-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpro.c
More file actions
1006 lines (827 loc) · 24.8 KB
/
cpro.c
File metadata and controls
1006 lines (827 loc) · 24.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "cpro.h"
Timestamp currenttime = 0;
char *CproDatabaseName = "";
bool enable_cpro = false;
struct timeval st,en;
static cprostorage cpro;
char read_buf[READ_BUF_MAX];
static volatile bool need_exit = false;
static volatile bool got_SIGHUP = false;
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(cpro_query);
PG_FUNCTION_INFO_V1(cpro_time);
PG_FUNCTION_INFO_V1(crosstab);
PG_FUNCTION_INFO_V1(what_is_cpro);
Size cprodbstat_memsize(void);
bool ReadCproFile(void);
bool beentryCheckState(PgBackendStatus *bs);
char *CurrentUserName(void);
char *parse_cpro_list(cprostorage *cpro);
char *timestamptz_2_str_en(TimestampTz t);
char *timestamptz_2_str_st(TimestampTz t);
int GetCpuNum(void);
long int GetCproTimeZone(void);
TimestampTz timestamp2timestamptz(Timestamp timestamp);
void CproWorkerMain(Datum arg);
void WriteCproFile(void);
void _PG_init(void);
void cleanupcproinfo(Relation heap,AttrNumber columnnum,TimestampTz currenttime);
void collect_cpro_info(cprostorage *cpro);
void cpro_info(cprostorage *cpro);
/* Basic Udf for cpro. Print Info About Cpro Analyzer. */
Datum
what_is_cpro(PG_FUNCTION_ARGS)
{
PG_RETURN_TEXT_P(cstring_to_text("Cpro - An Extension For Monitering CPU And Processes"));
}
void
_PG_init(void)
{
BackgroundWorker worker;
if (process_shared_preload_libraries_in_progress)
{
DefineCustomStringVariable(
"cpro.database_name",
gettext_noop("Databases to monitor"),
NULL,
&CproDatabaseName,
"postgres",
PGC_POSTMASTER,
GUC_SUPERUSER_ONLY,
NULL, NULL, NULL);
DefineCustomBoolVariable(
"cpro.enable_cpro",
"Determine wheather use cpro",
NULL,
&enable_cpro,
false,
PGC_POSTMASTER,
GUC_SUPERUSER_ONLY,
NULL,NULL,NULL);
EmitWarningsOnPlaceholders("cpro_db_stat");
RequestAddinShmemSpace(cprodbstat_memsize());
#if (PG_VERSION_NUM >= 90600)
RequestNamedLWLockTranche("cpro_db_stat", 1);
#else
RequestAddinLWLocks(1);
#endif
worker.bgw_flags = BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION;
worker.bgw_start_time = BgWorkerStart_RecoveryFinished;
worker.bgw_restart_time = 1;
#if (PG_VERSION_NUM < 100000)
worker.bgw_main = CproWorkerMain;
#endif
worker.bgw_main_arg = Int32GetDatum(0);
worker.bgw_notify_pid = 0;
sprintf(worker.bgw_library_name, "cpro");
sprintf(worker.bgw_function_name, "CproWorkerMain");
snprintf(worker.bgw_name, BGW_MAXLEN, "CeresDB Cpro Analyzer");
#if (PG_VERSION_NUM >= 110000)
snprintf(worker.bgw_type, BGW_MAXLEN, "CeresDB Cpro Analyzer");
#endif
RegisterBackgroundWorker(&worker);
}
else
{
ereport(ERROR, (errmsg("Cpro can only be loaded via shared_preload_libraries"),
errhint("Add cpro to shared_preload_libraries configuration "
"variable in postgres.conf in master and workers.")));
}
}
Size
cprodbstat_memsize(void)
{
Size size;
size = MAXALIGN(sizeof(cprodbstatSharedState));
return size;
}
void
WriteCproFile(void)
{
int fd, len;
StringInfo fpath,fcontent;
fpath = makeStringInfo();
fcontent = makeStringInfo();
appendStringInfo(fpath, "%s/cpro.stat", DataDir);
for (int i = 0; i < cpro.cpu_num ||
(appendStringInfo(fcontent, UINT64_FORMAT, cpro.cpro_arr[i]), 0);
appendStringInfo(fcontent, UINT64_FORMAT ",", cpro.cpro_arr[i++]));
/* Open Cpro File */
if ((fd = open(fpath -> data, O_CREAT|O_TRUNC|O_WRONLY,0777)) == -1)
{
ereport(ERROR, (errmsg("Can not open Cpro File in %s!", fpath -> data)));
}
/* Write Cpro File */
if ((len = write(fd, fcontent -> data, fcontent -> len)) == -1)
{
ereport(ERROR, (errmsg("Write Cpro File failed!")));
}
close(fd);
}
bool
ReadCproFile(void)
{
bool ret;
int fd, len, i = 0;
char *p;
StringInfo fpath = makeStringInfo();
appendStringInfo(fpath, "%s/cpro.stat", DataDir);
/* Open Cpro File */
if ((fd = open(fpath -> data, O_RDONLY)) == -1)
{
ereport(WARNING, (errmsg("Can not open Cpro File in %s!", fpath -> data)));
ret = false;
close(fd);
}
else /* file exists */
{
ret = true;
/* Read Cpro File */
if ((len = read(fd, read_buf, READ_BUF_MAX)) == -1)
{
ereport(ERROR, (errmsg("Read Cpro File failed!")));
}
close(fd);
/* Insert read_buf into struct cpro... */
p = strtok(read_buf, ",");
while (p)
{
cpro.cpro_arr[i++] = atoll(p);
p = strtok(NULL, ",");
}
cpro.cpro_arr[i] = atoll(read_buf);
remove(fpath -> data);
}
return ret;
}
static void
cprostat_exit(SIGNAL_ARGS)
{
int save_errno = errno;
need_exit = true;
SetLatch(MyLatch);
errno = save_errno;
}
/* SIGHUP handler for collector process */
static void
cprostat_sighup_handler(SIGNAL_ARGS)
{
int save_errno = errno;
got_SIGHUP = true;
SetLatch(MyLatch);
errno = save_errno;
}
static void
cpro_die(SIGNAL_ARGS)
{
PG_SETMASK(&BlockSig);
WriteCproFile();
ereport(FATAL,
(errcode(ERRCODE_ADMIN_SHUTDOWN),
errmsg("terminating background worker"
"\"%s\" due to administrator command",
MyBgworkerEntry->bgw_type)));
}
void
CproWorkerMain(Datum arg)
{
pqsignal(SIGHUP, cprostat_sighup_handler);
pqsignal(SIGINT, SIG_IGN);
pqsignal(SIGTERM, cpro_die);
pqsignal(SIGQUIT, cprostat_exit);
pqsignal(SIGALRM, SIG_IGN);
pqsignal(SIGPIPE, SIG_IGN);
pqsignal(SIGUSR1, SIG_IGN);
pqsignal(SIGUSR2, SIG_IGN);
pqsignal(SIGCHLD, SIG_IGN);
cpro.cpu_num = GetCpuNum();
cpro.cpro_arr = palloc(cpro.cpu_num * sizeof(uint64));
memset(read_buf, 0, READ_BUF_MAX);
if (!ReadCproFile())
for(int i = 0; i <= cpro.cpu_num; cpro.cpro_arr[i++] = 0);
gettimeofday(&st, NULL);
/* We're now ready to receive signals */
BackgroundWorkerUnblockSignals();
if(strcmp(CproDatabaseName,"") == 0)
{
proc_exit(0);
}
#if (PG_VERSION_NUM < 110000)
BackgroundWorkerInitializeConnection(CproDatabaseName, NULL);
#else
BackgroundWorkerInitializeConnection(CproDatabaseName, NULL, 0);
#endif
pgstat_report_appname("cpro analyzer");
for (;;)
{
MemoryContext CproLoopContext = NULL;
MemoryContext oldcontext = NULL;
sleep(1);
StartTransactionCommand();
CommitTransactionCommand();
CproLoopContext = AllocSetContextCreate(CurrentMemoryContext,
"cpro loop context",
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE);
oldcontext = MemoryContextSwitchTo(CproLoopContext);
StartTransactionCommand();
gettimeofday(&en,NULL);
cpro_info(&cpro);
/* store cpro every CPRO_MIN */
if (!((en.tv_sec - st.tv_sec) % CPRO_MIN))
{
currenttime = GetCurrentTimestamp();
/* Store cpro struct into table */
collect_cpro_info(&cpro);
}
/* Erase cpro struct every 24 hours. */
if(!((en.tv_sec + 8 * 3600) % CPRO_DAY))
for (int i = 0;i < cpro.cpu_num; cpro.cpro_arr[i++] = 0);
CommitTransactionCommand();
MemoryContextSwitchTo(oldcontext);
}
ereport(LOG, (errmsg("cpro analyzer shutting down")));
proc_exit(0);
}
void
cleanupcproinfo(Relation heap,AttrNumber columnnum,TimestampTz currenttime)
{
ScanKeyData scanKey;
HeapTuple tuple = NULL;
SysScanDesc scanDescriptor = NULL;
ScanKeyInit(&scanKey,columnnum, InvalidStrategy,
F_INT8LE,TimestampTzGetDatum(currenttime-86400000000*7));
scanDescriptor = systable_beginscan(heap,InvalidOid, false,NULL, 1, &scanKey);
while (HeapTupleIsValid(tuple = systable_getnext(scanDescriptor)))
{
simple_heap_delete(heap,&(tuple->t_self));
}
systable_endscan(scanDescriptor);
}
long int
GetCproTimeZone(void)
{
time_t t = time(NULL);
struct tm lt = {0};
localtime_r(&t, <);
return lt.tm_gmtoff;
}
void
collect_cpro_info(cprostorage *cpro)
{
Datum values[2];
bool nulls[2];
Oid cproInfoRelationId = InvalidOid;
Relation cproInfoTable = NULL;
HeapTuple tuple;
TupleDesc tupleDescriptor = NULL;
memset(values, 0, sizeof(values));
memset(nulls, 0, sizeof(nulls));
//values[0] = TimestampGetDatum(currenttime + (GetCproTimeZone() * 1000000));
values[0] = TimestampGetDatum(currenttime);
values[1] = CStringGetTextDatum(parse_cpro_list(cpro));
cproInfoRelationId = get_relname_relid("cpro_info", get_namespace_oid("cpro", false));
if (!OidIsValid(cproInfoRelationId))
ereport(ERROR,errmsg("can not find table cwc_snap"));
cproInfoTable = heap_open(cproInfoRelationId, RowExclusiveLock);
tupleDescriptor = RelationGetDescr(cproInfoTable);
tuple = heap_form_tuple(tupleDescriptor, values, nulls);
cleanupcproinfo(cproInfoTable,1,currenttime);
simple_heap_insert(cproInfoTable,tuple);
heap_close(cproInfoTable, RowExclusiveLock);
}
char *
parse_cpro_list(cprostorage *cpro)
{
StringInfoData *data = makeStringInfo();
appendStringInfo(data,"[");
for (int i = 0; i < cpro->cpu_num ||
(appendStringInfo(data,"{\"cpu_%d\":"
UINT64_FORMAT"}]", i, cpro -> cpro_arr[i]), 0) ;
(appendStringInfo(data,"{\"cpu_%d\":"UINT64_FORMAT"},",
i, cpro -> cpro_arr[i]),i++));
return data -> data;
}
void cpro_info(cprostorage *cpro)
{
int num_backends = pgstat_fetch_stat_numbackends();
int curr_backend;
for (curr_backend = 1; curr_backend <= num_backends; curr_backend++)
{
LocalPgBackendStatus *local_beentry;
PgBackendStatus *beentry;
proc_t *proc;
proc = palloc(sizeof(proc_t));
local_beentry = pgstat_fetch_stat_local_beentry(curr_backend);
if (local_beentry && beentryCheckState(&(local_beentry->backendStatus)))
{
beentry = &local_beentry -> backendStatus;
if (GetPidProcStat(beentry -> st_procpid, proc))
{
cpro -> cpro_arr[Int32GetDatum(proc->processor)]++;
ereport(DEBUG1, (errmsg("cpu_num:%d"
"\tpid:%ld"
"\tcpunum:%ld"
"\tst_state:%d",
cpro->cpu_num,
Int32GetDatum(beentry->st_procpid),
Int32GetDatum((proc->processor)),
beentry -> st_state)));
}
else
ereport(ERROR, (errmsg("%s",proc->errmsg)));
}
}
}
bool
beentryCheckState(PgBackendStatus *bs)
{
bool ret = false;
switch(bs -> st_state)
{
case STATE_UNDEFINED:
case STATE_IDLE:
ret = false;
break;
case STATE_RUNNING:
case STATE_IDLEINTRANSACTION:
case STATE_FASTPATH:
case STATE_IDLEINTRANSACTION_ABORTED:
case STATE_DISABLED:
ret = true;
break;
}
return ret;
}
int
GetCpuNum(void)
{
static char path[PATH_MAX], sbuf[32];
struct stat statbuf;
int ret = -1;
char *token;
sprintf(path, "/sys/devices/system/cpu/");
if (stat(path, &statbuf))
ereport(ERROR, errmsg("stat failed on %s,please check pid.", path));
if (file2str(path, "online", sbuf, sizeof sbuf) >= 0)
scanf("%s", sbuf);
else
ereport(ERROR,errmsg("stat failed on %s", path));
token = strtok(sbuf, "-");
token = strtok(NULL, "-");
if (token)
ret = atoi(token);
return ret;
}
Datum
cpro_query(PG_FUNCTION_ARGS)
{
#define CPRO_RETURN_COLS 4
ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
TupleDesc tupdesc;
MemoryContext per_query_ctx;
MemoryContext oldcontext;
Timestamp start = PG_ARGISNULL(0) ? 0 : PG_GETARG_TIMESTAMP(0);
Oid cproSchemaId = InvalidOid;
Oid cproSETJobRelationId = InvalidOid;
Relation cproSETJobsTable = NULL;
ScanKeyData scanKey;
TupleDesc tupleDescriptor = NULL;
HeapTuple tuple;
Tuplestorestate *tupleOut;
TableScanDesc scandesc;
per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
oldcontext = MemoryContextSwitchTo(per_query_ctx);
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
elog(ERROR, "return type must be a row type");
if (!start)
ereport(ERROR, (errmsg("Input Value Can Not Be NULL!")));
tupleOut = tuplestore_begin_heap(true, false, work_mem);
rsinfo->returnMode = SFRM_Materialize;
rsinfo->setResult = tupleOut;
rsinfo->setDesc = tupdesc;
MemoryContextSwitchTo(oldcontext);
cproSchemaId = get_namespace_oid("cpro", false);
cproSETJobRelationId = get_relname_relid("cpro_info", cproSchemaId);
if (!OidIsValid(cproSETJobRelationId))
{
elog(ERROR, "can not find table cpro_info");
}
cproSETJobsTable = heap_open(cproSETJobRelationId, AccessShareLock);
ScanKeyInit(&scanKey, 1,
InvalidStrategy, F_TIMESTAMP_EQ,
TimestampGetDatum(start));
scandesc = table_beginscan_catalog(cproSETJobsTable, 1, &scanKey);
tupleDescriptor = RelationGetDescr(cproSETJobsTable);
if (HeapTupleIsValid(tuple = heap_getnext(scandesc, ForwardScanDirection)))
{
bool isNull = false;
Datum input_time, cpro_array;
Timestamp out_time;
char *cproJsonb;
module *mod;
Datum values[CPRO_RETURN_COLS];
bool nulls[CPRO_RETURN_COLS];
CListCell *e;
memset(values, 0, sizeof(values));
memset(nulls, 0, sizeof(nulls));
input_time = heap_getattr(tuple, 1, tupleDescriptor, &isNull);
cpro_array = heap_getattr(tuple, 2, tupleDescriptor, &isNull);
out_time = DatumGetTimestamp(input_time);
cproJsonb = TextDatumGetCString(cpro_array);
mod = new_module_from_string(cproJsonb);
if (!parse_module(mod))
{
/* TO DO ... */
if (mod -> cpro)
{
cforeach (e, mod -> cpro -> cproList)
{
CproList *cprl = (CproList *) clfirst(e);
values[0] = TimestampGetDatum(out_time);
values[1] = Int64GetDatum(cprl -> pidnum);
values[2] = Int32GetDatum(cprl -> cpunum);
ereport(DEBUG1, errmsg("%ld,%ld,%d", out_time, cprl -> pidnum, cprl -> cpunum));
tuplestore_putvalues(tupleOut, tupdesc, values, nulls);
}
}
}
delete_cpro_module(mod);
}
tuplestore_donestoring(tupleOut);
table_endscan(scandesc);
heap_close(cproSETJobsTable, AccessShareLock);
return (Datum) 0;
}
static bool
compatCrosstabTupleDescs(TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
{
Form_pg_attribute ret_attr;
Form_pg_attribute sql_attr;
Oid sql_atttypid;
Oid ret_atttypid;
if (ret_tupdesc -> natts < 2 ||
sql_tupdesc -> natts < 3)
return false;
/* check the rowid types match */
ret_atttypid = TupleDescAttr(ret_tupdesc, 0) -> atttypid;
sql_atttypid = TupleDescAttr(sql_tupdesc, 0) -> atttypid;
if (ret_atttypid != sql_atttypid)
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("invalid return type"),
errdetail("SQL rowid datatype does not match "
"return rowid datatype.")));
sql_attr = TupleDescAttr(sql_tupdesc, 2);
for (int i = 1; i < ret_tupdesc->natts; i++)
{
ret_attr = TupleDescAttr(ret_tupdesc, i);
if (ret_attr -> atttypid != sql_attr->atttypid)
return false;
}
/* the two tupdescs are compatible for our purposes */
return true;
}
Datum
crosstab(PG_FUNCTION_ARGS)
{
char *sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
Tuplestorestate *tupstore;
TupleDesc tupdesc;
uint64 call_cntr;
uint64 max_calls;
AttInMetadata *attinmeta;
SPITupleTable *spi_tuptable;
TupleDesc spi_tupdesc;
bool firstpass;
char *lastrowid;
int num_categories;
MemoryContext per_query_ctx;
MemoryContext oldcontext;
int ret;
uint64 proc;
if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("set-valued function called in context that cannot accept a set")));
if (!(rsinfo->allowedModes & SFRM_Materialize))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("materialize mode required, but it is not "
"allowed in this context")));
per_query_ctx = rsinfo -> econtext -> ecxt_per_query_memory;
/* Connect to SPI manager */
if ((ret = SPI_connect()) < 0)
/* internal error */
ereport(ERROR, (errmsg("crosstab: SPI_connect returned %d", ret)));
/* Retrieve the desired rows */
ret = SPI_execute(sql, true, 0);
proc = SPI_processed;
/* If no qualifying tuples, fall out early */
if (ret != SPI_OK_SELECT || proc == 0)
{
SPI_finish();
rsinfo -> isDone = ExprEndResult;
PG_RETURN_NULL();
}
spi_tuptable = SPI_tuptable;
spi_tupdesc = spi_tuptable -> tupdesc;
if (spi_tupdesc -> natts != 3)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid source data SQL statement"),
errdetail("The provided SQL must return 3 "
"columns: rowid, category, and values.")));
/* get a tuple descriptor for our result type */
switch (get_call_result_type(fcinfo, NULL, &tupdesc))
{
case TYPEFUNC_COMPOSITE:
/* success */
break;
case TYPEFUNC_RECORD:
/* failed to determine actual type of RECORD */
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
break;
default:
/* result type isn't composite */
ereport(ERROR,
(errcode(ERRCODE_DATATYPE_MISMATCH),
errmsg("return type must be a row type")));
break;
}
if (!compatCrosstabTupleDescs(tupdesc, spi_tupdesc))
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("return and sql tuple descriptions are "
"incompatible")));
oldcontext = MemoryContextSwitchTo(per_query_ctx);
tupdesc = CreateTupleDescCopy(tupdesc);
tupstore =
tuplestore_begin_heap(rsinfo->allowedModes & SFRM_Materialize_Random,
false, work_mem);
MemoryContextSwitchTo(oldcontext);
attinmeta = TupleDescGetAttInMetadata(tupdesc);
max_calls = proc;
num_categories = tupdesc->natts - 1;
firstpass = true;
lastrowid = NULL;
for (call_cntr = 0; call_cntr < max_calls; call_cntr++)
{
bool skip_tuple = false;
char **values;
/* allocate and zero space */
values = (char **) palloc0((1 + num_categories) * sizeof(char *));
for (int i = 0; i < num_categories; i++)
{
HeapTuple spi_tuple;
char *rowid;
/* see if we've gone too far already */
if (call_cntr >= max_calls)
break;
/* get the next sql result tuple */
spi_tuple = spi_tuptable->vals[call_cntr];
/* get the rowid from the current sql result tuple */
rowid = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
if (i == 0)
{
xpstrdup(values[0], rowid);
if (!firstpass && xstreq(lastrowid, rowid))
{
xpfree(rowid);
skip_tuple = true;
break;
}
}
if (xstreq(rowid, values[0]))
{
values[1 + i] = SPI_getvalue(spi_tuple, spi_tupdesc, 3);
if (i < (num_categories - 1))
call_cntr++;
xpfree(rowid);
}
else
{
call_cntr--;
xpfree(rowid);
break;
}
}
if (!skip_tuple)
{
HeapTuple tuple;
tuple = BuildTupleFromCStrings(attinmeta, values);
tuplestore_puttuple(tupstore, tuple);
heap_freetuple(tuple);
}
xpfree(lastrowid);
xpstrdup(lastrowid, values[0]);
firstpass = false;
for (int i = 0; i < num_categories + 1; i++)
if (values[i] != NULL)
pfree(values[i]);
pfree(values);
}
/* let the caller know we're sending back a tuplestore */
rsinfo->returnMode = SFRM_Materialize;
rsinfo->setResult = tupstore;
rsinfo->setDesc = tupdesc;
/* release SPI related resources (and return to caller's context) */
SPI_finish();
return (Datum) 0;
}
char *
CurrentUserName(void)
{
Oid userId = GetUserId();
return GetUserNameFromId(userId, false);
}
TimestampTz
timestamp2timestamptz(Timestamp timestamp)
{
TimestampTz result;
struct pg_tm tt,
*tm = &tt;
fsec_t fsec;
int tz;
if (TIMESTAMP_NOT_FINITE(timestamp))
result = timestamp;
else
{
if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
tz = DetermineTimeZoneOffset(tm, session_timezone);
if (tm2timestamp(tm, fsec, &tz, &result) != 0)
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
}
return result;
}
char *
timestamptz_2_str_st(TimestampTz t)
{
static char buf[MAXDATELEN + 1];
int tz;
struct pg_tm tt,
*tm = &tt;
fsec_t fsec;
const char *tzn;
if (TIMESTAMP_NOT_FINITE(t))
EncodeSpecialTimestamp(t, buf);
else if (timestamp2tm(t, &tz, tm, &fsec, &tzn, NULL) == 0)
EncodeDateTime(tm, fsec, true, tz, tzn, USE_ISO_DATES, buf);
else
strlcpy(buf, "(timestamp out of range)", sizeof(buf));
return buf;
}
char *
timestamptz_2_str_en(TimestampTz t)
{
static char buf[MAXDATELEN + 1];
int tz;
struct pg_tm tt,
*tm = &tt;
fsec_t fsec;
const char *tzn;
if (TIMESTAMP_NOT_FINITE(t))
EncodeSpecialTimestamp(t, buf);
else if (timestamp2tm(t, &tz, tm, &fsec, &tzn, NULL) == 0)
EncodeDateTime(tm, fsec, true, tz, tzn, USE_ISO_DATES, buf);
else
strlcpy(buf, "(timestamp out of range)", sizeof(buf));
return buf;
}
Datum
cpro_time(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
Timestamp start = PG_ARGISNULL(0) ? -1 : PG_GETARG_TIMESTAMP(0);
Timestamp end = PG_ARGISNULL(0) ? -1 : PG_GETARG_TIMESTAMP(1);
TimestampTz ss,en;
int call_cntr, max_calls, tupleCount, ret;
TupleDesc tupdesc;
AttInMetadata *attinmeta;
char ***values;
PGconn *conn = NULL;
PGresult *result = NULL;
StringInfo data = makeStringInfo();
ss = timestamp2timestamptz(start);
en = timestamp2timestamptz(end);
if (start >= end)
ereport(ERROR, (errmsg("Usage: cpro_time(start_time, end_time)\n"
"\t start_time must by ahead of end_time!")));
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
appendStringInfo(data,PG_CONNECT_PARAMS,PostPortNumber,
CurrentUserName(),get_database_name(MyDatabaseId));
conn = PQconnectdb(data->data);
ret = PQstatus(conn);
if (ret != CONNECTION_OK)
ereport(ERROR,(errmsg("%s",conn->errorMessage.data)));
result = PQexec(conn,"BEGIN;");
ret = PQresultStatus(result);
if (ret != PGRES_COMMAND_OK)
ereport(ERROR,(errmsg("begin transaction failed")));
resetStringInfo(data);
appendStringInfo(data,"SELECT cpro.cpu_num, "
"COALESCE(cpro.category_2,0) AS cap_time1, "
"COALESCE(cpro.category_1,0) AS cap_time2, "
"ABS(COALESCE(cpro.category_1,0) - COALESCE(cpro.category_2,0)) AS pid_variation "
"FROM (SELECT CAST(row_name AS INT) AS cpu_num, "
"CAST(category_1 AS INT), CAST(category_2 AS INT) "
"FROM crosstab2(\'SELECT CAST(cpu_num AS TEXT), "
"CAST(cap_time AS TEXT), "
"CAST(pid_num AS TEXT) "
"FROM (SELECT cpu_num,cap_time,pid_num "
"FROM cpro_query(\'\'%s\'\') ) AS a "
"UNION SELECT CAST(cpu_num AS TEXT), "
"CAST(cap_time AS TEXT), "
"CAST(pid_num AS TEXT) "
"FROM (SELECT cpu_num,cap_time,pid_num FROM "
"cpro_query(\'\'%s\'\') ) AS b ORDER BY 1,2 DESC;\') "
") AS cpro ORDER BY cpro.cpu_num;",
timestamptz_2_str_st(ss), timestamptz_2_str_en(en));
elog(DEBUG1,"-> %s",data->data);
result = PQexec(conn,data->data);
ret = PQresultStatus(result);
if (ret != PGRES_TUPLES_OK)
{
result = PQexec(conn,"ROLLBACK;");
ret = PQresultStatus(result);
if (ret == PGRES_COMMAND_OK)
ereport(ERROR,(errmsg("select failed")));
}
tupleCount = PQntuples(result);
if(tupleCount < 0)
{
result = PQexec(conn,"ROLLBACK;");
ret = PQresultStatus(result);
if (ret == PGRES_COMMAND_OK)
ereport(ERROR,(errmsg("select failed")));
}
funcctx->max_calls = tupleCount;
max_calls = funcctx->max_calls;
values = (char ***) calloc(max_calls,sizeof(char **));
for (int i = 0;i < max_calls;i++)
{
values[i] = (char **) calloc(12,sizeof(char *));
for (int j = 0;j < CPRO_RETURN_COLS;j++)
{
values[i][j] = (char *) calloc(128,sizeof(char));
if (PQgetvalue(result,i,j) == NULL)
values[i][j] = NULL;
else if (!strcmp(PQgetvalue(result,i,j),""))
strcpy(values[i][j],"0");
else
strcpy(values[i][j],PQgetvalue(result,i,j));
}
}
result = PQexec(conn,"COMMIT;");
ret = PQresultStatus(result);
if (ret != PGRES_COMMAND_OK)
{
result = PQexec(conn,"ROLLBACK;");
ret = PQresultStatus(result);
if (ret == PGRES_COMMAND_OK)
ereport(ERROR,(errmsg("commit transaction failed")));
}
PQclear(result);
PQfinish(conn);
attinmeta = TupleDescGetAttInMetadata(tupdesc);
funcctx->attinmeta = attinmeta;
funcctx->user_fctx = values;
MemoryContextSwitchTo(oldcontext);
}
funcctx = SRF_PERCALL_SETUP();
call_cntr = funcctx->call_cntr;
max_calls = funcctx->max_calls;
attinmeta = funcctx->attinmeta;
values = funcctx->user_fctx;
if (call_cntr < max_calls)
{
Datum result2;
HeapTuple tuple;
tuple = BuildTupleFromCStrings(attinmeta, values[call_cntr]);
result2 = HeapTupleGetDatum(tuple);
SRF_RETURN_NEXT(funcctx, result2);