-
Notifications
You must be signed in to change notification settings - Fork 225
/
Copy pathsqlanalyze.c
1494 lines (1252 loc) · 41.6 KB
/
sqlanalyze.c
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
/*
Copyright 2015 Bloomberg Finance L.P.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <comdb2.h>
#include <strings.h>
#include <assert.h>
#include <limits.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <inttypes.h>
#include <pthread.h>
#include <unistd.h>
#include <epochlib.h>
#include "analyze.h"
#include "sql.h"
#include <sqliteInt.h>
#include "block_internal.h"
#include <thread_malloc.h>
#include <autoanalyze.h>
#include <bdb_schemachange.h>
#include <sqlstat1.h>
#include <sqloffload.h>
#include <comdb2_atomic.h>
#include <ctrace.h>
#include <logmsg.h>
#include "str0.h"
#include "sc_util.h"
#include "debug_switches.h"
/* amount of thread-memory initialized for this thread */
#ifndef PER_THREAD_MALLOC
static int analyze_thread_memory = 1048576;
#endif
extern void reset_aa_counter(char *tblname);
/* global is-running flag */
uint32_t analyze_running_flag = 0;
static int analyze_abort_requested = 0;
/* global enable / disable switch */
static int sampled_tables_enabled = 1;
/* sampling threshold defaults to 100 Mb */
long long sampling_threshold = 104857600;
/* hard-maximum number of analyze-table threads */
static int analyze_hard_max_table_threads = 15;
/* maximum number of analyze-table threads */
int analyze_max_table_threads = 5;
/* current number of analyze-sampling threads */
static int analyze_cur_table_threads = 0;
/* maximum number of analyze-sampling threads */
static int analyze_hard_max_comp_threads = 40;
/* maximum number of analyze-sampling threads */
int analyze_max_comp_threads = 10;
/* current number of analyze-sampling threads */
static int analyze_cur_comp_threads = 0;
/* table-thread mutex */
static pthread_mutex_t table_thd_mutex = PTHREAD_MUTEX_INITIALIZER;
/* table-thread cond */
static pthread_cond_t table_thd_cond = PTHREAD_COND_INITIALIZER;
/* comp-thread mutex */
static pthread_mutex_t comp_thd_mutex = PTHREAD_MUTEX_INITIALIZER;
/* comp-thread cond */
static pthread_cond_t comp_thd_cond = PTHREAD_COND_INITIALIZER;
/* comp-state enum */
enum {
SAMPLING_NOTINITED = 0,
SAMPLING_STARTUP = 1,
SAMPLING_RUNNING = 2,
SAMPLING_COMPLETE = 3,
SAMPLING_ERROR = 4
};
/* table-state enum */
enum {
TABLE_NOTINITED = 0,
TABLE_STARTUP = 1,
TABLE_RUNNING = 2,
TABLE_COMPLETE = 3,
TABLE_FAILED = 4,
TABLE_SKIPPED = 5
};
/* index-descriptor */
typedef struct index_descriptor {
pthread_t thread_id;
int comp_state;
sampled_idx_t *s_ix;
struct dbtable *tbl;
int ix;
int sampling_pct;
} index_descriptor_t;
/* table-descriptor */
typedef struct table_descriptor {
pthread_t thread_id;
int table_state;
char table[MAXTABLELEN];
SBUF2 *sb;
int scale;
int override_llmeta;
index_descriptor_t index[MAXINDEX];
struct user current_user;
void *appdata;
void *get_authdata;
} table_descriptor_t;
/* loadStat4 (analyze.c) will ignore all stat entries
* which have "tbl like 'cdb2.%' */
int backout_stats_frm_tbl(struct sqlclntstate *clnt, const char *table,
int stattbl)
{
char *sql = NULL;
sql = sqlite3_mprintf(
"delete from sqlite_stat%d where tbl='%q' and exists (select tbl from "
"sqlite_stat%d where tbl='cdb2.%q.sav')",
stattbl, table, stattbl, table);
assert(sql != NULL);
int rc = run_internal_sql_clnt(clnt, sql);
sqlite3_free(sql); sql = NULL;
if (rc)
return rc;
sql = sqlite3_mprintf(
"update sqlite_stat%d set tbl='%q' where tbl='cdb2.%q.sav'",
stattbl, table, table);
assert(sql != NULL);
rc = run_internal_sql_clnt(clnt, sql);
sqlite3_free(sql); sql = NULL;
return rc;
}
/* Create an sql machine & run an analyze command. */
static int run_sql_part_trans(sqlite3 *sqldb, struct sqlclntstate *client,
char *sql, int *changes)
{
int rc;
char *msg;
/* set sql and analyze flavor */
client->sql = sql;
/* set thread info */
struct sql_thread *thd = pthread_getspecific(query_info_key);
sql_get_query_id(thd);
/* run sql */
rc = sqlite3_exec(sqldb, sql, NULL, NULL, &msg);
if (rc) {
logmsg(LOGMSG_ERROR, "Analyze failure rc %d: %s\n", rc,
msg ? msg : "<unknown error>");
return rc;
}
if (changes != NULL)
*changes = sqlite3_changes(sqldb);
return rc;
}
static int check_stat1_and_flag(SBUF2 *sb)
{
/* verify sqlite_stat1 */
if (NULL == get_dbtable_by_name("sqlite_stat1")) {
sbuf2printf(sb, "?%s: analyze requires sqlite_stat1 to run\n",
__func__);
sbuf2printf(sb, "FAILED\n");
logmsg(LOGMSG_ERROR, "%s: analyze requires sqlite_stat1 to run\n", __func__);
return -1;
}
/* check if its already running */
if (analyze_running_flag) {
sbuf2printf(sb, "?%s: analyze is already running\n", __func__);
sbuf2printf(sb, "FAILED\n");
logmsg(LOGMSG_ERROR, "%s: analyze is already running\n", __func__);
return -1;
}
return 0;
}
void cleanup_stats(SBUF2 *sb)
{
struct sqlclntstate clnt;
start_internal_sql_clnt(&clnt);
if (get_dbtable_by_name("sqlite_stat1")) {
run_internal_sql_clnt(&clnt,
"delete from sqlite_stat1 where idx is null");
run_internal_sql_clnt(&clnt, "delete from sqlite_stat1 where idx not "
"in (select name from sqlite_master where "
"type='index')");
}
if (get_dbtable_by_name("sqlite_stat2"))
run_internal_sql_clnt(&clnt, "delete from sqlite_stat2 where idx not "
"in (select name from sqlite_master where "
"type='index')");
if (get_dbtable_by_name("sqlite_stat4"))
run_internal_sql_clnt(&clnt, "delete from sqlite_stat4 where idx not "
"in (select name from sqlite_master where "
"type='index' UNION select "
"'cdb2.'||name||'.sav' from sqlite_master "
"where type='index')");
end_internal_sql_clnt(&clnt);
}
/* returns the index or NULL */
static sampled_idx_t *find_sampled_index(struct sqlclntstate *client,
char *table, int ix)
{
int i;
/* punt if this wasn't sampled */
if (NULL == client->sampled_idx_tbl || client->n_cmp_idx <= 0) {
return NULL;
}
/* search for table / index */
for (i = 0; i < client->n_cmp_idx; i++) {
sampled_idx_t *s_ix = &(client->sampled_idx_tbl[i]);
if (!strcmp(table, s_ix->name) && ix == s_ix->ixnum) {
return &client->sampled_idx_tbl[i];
}
}
return NULL;
}
/* sample (previously misnamed compress) this index */
static int sample_index_int(index_descriptor_t *ix_des)
{
sampled_idx_t *s_ix = ix_des->s_ix;
struct dbtable *tbl = ix_des->tbl;
int sampling_pct = ix_des->sampling_pct;
int ix = ix_des->ix;
int rc;
int bdberr;
unsigned long long n_recs;
unsigned long long n_sampled_recs;
sampler_t *sampler = NULL;
/* cache the tablename for sqlglue */
strncpy0(s_ix->name, tbl->tablename, sizeof(s_ix->name));
/* ask bdb to put a summary of this into a temp-table */
rc = bdb_summarize_table(tbl->handle, ix, sampling_pct, &sampler,
&n_sampled_recs, &n_recs, &bdberr);
/* failed */
if (rc) {
logmsg(LOGMSG_ERROR, "%s: failed to sample table '%s' idx %d\n",
__func__, tbl->tablename, ix);
return -1;
}
/* fill in structure */
s_ix->ixnum = ix;
s_ix->sampler = sampler;
s_ix->sampling_pct = sampling_pct;
s_ix->n_recs = n_recs;
s_ix->n_sampled_recs = n_sampled_recs;
return 0;
}
/* spawn a thread to sample an index */
static void *sampling_thread(void *arg)
{
comdb2_name_thread(__func__);
int rc;
index_descriptor_t *ix_des = (index_descriptor_t *)arg;
/* register thread */
thrman_register(THRTYPE_ANALYZE);
backend_thread_event(thedb, COMDB2_THR_EVENT_START_RDWR);
/* update state */
ix_des->comp_state = SAMPLING_RUNNING;
/* sample the index */
rc = sample_index_int(ix_des);
/* mark the return */
if (0 == rc) {
ix_des->comp_state = SAMPLING_COMPLETE;
} else {
ix_des->comp_state = SAMPLING_ERROR;
}
/* release the thread */
Pthread_mutex_lock(&comp_thd_mutex);
analyze_cur_comp_threads--;
Pthread_cond_broadcast(&comp_thd_cond);
Pthread_mutex_unlock(&comp_thd_mutex);
/* cleanup */
backend_thread_event(thedb, COMDB2_THR_EVENT_DONE_RDWR);
return NULL;
}
/* dispatch a thread to sample this index */
static int dispatch_sample_index_thread(index_descriptor_t *ix_des)
{
/* grab lock */
Pthread_mutex_lock(&comp_thd_mutex);
/* wait for sampling thread availability */
while (analyze_cur_comp_threads >= analyze_max_comp_threads) {
Pthread_cond_wait(&comp_thd_cond, &comp_thd_mutex);
}
/* grab sampling thread */
analyze_cur_comp_threads++;
/* release */
Pthread_mutex_unlock(&comp_thd_mutex);
/* dispatch */
int rc = pthread_create(&ix_des->thread_id, &gbl_pthread_attr_detached,
sampling_thread, ix_des);
/* return */
return rc;
}
/* wait for an index to complete */
static int wait_for_index(index_descriptor_t *ix_des)
{
/* lock index mutex */
Pthread_mutex_lock(&comp_thd_mutex);
/* wait for the state to change */
while (ix_des->comp_state == SAMPLING_STARTUP ||
ix_des->comp_state == SAMPLING_RUNNING) {
Pthread_cond_wait(&comp_thd_cond, &comp_thd_mutex);
}
/* release */
Pthread_mutex_unlock(&comp_thd_mutex);
return 0;
}
/* sample all indicies in this table */
static int sample_indicies(table_descriptor_t *td, struct sqlclntstate *client,
struct dbtable *tbl, int sampling_pct, SBUF2 *sb)
{
int i;
int err = 0;
char *table;
index_descriptor_t *ix_des;
/* find table to backout */
table = tbl->tablename;
/* allocate cmp_idx */
client->sampled_idx_tbl = calloc(tbl->nix, sizeof(sampled_idx_t));
if (!client->sampled_idx_tbl) {
logmsg(LOGMSG_ERROR, "%s: out of memory\n", __func__);
return -1;
}
/* set # sampled ixs */
client->n_cmp_idx = tbl->nix;
/* sample indicies */
for (i = 0; i < client->n_cmp_idx; i++) {
/* prepare index descriptor */
ix_des = &td->index[i];
ix_des->comp_state = SAMPLING_STARTUP;
ix_des->s_ix = &client->sampled_idx_tbl[i];
ix_des->tbl = tbl;
ix_des->ix = i;
ix_des->sampling_pct = sampling_pct;
/* start an index sampling thread */
int rc = dispatch_sample_index_thread(ix_des);
if (0 != rc) {
logmsg(LOGMSG_ERROR, "Couldn't start sampling-thread for table '%s' ix %d "
"rc=%d\n",
table, i, rc);
err = 1;
break;
}
}
/* wait for them to complete */
for (i = 0; i < client->n_cmp_idx; i++) {
wait_for_index(&td->index[i]);
if (SAMPLING_COMPLETE != td->index[i].comp_state)
err = 1;
}
return err;
}
/* clean up */
static int cleanup_sampled_indicies(struct sqlclntstate *client, struct dbtable *tbl)
{
int i;
/* delete sampled temptables */
for (i = 0; i < client->n_cmp_idx; i++) {
sampled_idx_t *s_ix = &client->sampled_idx_tbl[i];
if (!s_ix)
continue;
}
/* free & zero struct */
free(client->sampled_idx_tbl);
client->sampled_idx_tbl = NULL;
return 0;
}
/* Return the requested sampler */
sampler_t *analyze_get_sampler(struct sqlclntstate *client, char *table,
int idx)
{
sampled_idx_t *s_ix;
s_ix = find_sampled_index(client, table, idx);
if (!s_ix)
return NULL;
return s_ix->sampler;
}
/* Called from sqlite. Return the number of records for a sampled table */
int64_t analyze_get_nrecs(int iTable)
{
struct sql_thread *thd;
struct sqlclntstate *client;
struct dbtable *db;
sampled_idx_t *s_ix;
int ixnum;
unsigned long long n_recs;
/* get client structures */
thd = pthread_getspecific(query_info_key);
client = thd->clnt;
/* comdb2-ize table-num and ixnum */
db = get_sqlite_db(thd, iTable, &ixnum);
assert(db);
/* grab sampled table descriptor */
s_ix = find_sampled_index(client, db->tablename, ixnum);
/* return -1 if not sampled. Sqlite will use the value it calculated. */
if (!s_ix) {
return -1;
}
/* grab actual number of records */
n_recs = s_ix->n_recs;
/* boundry check return code */
assert( n_recs>=0 );
assert( n_recs<=LLONG_MAX );
/* return actual number of records */
return (int64_t)n_recs;
}
/* Return the number of records sampled for an index */
int64_t analyze_get_sampled_nrecs(const char *dbname, int ixnum)
{
struct sql_thread *thd;
struct sqlclntstate *client;
unsigned long long n_sampled_recs;
/* get client structures */
thd = pthread_getspecific(query_info_key);
client = thd->clnt;
/* Punt if this wasn't sampled. */
if (NULL == client->sampled_idx_tbl || client->n_cmp_idx <= 0) {
return -1;
}
assert(0 <= ixnum && ixnum < client->n_cmp_idx);
/* grab actual number of sampled records */
n_sampled_recs = client->sampled_idx_tbl[ixnum].n_sampled_recs;
/* boundry check return code */
assert( n_sampled_recs>=0 );
assert( n_sampled_recs<=LLONG_MAX );
/* return actual number of sampled records */
return (int64_t)n_sampled_recs;
}
/* Return 1 if we have this sampled index, 0 otherwise */
int analyze_is_sampled(struct sqlclntstate *client, char *table, int idx)
{
sampled_idx_t *s_ix;
s_ix = find_sampled_index(client, table, idx);
return (NULL != s_ix);
}
static int local_replicate_write_analyze(char *table)
{
int rc;
tran_type *trans = NULL;
long long seqno;
int nretries = 0;
struct ireq iq;
int arc;
struct block_state blkstate = {0};
/* skip if not needed */
if (gbl_replicate_local == 0 || get_dbtable_by_name("comdb2_oplog") == NULL)
return 0;
init_fake_ireq(thedb, &iq);
iq.blkstate = &blkstate;
again:
nretries++;
if (trans) {
arc = trans_abort(&iq, trans);
if (arc) {
logmsg(LOGMSG_ERROR, "Analyze: trans_abort rc %d\n", arc);
trans = NULL;
goto done;
}
trans = NULL;
}
if (nretries > gbl_maxretries)
return RC_INTERNAL_RETRY;
rc = trans_start(&iq, NULL, &trans);
if (rc) {
logmsg(LOGMSG_ERROR, "analyze: trans_start rc %d\n", rc);
goto done;
}
if (gbl_replicate_local_concurrent) {
unsigned long long useqno;
useqno = bdb_get_timestamp(thedb->bdb_env);
memcpy(&seqno, &useqno, sizeof(seqno));
} else
rc = get_next_seqno(trans, NULL, &seqno);
if (rc) {
if (rc != RC_INTERNAL_RETRY) {
logmsg(LOGMSG_ERROR, "get_next_seqno unexpected rc %d\n", rc);
goto done;
} else
goto again;
}
iq.blkstate->seqno = seqno;
iq.blkstate->pos = 0;
rc = add_oplog_entry(&iq, trans, LCL_OP_ANALYZE, table, strlen(table));
if (rc == RC_INTERNAL_RETRY)
goto again;
if (rc) {
logmsg(LOGMSG_ERROR, "analyze: add_oplog_entry(analyze) rc %d\n", rc);
goto done;
}
iq.blkstate->seqno = seqno;
iq.blkstate->pos = 1;
rc = add_oplog_entry(&iq, trans, LCL_OP_COMMIT, NULL, 0);
if (rc == RC_INTERNAL_RETRY)
goto again;
if (rc) {
logmsg(LOGMSG_ERROR, "analyze: add_oplog_entry(commit) rc %d\n", rc);
goto done;
}
rc = trans_commit(&iq, trans, gbl_myhostname);
trans = NULL;
if (rc) {
logmsg(LOGMSG_ERROR, "analyze: commit rc %d\n", rc);
goto done;
}
done:
if (trans) {
arc = trans_abort(&iq, trans);
if (arc)
logmsg(LOGMSG_ERROR, "analyze: trans_abort rc %d\n", arc);
}
return rc;
}
/* get tbl sampling threshold, if NOT -1 set it
*/
static void get_sampling_threshold(char *table, long long *sampling_thresh)
{
int bdberr = 0;
long long threshold = 0;
bdb_get_analyzethreshold_table(NULL, table, &threshold, &bdberr);
#ifdef DEBUG
printf("retrieving from llmeta saved threshold for table '%s': %lld\n",
table, threshold);
#endif
if (threshold > 0) {
*sampling_thresh = threshold;
#ifdef DEBUG
printf("Using llmetasaved threshold %lld\n", *sampling_thresh);
}
else {
printf("Using default threshold %lld\n", *sampling_thresh);
#endif
}
}
/* get coverage value saved in llmeta for table
* if value is not saved in llmeta, will not modify scale
*/
static void get_saved_scale(char *table, int *scale)
{
int bdberr = 0;
int coveragevalue = 0;
bdb_get_analyzecoverage_table(NULL, table, &coveragevalue, &bdberr);
#ifdef DEBUG
printf("retrieving from llmeta saved coverage for table '%s': %d\n", table,
coveragevalue);
#endif
if (coveragevalue >= 0 && coveragevalue <= 100) {
*scale = coveragevalue;
}
}
int delete_sav(sqlite3 *sqldb, struct sqlclntstate *client, SBUF2 *sb,
int stat_tbl, const char *table)
{
char *sql = NULL;
int more = 1;
int rc = 0;
sql = sqlite3_mprintf(
"delete from sqlite_stat%d where tbl='cdb2.%q.sav'",
stat_tbl, table);
assert(sql != NULL);
#ifdef DEBUG
printf("query '%s'\n", sql);
#endif
if ( (rc = run_sql_part_trans( sqldb, client, sql, &more)) != 0) {
logmsg(LOGMSG_ERROR, "delete sav failed");
sqlite3_free(sql); sql = NULL;
return rc;
}
#ifdef DEBUG
printf("deleted %d from tbl='cdb2.%s.sav'\n", more, table);
#endif
sqlite3_free(sql); sql = NULL;
return 0;
}
int update_sav(sqlite3 *sqldb, struct sqlclntstate *client, SBUF2 *sb,
int stat_tbl, const char *table)
{
char *sql = NULL;
int more = 1;
int rc = 0;
sql = sqlite3_mprintf(
"update sqlite_stat%d set tbl='cdb2.%q.sav' where tbl='%q'",
stat_tbl, table, table);
#ifdef DEBUG
printf("query '%s'\n", sql);
#endif
if ( (rc = run_sql_part_trans( sqldb, client, sql, &more)) != 0) {
logmsg(LOGMSG_ERROR, "update sav failed");
sqlite3_free(sql); sql = NULL;
return rc;
}
#ifdef DEBUG
printf("updated %d from tbl='cdb2.%s.sav'\n", more, table);
#endif
sqlite3_free(sql); sql = NULL;
return 0;
}
static int analyze_table_int(table_descriptor_t *td,
struct thr_handle *thr_self)
{
char zErrTab[256] = {0};
#ifdef DEBUG
printf("analyze_table_int() table '%s': scale %d\n", td->table, td->scale);
#endif
/* make sure we can find this table */
struct dbtable *tbl = get_dbtable_by_name(td->table);
if (!tbl) {
sbuf2printf(td->sb, "?Cannot find table '%s'\n", td->table);
return -1;
}
if (td->override_llmeta == 0) // user did not specify override parameter
get_saved_scale(td->table, &td->scale);
if (td->scale == 0) {
sbuf2printf(td->sb, "?Coverage for table '%s' is 0, skipping analyze\n",
td->table);
logmsg(LOGMSG_INFO, "coverage for table '%s' is 0, skipping analyze\n", td->table);
return TABLE_SKIPPED;
}
struct sqlclntstate clnt;
start_internal_sql_clnt(&clnt);
clnt.osql_max_trans = 0; // allow large transactions
int sampled_table = 0;
clnt.current_user = td->current_user;
if (td->appdata != NULL)
clnt.appdata = td->appdata;
if (td->get_authdata != NULL)
clnt.plugin.get_authdata = td->get_authdata;
logmsg(LOGMSG_INFO, "Analyze thread starting, table %s (%d%%)\n", td->table, td->scale);
int rc = run_internal_sql_clnt(&clnt, "BEGIN");
if (rc) {
snprintf(zErrTab, sizeof(zErrTab), "BEGIN");
goto cleanup;
}
char *sql = NULL;
sql = sqlite3_mprintf(
"delete from sqlite_stat1 where tbl='cdb2.%q.sav'", td->table);
assert(sql != NULL);
rc = run_internal_sql_clnt(&clnt, sql);
if (rc) strncpy(zErrTab, sql, sizeof(zErrTab));
sqlite3_free(sql); sql = NULL;
if (rc)
goto error;
sql = sqlite3_mprintf(
"update sqlite_stat1 set tbl='cdb2.%q.sav' where tbl='%q'",
td->table, td->table);
assert(sql != NULL);
rc = run_internal_sql_clnt(&clnt, sql);
if (rc) strncpy(zErrTab, sql, sizeof(zErrTab));
sqlite3_free(sql); sql = NULL;
if (rc)
goto error;
if (get_dbtable_by_name("sqlite_stat2")) {
sql = sqlite3_mprintf(
"delete from sqlite_stat2 where tbl='cdb2.%q.sav'", td->table);
assert(sql != NULL);
rc = run_internal_sql_clnt(&clnt, sql);
if (rc) strncpy(zErrTab, sql, sizeof(zErrTab));
sqlite3_free(sql); sql = NULL;
if (rc)
goto error;
sql = sqlite3_mprintf(
"update sqlite_stat2 set tbl='cdb2.%q.sav' where tbl='%q'",
td->table, td->table);
assert(sql != NULL);
rc = run_internal_sql_clnt(&clnt, sql);
if (rc) strncpy(zErrTab, sql, sizeof(zErrTab));
sqlite3_free(sql); sql = NULL;
if (rc)
goto error;
}
if (get_dbtable_by_name("sqlite_stat4")) {
sql = sqlite3_mprintf(
"delete from sqlite_stat4 where tbl='cdb2.%q.sav'", td->table);
assert(sql != NULL);
rc = run_internal_sql_clnt(&clnt, sql);
if (rc) strncpy(zErrTab, sql, sizeof(zErrTab));
sqlite3_free(sql); sql = NULL;
if (rc)
goto error;
sql = sqlite3_mprintf(
"update sqlite_stat4 set tbl='cdb2.%q.sav' where tbl='%q'",
td->table, td->table);
assert(sql != NULL);
rc = run_internal_sql_clnt(&clnt, sql);
if (rc) strncpy(zErrTab, sql, sizeof(zErrTab));
sqlite3_free(sql); sql = NULL;
if (rc)
goto error;
}
/* grab the size of the table */
int64_t totsiz = calc_table_size(tbl, 1);
if (sampled_tables_enabled)
get_sampling_threshold(td->table, &sampling_threshold);
/* sample if enabled */
if (sampled_tables_enabled) {
if (totsiz <= sampling_threshold) {
td->scale = 100;
}
logmsg(LOGMSG_INFO, "Sampling table '%s' at %d%% coverage\n", td->table, td->scale);
sampled_table = 1;
rc = sample_indicies(td, &clnt, tbl, td->scale, td->sb);
if (rc) {
snprintf(zErrTab, sizeof(zErrTab), "Sampling table '%s'", td->table);
goto error;
}
}
clnt.is_analyze = 1;
/* run analyze as sql query */
sql = sqlite3_mprintf("analyzesqlite main.\"%w\"", td->table);
assert(sql != NULL);
rc = run_internal_sql_clnt(&clnt, sql);
if (rc) strncpy(zErrTab, sql, sizeof(zErrTab));
sqlite3_free(sql); sql = NULL;
clnt.is_analyze = 0;
if (rc)
goto error;
if (debug_switch_test_delay_analyze_commit())
sleep(10);
rc = run_internal_sql_clnt(&clnt, "COMMIT /* from analyzesqlite main.... */");
if (rc) {
/*
** Manually unregister the client from the checkboard,
** if COMMIT or ROLLBACK fails.
*/
osql_unregister_sqlthr(&clnt);
snprintf(zErrTab, sizeof(zErrTab), "COMMIT");
}
cleanup:
if (rc) { // send error to client
sbuf2printf(td->sb, "?Analyze table %s. Error occurred with: %s\n",
td->table, zErrTab);
} else {
sbuf2printf(td->sb, "?Analyze completed table %s\n", td->table);
logmsg(LOGMSG_INFO, "Analyze completed, table %s\n", td->table);
}
if (sampled_table) {
cleanup_sampled_indicies(&clnt, tbl);
}
end_internal_sql_clnt(&clnt);
return rc;
error:
if (run_internal_sql_clnt(&clnt, "ROLLBACK /* from analyzesqlite main.... */") != 0)
osql_unregister_sqlthr(&clnt);
goto cleanup;
}
/* spawn thread to analyze a table */
static void *table_thread(void *arg)
{
comdb2_name_thread(__func__);
int rc;
table_descriptor_t *td = (table_descriptor_t *)arg;
struct thr_handle *thd_self;
/* register thread */
thd_self = thrman_register(THRTYPE_ANALYZE);
backend_thread_event(thedb, COMDB2_THR_EVENT_START_RDWR);
stat4dump(1, td->table, 1); /* dump stats in trc file */
sql_mem_init(NULL);
thread_memcreate(analyze_thread_memory);
/* update state */
td->table_state = TABLE_RUNNING;
/* analyze the table */
rc = analyze_table_int(td, thd_self);
ctrace("analyze_table_int: Table %s, rc = %d\n", td->table, rc);
/* mark the return */
if (0 == rc) {
td->table_state = TABLE_COMPLETE;
if (thedb->master == gbl_myhostname) { // reset directly
ctrace("analyze: Analyzed Table %s, reseting counter to 0\n", td->table);
reset_aa_counter(td->table);
} else {
ctrace("analyze: Analyzed Table %s, msg to master to reset counter to 0\n", td->table);
bdb_send_analysed_table_to_master(thedb->bdb_env, td->table);
}
} else if (TABLE_SKIPPED == rc) {
td->table_state = TABLE_SKIPPED;
} else {
td->table_state = TABLE_FAILED;
}
/* release thread */
Pthread_mutex_lock(&table_thd_mutex);
analyze_cur_table_threads--;
Pthread_cond_broadcast(&table_thd_cond);
Pthread_mutex_unlock(&table_thd_mutex);
backend_thread_event(thedb, COMDB2_THR_EVENT_DONE_RDWR);
thread_memdestroy();
sql_mem_shutdown(NULL);
return NULL;
}
/* dispatch a table thread when we're allowed to */
static int dispatch_table_thread(table_descriptor_t *td)
{
int rc;
struct timespec timeout;
/* grab lock */
Pthread_mutex_lock(&table_thd_mutex);
/* wait for thread availability */
while (analyze_cur_table_threads >= analyze_max_table_threads) {
clock_gettime(CLOCK_REALTIME, &timeout);
++timeout.tv_sec; // 1 second timeout
rc = pthread_cond_timedwait(&table_thd_cond, &table_thd_mutex, &timeout);
if (rc == ETIMEDOUT) {
if (pthread_getspecific(query_info_key) && bdb_lock_desired(thedb->bdb_env)) {
rc = recover_deadlock_simple(thedb->bdb_env);
if (rc) {
logmsg(LOGMSG_WARN, "%s: recover_deadlock rc=%d\n", __func__, rc);
}
}
} else if (rc) {
logmsg(LOGMSG_FATAL, "pthread_cond_timedwait:%d rc:%d (%s) thd:%p\n", __LINE__, rc, strerror(rc),
(void *)pthread_self());
abort();
}
}
/* grab table thread */
analyze_cur_table_threads++;
/* release */
Pthread_mutex_unlock(&table_thd_mutex);
/* dispatch */
rc = pthread_create(&td->thread_id, &gbl_pthread_attr_detached,
table_thread, td);
/* return */
return rc;
}
/* wait for table to complete */
static int wait_for_table(table_descriptor_t *td)
{
int rc;
struct timespec timeout;
/* lock table mutex */
Pthread_mutex_lock(&table_thd_mutex);
/* wait for the state to change */
while (td->table_state == TABLE_STARTUP ||
td->table_state == TABLE_RUNNING) {
clock_gettime(CLOCK_REALTIME, &timeout);
++timeout.tv_sec; // 1 second timeout
rc = pthread_cond_timedwait(&table_thd_cond, &table_thd_mutex, &timeout);
if (rc == ETIMEDOUT) {
if (pthread_getspecific(query_info_key) && bdb_lock_desired(thedb->bdb_env)) {
rc = recover_deadlock_simple(thedb->bdb_env);
if (rc) {
logmsg(LOGMSG_WARN, "%s: recover_deadlock rc=%d\n", __func__, rc);