forked from manticoresoftware/manticoresearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
searchd.cpp
21066 lines (17635 loc) · 621 KB
/
searchd.cpp
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 (c) 2017-2023, Manticore Software LTD (https://manticoresearch.com)
// Copyright (c) 2001-2016, Andrew Aksyonoff
// Copyright (c) 2008-2016, Sphinx Technologies Inc
// All rights reserved
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License. You should have
// received a copy of the GPL license along with this program; if you
// did not, you can find it at http://www.gnu.org/
//
#include "sphinxutils.h"
#include "fileutils.h"
#include "sphinxexcerpt.h"
#include "sphinxrt.h"
#include "sphinxpq.h"
#include "sphinxint.h"
#include "sphinxquery.h"
#include "sphinxsort.h"
#include "sphinxjson.h"
#include "sphinxjsonquery.h"
#include "sphinxplugin.h"
#include "sphinxqcache.h"
#include "accumulator.h"
#include "searchdaemon.h"
#include "searchdha.h"
#include "searchdreplication.h"
#include "threadutils.h"
#include "searchdtask.h"
#include "global_idf.h"
#include "docstore.h"
#include "searchdssl.h"
#include "searchdexpr.h"
#include "indexsettings.h"
#include "searchdddl.h"
#include "networking_daemon.h"
#include "query_status.h"
#include "sphinxql_debug.h"
#include "stackmock.h"
#include "binlog.h"
#include "indexfiles.h"
#include "digest_sha1.h"
#include "tokenizer/charset_definition_parser.h"
#include "client_session.h"
#include "sphinx_alter.h"
#include "docs_collector.h"
#include "index_rotator.h"
#include "config_reloader.h"
#include "secondarylib.h"
#include "task_dispatcher.h"
#include "tracer.h"
#include "netfetch.h"
#include "queryfilter.h"
#include "pseudosharding.h"
// services
#include "taskping.h"
#include "taskmalloctrim.h"
#include "taskoptimize.h"
#include "taskglobalidf.h"
#include "tasksavestate.h"
#include "taskflushbinlog.h"
#include "taskflushattrs.h"
#include "taskflushmutable.h"
#include "taskpreread.h"
#include "coroutine.h"
#include "dynamic_idx.h"
#include "searchdbuddy.h"
#include "detail/indexlink.h"
#include "detail/expmeter.h"
extern "C"
{
#include "sphinxudf.h"
}
#include <csignal>
#include <clocale>
#include <cmath>
#include <ctime>
#define SEARCHD_BACKLOG 5
// don't shutdown on SIGKILL (debug purposes)
// 1 - SIGKILL will shut down the whole daemon; 0 - watchdog will reincarnate the daemon
#define WATCHDOG_SIGKILL 1
/////////////////////////////////////////////////////////////////////////////
#if _WIN32
// Win-specific headers and calls
#include <io.h>
#else
// UNIX-specific headers and calls
#include <sys/wait.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif
#if USE_SYSLOG
#include <syslog.h>
#endif
#if HAVE_GETRLIMIT & HAVE_SETRLIMIT
#include <sys/resource.h>
#endif
/////////////////////////////////////////////////////////////////////////////
using namespace Threads;
static bool g_bService = false;
#if _WIN32
static bool g_bServiceStop = false;
static const char * g_sServiceName = "searchd";
static HANDLE g_hPipe = INVALID_HANDLE_VALUE;
#endif
static StrVec_t g_dArgs;
enum LogFormat_e
{
LOG_FORMAT_PLAIN,
LOG_FORMAT_SPHINXQL
};
#define LOG_COMPACT_IN 128 // upto this many IN(..) values allowed in query_log
static int g_iLogFile = STDOUT_FILENO; // log file descriptor
static auto& g_iParentPID = getParentPID (); // set by watchdog
static bool g_bLogSyslog = false;
static bool g_bQuerySyslog = false;
static CSphString g_sLogFile; // log file name
static bool g_bLogTty = false; // cached isatty(g_iLogFile)
static bool g_bLogStdout = true; // extra copy of startup log messages to stdout; true until around "accepting connections", then MUST be false
static LogFormat_e g_eLogFormat = LOG_FORMAT_SPHINXQL;
static bool g_bLogCompactIn = false; // whether to cut list in IN() clauses.
static int g_iQueryLogMinMs = 0; // log 'slow' threshold for query
static char g_sLogFilter[SPH_MAX_FILENAME_LEN+1] = "\0";
static int g_iLogFilterLen = 0;
static int g_iLogFileMode = 0;
static CSphBitvec g_tLogStatements;
int g_iReadTimeoutS = 5; // sec
int g_iWriteTimeoutS = 5; // sec
int g_iClientTimeoutS = 300;
int g_iClientQlTimeoutS = 900; // sec
static int g_iMaxConnection = 0; // unlimited
static int g_iThreads; // defined in config, or =cpu cores
static bool g_bWatchdog = true;
static int g_iExpansionLimit = 0;
static int g_iShutdownTimeoutUs = 3000000; // default timeout on daemon shutdown and stopwait is 3 seconds
static int g_iBacklog = SEARCHD_BACKLOG;
static int g_iThdQueueMax = 0;
static bool g_bGroupingInUtc = false;
static auto& g_iTFO = sphGetTFO ();
static CSphString g_sShutdownToken;
static int g_iServerID = 0;
static bool g_bServerID = false;
static bool g_bJsonConfigLoadedOk = false;
static auto& g_iAutoOptimizeCutoffMultiplier = AutoOptimizeCutoffMultiplier();
static constexpr bool AUTOOPTIMIZE_NEEDS_VIP = false; // whether non-VIP can issue 'SET GLOBAL auto_optimize = X'
static constexpr bool THREAD_EX_NEEDS_VIP = false; // whether non-VIP can issue 'SET GLOBAL auto_optimize = X'
static CSphVector<Listener_t> g_dListeners;
static int g_iQueryLogFile = -1;
static CSphString g_sQueryLogFile;
static CSphString g_sPidFile;
static bool g_bPidIsMine = false; // if PID is not mine, don't unlink it on fail
static int g_iPidFD = -1;
static int g_iMaxCachedDocs = 0; // in bytes
static int g_iMaxCachedHits = 0; // in bytes
int g_iMaxPacketSize = 8*1024*1024; // in bytes; for both query packets from clients and response packets from agents
static int g_iMaxFilters = 256;
static int g_iMaxFilterValues = 4096;
static int g_iMaxBatchQueries = 32;
static int64_t g_iDocstoreCache = 0;
static int64_t g_iSkipCache = 0;
static auto & g_iDistThreads = getDistThreads();
int g_iAgentConnectTimeoutMs = 1000;
int g_iAgentQueryTimeoutMs = 3000; // global (default). May be override by index-scope values, if one specified
const int MAX_RETRY_COUNT = 8;
const int MAX_RETRY_DELAY = 1000;
int g_iAgentRetryCount = 0;
int g_iAgentRetryDelayMs = MAX_RETRY_DELAY/2; // global (default) values. May be override by the query options 'retry_count' and 'retry_timeout'
bool g_bHostnameLookup = false;
CSphString g_sMySQLVersion = szMANTICORE_VERSION;
CSphString g_sDbName = "Manticore";
CSphString g_sBannerVersion { szMANTICORE_NAME };
CSphString g_sBanner;
CSphString g_sStatusVersion = szMANTICORE_VERSION;
CSphString g_sSecondaryError;
static CSphString g_sBuddyPath;
static bool g_bTelemetry = val_from_env ( "MANTICORE_TELEMETRY", true );
static bool g_bHasBuddyPath = false;
static bool g_bAutoSchema = true;
static bool g_bNoChangeCwd = val_from_env ( "MANTICORE_NO_CHANGE_CWD", false );
static int g_iDumpDocs = 1000000000;
// for CLang thread-safety analysis
ThreadRole MainThread; // functions which called only from main thread
ThreadRole HandlerThread; // thread which serves clients
//////////////////////////////////////////////////////////////////////////
static CSphString g_sConfigFile;
static bool LOG_LEVEL_SHUTDOWN = val_from_env("MANTICORE_TRACK_DAEMON_SHUTDOWN",false); // verbose logging when daemon shutdown, ruled by this env variable
static CSphString g_sConfigPath; // for resolve paths to absolute
static auto& g_bSeamlessRotate = sphGetSeamlessRotate ();
static bool g_bIOStats = false;
static auto& g_bCpuStats = sphGetbCpuStat ();
static bool g_bOptNoDetach = false;
static bool g_bOptNoLock = false;
static bool g_bSafeTrace = false;
static bool g_bStripPath = false;
static bool g_bCoreDump = false;
static bool LOG_LEVEL_LOCAL_SEARCH = val_from_env ( "MANTICORE_LOG_LOCAL_SEARCH", false ); // verbose logging local search events, ruled by this env variable
#define LOG_COMPONENT_LOCSEARCHINFO __LINE__ << " "
#define LOCSEARCHINFO LOGINFO ( LOCAL_SEARCH, LOCSEARCHINFO )
static auto& g_bGotSighup = sphGetGotSighup(); // we just received SIGHUP; need to log
static auto& g_bGotSigusr1 = sphGetGotSigusr1(); // we just received SIGUSR1; need to reopen logs
static auto& g_bGotSigusr2 = sphGetGotSigusr2(); // we just received SIGUSR2; need to dump daemon's bt
// pipe to watchdog to inform that daemon is going to close, so no need to restart it in case of crash
struct SharedData_t
{
bool m_bDaemonAtShutdown;
bool m_bHaveTTY;
};
static SharedData_t* g_pShared = nullptr;
volatile bool g_bMaintenance = false;
std::unique_ptr<ReadOnlyServedHash_c> g_pLocalIndexes = std::make_unique<ReadOnlyServedHash_c>(); // served (local) indexes hash
std::unique_ptr<ReadOnlyDistrHash_c> g_pDistIndexes = std::make_unique<ReadOnlyDistrHash_c>(); // distributed indexes hash
// this is internal deal of the daemon; don't expose it outside!
// fixme! move all this stuff to dedicated file.
static RwLock_t g_tRotateConfigMutex;
static CSphConfig g_hCfg GUARDED_BY ( g_tRotateConfigMutex );
static volatile bool g_bNeedRotate = false; // true if there were pending HUPs to handle (they could fly in during previous rotate)
static volatile bool g_bInRotate = false; // true while we are rotating
static volatile bool g_bReloadForced = false; // true in case reload issued via SphinxQL
static WorkerSharedPtr_t g_pTickPoolThread;
static CSphVector<CSphNetLoop*> g_dNetLoops;
constexpr int g_iExpMeterPeriod = 5000000; // once per 5s
static ExpMeter_c g_tStat1m { 12 }; // once a minute (12 * 5s)
static ExpMeter_c g_tStat5m { 12*5 }; // once a 5 minutes
static ExpMeter_c g_tStat15m { 12*15 }; // once a 15 minutes
static ExpMeter_c g_tPriStat1m { 12 }; // once a minute (12 * 5s)
static ExpMeter_c g_tPriStat5m { 12*5 }; // once a 5 minutes
static ExpMeter_c g_tPriStat15m { 12*15 }; // once a 15 minutes
static ExpMeter_c g_tSecStat1m { 12 }; // once a minute (12 * 5s)
static ExpMeter_c g_tSecStat5m { 12*5 }; // once a 5 minutes
static ExpMeter_c g_tSecStat15m { 12*15 }; // once a 15 minutes
int64_t g_iNextExpMeterTimestamp = sphMicroTimer() + g_iExpMeterPeriod;
/// command names
static const char * g_dApiCommands[] =
{
"search", "excerpt", "update", "keywords", "persist", "status", "query", "flushattrs", "query", "ping", "delete", "set", "insert", "replace", "commit", "suggest", "json",
"callpq", "clusterpq", "getfield"
};
STATIC_ASSERT ( sizeof(g_dApiCommands)/sizeof(g_dApiCommands[0])==SEARCHD_COMMAND_TOTAL, SEARCHD_COMMAND_SHOULD_BE_SAME_AS_SEARCHD_COMMAND_TOTAL );
//////////////////////////////////////////////////////////////////////////
const char * sAgentStatsNames[eMaxAgentStat+ehMaxStat]=
{ "query_timeouts", "connect_timeouts", "connect_failures",
"network_errors", "wrong_replies", "unexpected_closings",
"warnings", "succeeded_queries", "total_query_time",
"connect_count", "connect_avg", "connect_max" };
static RwLock_t g_tLastMetaLock;
static CSphQueryResultMeta g_tLastMeta GUARDED_BY ( g_tLastMetaLock );
/////////////////////////////////////////////////////////////////////////////
// MISC
/////////////////////////////////////////////////////////////////////////////
static void ReleaseTTYFlag()
{
if ( g_pShared )
g_pShared->m_bHaveTTY = true;
}
/////////////////////////////////////////////////////////////////////////////
// LOGGING
/////////////////////////////////////////////////////////////////////////////
/// physically emit log entry
/// buffer must have 1 extra byte for linefeed
#if _WIN32
static void sphLogEntry ( ESphLogLevel eLevel, char * sBuf, char * sTtyBuf )
#else
static void sphLogEntry ( ESphLogLevel , char * sBuf, char * sTtyBuf )
#endif
{
#if _WIN32
if ( g_bService && g_iLogFile==STDOUT_FILENO )
{
HANDLE hEventSource;
LPCTSTR lpszStrings[2];
hEventSource = RegisterEventSource ( NULL, g_sServiceName );
if ( hEventSource )
{
lpszStrings[0] = g_sServiceName;
lpszStrings[1] = sBuf;
WORD eType;
switch ( eLevel )
{
case SPH_LOG_FATAL: eType = EVENTLOG_ERROR_TYPE; break;
case SPH_LOG_WARNING: eType = EVENTLOG_WARNING_TYPE; break;
case SPH_LOG_INFO: eType = EVENTLOG_INFORMATION_TYPE; break;
default: eType = EVENTLOG_INFORMATION_TYPE; break;
}
ReportEvent ( hEventSource, // event log handle
eType, // event type
0, // event category
0, // event identifier
NULL, // no security identifier
2, // size of lpszStrings array
0, // no binary data
lpszStrings, // array of strings
NULL ); // no binary data
DeregisterEventSource ( hEventSource );
}
} else
#endif
{
strcat ( sBuf, "\n" ); // NOLINT
sphSeek ( g_iLogFile, 0, SEEK_END );
if ( g_bLogTty )
{
memmove ( sBuf+20, sBuf+15, 9);
sTtyBuf = sBuf + 19;
*sTtyBuf = '[';
sphWrite ( g_iLogFile, sTtyBuf, strlen(sTtyBuf) );
}
else
sphWrite ( g_iLogFile, sBuf, strlen(sBuf) );
if ( g_bLogStdout && g_iLogFile!=STDOUT_FILENO )
sphWrite ( STDOUT_FILENO, sTtyBuf, strlen(sTtyBuf) );
}
}
/// log entry (with log levels, dupe catching, etc)
/// call with NULL format for dupe flushing
void sphLog ( ESphLogLevel eLevel, const char * sFmt, va_list ap )
{
// dupe catcher state
static const int FLUSH_THRESH_TIME = 1000000; // in microseconds
static const int FLUSH_THRESH_COUNT = 100;
static ESphLogLevel eLastLevel = SPH_LOG_INFO;
static DWORD uLastEntry = 0;
static int64_t tmLastStamp = -1000000-FLUSH_THRESH_TIME;
static int iLastRepeats = 0;
// only if we can
if ( sFmt && eLevel>g_eLogLevel )
return;
#if USE_SYSLOG
if ( g_bLogSyslog && sFmt )
{
const int levels[SPH_LOG_MAX+1] = { LOG_EMERG, LOG_WARNING, LOG_INFO, LOG_DEBUG, LOG_DEBUG, LOG_DEBUG, LOG_DEBUG };
vsyslog ( levels[eLevel], sFmt, ap );
return;
}
#endif
if ( g_iLogFile<0 && !g_bService )
return;
// format the banner
char sTimeBuf[128];
sphFormatCurrentTime ( sTimeBuf, sizeof(sTimeBuf) );
const char * sBanner = "";
if ( sFmt==NULL ) eLevel = eLastLevel;
if ( eLevel==SPH_LOG_FATAL ) sBanner = "FATAL: ";
if ( eLevel==SPH_LOG_WARNING ) sBanner = "WARNING: ";
if ( eLevel>=SPH_LOG_DEBUG ) sBanner = "DEBUG: ";
if ( eLevel==SPH_LOG_RPL_DEBUG ) sBanner = "RPL: ";
char sBuf [ 1024 ];
snprintf ( sBuf, sizeof(sBuf)-1, "[%s] [%d] ", sTimeBuf, GetOsThreadId() );
char * sTtyBuf = sBuf + strlen(sBuf);
strncpy ( sTtyBuf, sBanner, 32 ); // 32 is arbitrary; just something that is enough and keeps lint happy
auto iLen = (int) strlen(sBuf);
// format the message
if ( sFmt )
{
// need more space for tail zero and "\n" that added at sphLogEntry
int iSafeGap = 4;
int iBufSize = sizeof(sBuf)-iLen-iSafeGap;
vsnprintf ( sBuf+iLen, iBufSize, sFmt, ap );
sBuf[ sizeof(sBuf)-iSafeGap ] = '\0';
}
if ( sFmt && eLevel>SPH_LOG_INFO && g_iLogFilterLen )
{
if ( strncmp ( sBuf+iLen, g_sLogFilter, g_iLogFilterLen )!=0 )
return;
}
// catch dupes
DWORD uEntry = sFmt ? sphCRC32 ( sBuf+iLen ) : 0;
int64_t tmNow = sphMicroTimer();
// accumulate while possible
if ( sFmt && eLevel==eLastLevel && uEntry==uLastEntry && iLastRepeats<FLUSH_THRESH_COUNT && tmNow<tmLastStamp+FLUSH_THRESH_TIME )
{
tmLastStamp = tmNow;
iLastRepeats++;
return;
}
// flush if needed
if ( iLastRepeats!=0 && ( sFmt || tmNow>=tmLastStamp+FLUSH_THRESH_TIME ) )
{
// flush if we actually have something to flush, and
// case 1: got a message we can't accumulate
// case 2: got a periodic flush and been otherwise idle for a thresh period
char sLast[256];
iLen = Min ( iLen, 256 );
strncpy ( sLast, sBuf, iLen );
if ( iLen < 256 )
snprintf ( sLast+iLen, sizeof(sLast)-iLen, "last message repeated %d times", iLastRepeats );
sphLogEntry ( eLastLevel, sLast, sLast + ( sTtyBuf-sBuf ) );
tmLastStamp = tmNow;
iLastRepeats = 0;
eLastLevel = SPH_LOG_INFO;
uLastEntry = 0;
}
// was that a flush-only call?
if ( !sFmt )
return;
tmLastStamp = tmNow;
iLastRepeats = 0;
eLastLevel = eLevel;
uLastEntry = uEntry;
// do the logging
sphLogEntry ( eLevel, sBuf, sTtyBuf );
}
void Shutdown (); // forward
bool DieOrFatalWithShutdownCb ( bool bDie, const char * sFmt, va_list ap )
{
if ( bDie )
g_pLogger () ( SPH_LOG_FATAL, sFmt, ap );
else
Shutdown ();
return false; // don't lot to stdout
}
bool DieOrFatalCb ( bool bDie, const char * sFmt, va_list ap )
{
if ( bDie )
g_pLogger () ( SPH_LOG_FATAL, sFmt, ap );
return false; // don't lot to stdout
}
#if !_WIN32
static CSphString GetNamedPipeName ( int iPid )
{
CSphString sRes;
sRes.SetSprintf ( "/tmp/searchd_%d", iPid );
return sRes;
}
#endif
void LogChangeMode ( int iFile, int iMode )
{
if ( iFile<0 || iMode==0 || iFile==STDOUT_FILENO || iFile==STDERR_FILENO )
return;
#if !_WIN32
fchmod ( iFile, iMode );
#endif
}
/////////////////////////////////////////////////////////////////////////////
static int CmpString ( const CSphString & a, const CSphString & b )
{
if ( !a.cstr() && !b.cstr() )
return 0;
if ( !a.cstr() || !b.cstr() )
return a.cstr() ? -1 : 1;
return strcmp ( a.cstr(), b.cstr() );
}
struct SearchFailure_t
{
CSphString m_sParentIndex;
CSphString m_sIndex; ///< searched index name
CSphString m_sError; ///< search error message
bool operator == ( const SearchFailure_t & r ) const
{
return m_sIndex==r.m_sIndex && m_sError==r.m_sError && m_sParentIndex==r.m_sParentIndex;
}
bool operator < ( const SearchFailure_t & r ) const
{
int iRes = CmpString ( m_sError.cstr(), r.m_sError.cstr() );
if ( !iRes )
iRes = CmpString ( m_sParentIndex.cstr (), r.m_sParentIndex.cstr () );
if ( !iRes )
iRes = CmpString ( m_sIndex.cstr(), r.m_sIndex.cstr() );
return iRes<0;
}
SearchFailure_t & operator = ( const SearchFailure_t & r )
{
if ( this!=&r )
{
m_sParentIndex = r.m_sParentIndex;
m_sIndex = r.m_sIndex;
m_sError = r.m_sError;
}
return *this;
}
};
static void ReportIndexesName ( int iSpanStart, int iSpandEnd, const CSphVector<SearchFailure_t> & dLog, StringBuilder_c & sOut );
class SearchFailuresLog_c
{
CSphVector<SearchFailure_t> m_dLog;
public:
void Submit ( const CSphString& sIndex, const char * sParentIndex , const char * sError )
{
SearchFailure_t & tEntry = m_dLog.Add ();
tEntry.m_sParentIndex = sParentIndex;
tEntry.m_sIndex = sIndex;
tEntry.m_sError = sError;
}
void SubmitVa ( const char * sIndex, const char * sParentIndex, const char * sTemplate, va_list ap )
{
StringBuilder_c tError;
tError.vAppendf ( sTemplate, ap );
SearchFailure_t &tEntry = m_dLog.Add ();
tEntry.m_sParentIndex = sParentIndex;
tEntry.m_sIndex = sIndex;
tError.MoveTo ( tEntry.m_sError );
}
inline void Append ( const SearchFailuresLog_c& rhs )
{
m_dLog.Append ( rhs.m_dLog );
}
void SubmitEx ( const char * sIndex, const char * sParentIndex, const char * sTemplate, ... ) __attribute__ ( ( format ( printf, 4, 5 ) ) )
{
va_list ap;
va_start ( ap, sTemplate );
SubmitVa ( sIndex, sParentIndex, sTemplate, ap);
va_end ( ap );
}
void SubmitEx ( const CSphString &sIndex, const char * sParentIndex, const char * sTemplate, ... ) __attribute__ ( ( format ( printf, 4, 5 ) ) )
{
va_list ap;
va_start ( ap, sTemplate );
SubmitVa ( sIndex.cstr(), sParentIndex, sTemplate, ap );
va_end ( ap );
}
bool IsEmpty ()
{
return m_dLog.GetLength()==0;
}
int GetReportsCount()
{
return m_dLog.GetLength();
}
void BuildReport ( StringBuilder_c & sReport )
{
if ( IsEmpty() )
return;
// collapse same messages
m_dLog.Uniq ();
int iSpanStart = 0;
Comma_c sColon( { ";\n", 2 } );
for ( int i=1; i<=m_dLog.GetLength(); ++i )
{
// keep scanning while error text is the same
if ( i!=m_dLog.GetLength() )
if ( m_dLog[i].m_sError==m_dLog[i-1].m_sError )
continue;
sReport << sColon;
ReportIndexesName ( iSpanStart, i, m_dLog, sReport );
sReport << m_dLog[iSpanStart].m_sError;
// done
iSpanStart = i;
}
}
};
#define LOG_COMPONENT_SEARCHD __LINE__ << " "
#define SHUTINFO LOGINFO (SHUTDOWN,SEARCHD)
/////////////////////////////////////////////////////////////////////////////
// SIGNAL HANDLERS
/////////////////////////////////////////////////////////////////////////////
void Shutdown () REQUIRES ( MainThread ) NO_THREAD_SAFETY_ANALYSIS
{
// force even long time searches to shut
SHUTINFO << "Trigger g_bInterruptNow ...";
sphInterruptNow ();
SHUTINFO << "Shutdown curl query subsystem ...";
ShutdownCurl();
#if !_WIN32
int fdStopwait = -1;
#endif
bool bAttrsSaveOk = true;
if ( g_pShared )
g_pShared->m_bDaemonAtShutdown = true;
#if !_WIN32
// stopwait handshake
CSphString sPipeName = GetNamedPipeName ( getpid() );
fdStopwait = ::open ( sPipeName.cstr(), O_WRONLY | O_NONBLOCK );
if ( fdStopwait>=0 )
{
DWORD uHandshakeOk = 0;
int VARIABLE_IS_NOT_USED iDummy = ::write ( fdStopwait, &uHandshakeOk, sizeof(DWORD) );
}
#endif
int64_t tmShutStarted = sphMicroTimer ();
// release all planned/scheduled tasks
SHUTINFO << "Shut down mini timer ...";
sph::ShutdownMiniTimer();
SHUTINFO << "Shut down flushing mutable ...";
ShutdownFlushingMutable();
// stop search threads; up to shutdown_timeout seconds
SHUTINFO << "Wait preread (if any) finished ...";
WaitPrereadFinished ( g_iShutdownTimeoutUs );
// save attribute updates for all local indexes
SHUTINFO << "Finally save tables ...";
bAttrsSaveOk = FinallySaveIndexes();
// right before unlock loop
if ( g_bJsonConfigLoadedOk )
{
CSphString sError;
SHUTINFO << "Save json config ...";
SaveConfigInt(sError);
}
// stop netloop processing
SHUTINFO << "Stop netloop processing ...";
for ( auto & pNetLoop : g_dNetLoops )
{
pNetLoop->StopNetLoop ();
SafeRelease ( pNetLoop );
}
// stop netloop threads
SHUTINFO << "Stop netloop pool ...";
if ( g_pTickPoolThread )
g_pTickPoolThread->StopAll ();
// call scheduled callbacks:
// shutdown replication,
// shutdown ssl,
// shutdown tick threads,
SHUTINFO << "Invoke shutdown callbacks ...";
searchd::FireShutdownCbs ();
SHUTINFO << "Waiting clients to finish ... (" << myinfo::CountClients() << ")";
while ( ( myinfo::CountClients ()>0 ) && ( sphMicroTimer ()-tmShutStarted )<g_iShutdownTimeoutUs )
sphSleepMsec ( 50 );
if ( myinfo::CountClients ()>0 )
{
int64_t tmDelta = sphMicroTimer ()-tmShutStarted;
sphWarning ( "still %d alive tasks during shutdown, after %d.%03d sec", myinfo::CountClients (), (int) ( tmDelta
/ 1000000 ), (int) ( ( tmDelta / 1000 ) % 1000 ) );
}
// unlock indexes and release locks if needed
SHUTINFO << "Unlock tables ...";
{
ServedSnap_t hLocal = g_pLocalIndexes->GetHash();
for ( const auto& tIt : *hLocal )
RWIdx_c ( tIt.second )->Unlock();
}
Threads::CallCoroutine ( [] {
SHUTINFO << "Abandon local tables list ...";
g_pLocalIndexes->ReleaseAndClear();
// unlock Distr indexes automatically done by d-tr
SHUTINFO << "Abandon distr tables list ...";
g_pDistIndexes->ReleaseAndClear();
} );
SHUTINFO << "Shutdown alone threads (if any) ...";
Detached::ShutdownAllAlones();
SHUTINFO << "Shutdown main work pool ...";
StopGlobalWorkPool();
SHUTINFO << "Remove local tables list ...";
g_pLocalIndexes.reset();
SHUTINFO << "Remove distr tables list ...";
g_pDistIndexes.reset();
// clear shut down of rt indexes + binlog
SHUTINFO << "Finish IO stats collecting ...";
sphDoneIOStats();
SHUTINFO << "Finish RT serving ...";
Binlog::Deinit();
SHUTINFO << "Shutdown docstore ...";
ShutdownDocstore();
SHUTINFO << "Shutdown skip cache ...";
ShutdownSkipCache();
SHUTINFO << "Shutdown global IDFs ...";
sph::ShutdownGlobalIDFs ();
SHUTINFO << "Shutdown aot ...";
sphAotShutdown ();
SHUTINFO << "Shutdown columnar ...";
ShutdownColumnar();
SHUTINFO << "Shutdown listeners ...";
for ( auto& dListener : g_dListeners )
if ( dListener.m_iSock>=0 )
sphSockClose ( dListener.m_iSock );
SHUTINFO << "Close persistent sockets ...";
ClosePersistentSockets();
// close pid
SHUTINFO << "Release (close) pid file ...";
if ( g_iPidFD!=-1 )
::close ( g_iPidFD );
g_iPidFD = -1;
// remove pid file, if we owned it
if ( g_bPidIsMine && !g_sPidFile.IsEmpty() )
::unlink ( g_sPidFile.cstr() );
SHUTINFO << "Shutdown hazard pointers ...";
hazard::Shutdown ();
// wordforms till there might be referenced from accum (rt-index), which, in turn, is part of client session.
// so, shutdown them before will probably fail.
// after hazard shutdown, all sessions are surely done, so wordforms is good to be destroyed at this point.
SHUTINFO << "Shutdown wordforms ...";
sphShutdownWordforms();
sphInfo ( "shutdown daemon version '%s' ...", g_sStatusVersion.cstr() );
sphInfo ( "shutdown complete" );
Threads::Done ( g_iLogFile );
#if _WIN32
CloseHandle ( g_hPipe );
#else
if ( fdStopwait>=0 )
{
DWORD uStatus = bAttrsSaveOk;
int VARIABLE_IS_NOT_USED iDummy = ::write ( fdStopwait, &uStatus, sizeof(DWORD) );
::close ( fdStopwait );
}
#endif
}
void sighup ( int )
{
g_bGotSighup = 1;
}
static void sigterm ( int )
{
// tricky bit
// we can't call exit() here because malloc()/free() are not re-entrant
// we could call _exit() but let's try to die gracefully on TERM
// and let signal sender wait and send KILL as needed
sphInterruptNow();
}
static void sigusr1 ( int )
{
g_bGotSigusr1 = true;
}
static void sigusr2 ( int )
{
g_bGotSigusr2 = true;
}
struct QueryCopyState_t
{
BYTE * m_pDst;
BYTE * m_pDstEnd;
const BYTE * m_pSrc;
const BYTE * m_pSrcEnd;
};
// crash query handler
static const int g_iQueryLineLen = 80;
static const char g_dEncodeBase64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static bool sphCopyEncodedBase64 ( QueryCopyState_t & tEnc )
{
BYTE * pDst = tEnc.m_pDst;
const BYTE * pDstBase = tEnc.m_pDst;
const BYTE * pSrc = tEnc.m_pSrc;
const BYTE * pDstEnd = tEnc.m_pDstEnd-5;
const BYTE * pSrcEnd = tEnc.m_pSrcEnd-3;
while ( pDst<=pDstEnd && pSrc<=pSrcEnd )
{
// put line delimiter at max line length
if ( ( ( pDst-pDstBase ) % g_iQueryLineLen )>( ( pDst-pDstBase+4 ) % g_iQueryLineLen ) )
*pDst++ = '\n';
// Convert to big endian
DWORD uSrc = ( pSrc[0] << 16 ) | ( pSrc[1] << 8 ) | ( pSrc[2] );
pSrc += 3;
*pDst++ = g_dEncodeBase64 [ ( uSrc & 0x00FC0000 ) >> 18 ];
*pDst++ = g_dEncodeBase64 [ ( uSrc & 0x0003F000 ) >> 12 ];
*pDst++ = g_dEncodeBase64 [ ( uSrc & 0x00000FC0 ) >> 6 ];
*pDst++ = g_dEncodeBase64 [ ( uSrc & 0x0000003F ) ];
}
// there is a tail in source data and a room for it at destination buffer
if ( pSrc<tEnc.m_pSrcEnd && ( tEnc.m_pSrcEnd-pSrc<3 ) && ( pDst<=pDstEnd-4 ) )
{
int iLeft = ( tEnc.m_pSrcEnd - pSrc ) % 3;
if ( iLeft==1 )
{
DWORD uSrc = pSrc[0]<<16;
pSrc += 1;
*pDst++ = g_dEncodeBase64 [ ( uSrc & 0x00FC0000 ) >> 18 ];
*pDst++ = g_dEncodeBase64 [ ( uSrc & 0x0003F000 ) >> 12 ];
*pDst++ = '=';
*pDst++ = '=';
} else if ( iLeft==2 )
{
DWORD uSrc = ( pSrc[0]<<16 ) | ( pSrc[1] << 8 );
pSrc += 2;
*pDst++ = g_dEncodeBase64 [ ( uSrc & 0x00FC0000 ) >> 18 ];
*pDst++ = g_dEncodeBase64 [ ( uSrc & 0x0003F000 ) >> 12 ];
*pDst++ = g_dEncodeBase64 [ ( uSrc & 0x00000FC0 ) >> 6 ];
*pDst++ = '=';
}
}
tEnc.m_pDst = pDst;
tEnc.m_pSrc = pSrc;
return ( tEnc.m_pSrc<tEnc.m_pSrcEnd );
}
static bool sphCopySphinxQL ( QueryCopyState_t & tState )
{
BYTE * pDst = tState.m_pDst;
const BYTE * pSrc = tState.m_pSrc;
BYTE * pNextLine = pDst+g_iQueryLineLen;
while ( pDst<tState.m_pDstEnd && pSrc<tState.m_pSrcEnd )
{
if ( pDst>pNextLine && pDst+1<tState.m_pDstEnd && ( sphIsSpace ( *pSrc ) || *pSrc==',' ) )
{
*pDst++ = *pSrc++;
*pDst++ = '\n';
pNextLine = pDst + g_iQueryLineLen;
} else
{
*pDst++ = *pSrc++;
}
}
tState.m_pDst = pDst;
tState.m_pSrc = pSrc;
return ( tState.m_pSrc<tState.m_pSrcEnd );
}
static bool sphCopySphinxHttp ( QueryCopyState_t & tState )
{
BYTE * pDst = tState.m_pDst;
const BYTE * pSrc = tState.m_pSrc;
while ( pDst<tState.m_pDstEnd && pSrc<tState.m_pSrcEnd )
{
*pDst++ = *pSrc++;
}
tState.m_pDst = pDst;
tState.m_pSrc = pSrc;
return ( tState.m_pSrc<tState.m_pSrcEnd );
}
typedef bool CopyQuery_fn ( QueryCopyState_t & tState );
#define SPH_TIME_PID_MAX_SIZE 256
const char g_sCrashedBannerAPI[] = "\n--- crashed SphinxAPI request dump ---\n";
const char g_sCrashedBannerMySQL[] = "\n--- crashed SphinxQL request dump ---\n";
const char g_sCrashedBannerHTTP[] = "\n--- crashed HTTP request dump ---\n";
const char g_sCrashedBannerBad[] = "\n--- crashed invalid query ---\n";
const char g_sCrashedBannerTail[] = "\n--- request dump end ---\n";
const char g_sCrashedIndex[] = "--- local index:";
const char g_sEndLine[] = "\n";
#if _WIN32
const char g_sMinidumpBanner[] = "minidump located at: ";
#endif
#if SPH_ALLOCS_PROFILER
const char g_sMemoryStatBanner[] = "\n--- memory statistics ---\n";
#endif
static BYTE g_dCrashQueryBuff [4096];
static char g_sCrashInfo [SPH_TIME_PID_MAX_SIZE] = "[][]\n";
static int g_iCrashInfoLen = 0;
#if _WIN32
static char g_sMinidump[SPH_TIME_PID_MAX_SIZE] = "";
#endif
#if !_WIN32
void CrashLogger::HandleCrash ( int sig ) NO_THREAD_SAFETY_ANALYSIS
#else
LONG WINAPI CrashLogger::HandleCrash ( EXCEPTION_POINTERS * pExc )
#endif // !_WIN32