searchd.cpp 223 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549
  1. //
  2. // $Id$
  3. //
  4. //
  5. // Copyright (c) 2001-2008, Andrew Aksyonoff. All rights reserved.
  6. //
  7. // This program is free software; you can redistribute it and/or modify
  8. // it under the terms of the GNU General Public License. You should have
  9. // received a copy of the GPL license along with this program; if you
  10. // did not, you can find it at http://www.gnu.org/
  11. //
  12. #include "sphinx.h"
  13. #include "sphinxutils.h"
  14. #include "sphinxexcerpt.h"
  15. #include <errno.h>
  16. #include <fcntl.h>
  17. #include <signal.h>
  18. #include <stdio.h>
  19. #include <string.h>
  20. #include <sys/stat.h>
  21. #include <sys/types.h>
  22. #include <time.h>
  23. #include <stdarg.h>
  24. #include <limits.h>
  25. #define SEARCHD_BACKLOG 5
  26. #define SEARCHD_DEFAULT_PORT 3312
  27. #define SPH_ADDRESS_SIZE sizeof("000.000.000.000")
  28. /////////////////////////////////////////////////////////////////////////////
  29. #if USE_WINDOWS
  30. // Win-specific headers and calls
  31. #include <io.h>
  32. #include <winsock2.h>
  33. #include <tlhelp32.h>
  34. #define sphSockRecv(_sock,_buf,_len) ::recv(_sock,_buf,_len,0)
  35. #define sphSockSend(_sock,_buf,_len) ::send(_sock,_buf,_len,0)
  36. #define sphSockClose(_sock) ::closesocket(_sock)
  37. #define stat _stat
  38. #else
  39. // UNIX-specific headers and calls
  40. #include <unistd.h>
  41. #include <netinet/in.h>
  42. #include <sys/file.h>
  43. #include <sys/socket.h>
  44. #include <sys/time.h>
  45. #include <sys/wait.h>
  46. #include <sys/un.h>
  47. #include <netdb.h>
  48. // there's no MSG_NOSIGNAL on OS X
  49. #ifndef MSG_NOSIGNAL
  50. #define MSG_NOSIGNAL 0
  51. #endif
  52. #define sphSockRecv(_sock,_buf,_len) ::recv(_sock,_buf,_len,MSG_NOSIGNAL)
  53. #define sphSockSend(_sock,_buf,_len) ::send(_sock,_buf,_len,MSG_NOSIGNAL)
  54. #define sphSockClose(_sock) ::close(_sock)
  55. #endif
  56. /////////////////////////////////////////////////////////////////////////////
  57. // MISC GLOBALS
  58. /////////////////////////////////////////////////////////////////////////////
  59. struct ServedIndex_t
  60. {
  61. CSphIndex * m_pIndex;
  62. const CSphSchema * m_pSchema; ///< pointer to index schema, managed by the index itself
  63. CSphString m_sIndexPath;
  64. bool m_bEnabled; ///< to disable index in cases when rotation fails
  65. bool m_bMlock;
  66. bool m_bPreopen;
  67. bool m_bOnDiskDict;
  68. bool m_bStar;
  69. bool m_bExpand;
  70. bool m_bToDelete;
  71. bool m_bOnlyNew;
  72. int m_iUpdateTag;
  73. public:
  74. ServedIndex_t ();
  75. ~ServedIndex_t ();
  76. void Reset ();
  77. };
  78. /////////////////////////////////////////////////////////////////////////////
  79. enum ESphAddIndex
  80. {
  81. ADD_ERROR = 0,
  82. ADD_LOCAL = 1,
  83. ADD_DISTR = 2
  84. };
  85. enum ESphLogLevel
  86. {
  87. LOG_FATAL = 0,
  88. LOG_WARNING = 1,
  89. LOG_INFO = 2
  90. };
  91. enum ProtocolType_e
  92. {
  93. PROTO_SPHINX,
  94. PROTO_MYSQL41
  95. };
  96. static bool g_bService = false;
  97. #if USE_WINDOWS
  98. static bool g_bServiceStop = false;
  99. static const char * g_sServiceName = "searchd";
  100. HANDLE g_hPipe = INVALID_HANDLE_VALUE;
  101. #endif
  102. static CSphVector<CSphString> g_dArgs;
  103. static bool g_bHeadDaemon = false;
  104. static bool g_bLogStdout = true;
  105. static bool g_bCrashLog_Enabled = false;
  106. static const char * g_sCrashLog_Path = NULL;
  107. static const BYTE * g_pCrashLog_LastQuery = NULL;
  108. static int g_iCrashLog_LastQuerySize = 0;
  109. static BYTE g_dCrashLog_LastHello[12];
  110. static ESphLogLevel g_eLogLevel = LOG_INFO;
  111. static int g_iLogFile = STDOUT_FILENO; // log file descriptor
  112. static CSphString g_sLogFile; // log file name
  113. static bool g_bLogTty = false; // cached isatty(g_iLogFile)
  114. static int g_iReadTimeout = 5; // sec
  115. static int g_iWriteTimeout = 5;
  116. static int g_iClientTimeout = 300;
  117. static int g_iChildren = 0;
  118. static int g_iMaxChildren = 0;
  119. static bool g_bPreopenIndexes = false;
  120. static bool g_bOnDiskDicts = false;
  121. static bool g_bUnlinkOld = true;
  122. struct Listener_t
  123. {
  124. int m_iSock;
  125. ProtocolType_e m_eProto;
  126. };
  127. static CSphVector<Listener_t> g_dListeners;
  128. static int g_iQueryLogFile = -1;
  129. static CSphString g_sQueryLogFile;
  130. static const char * g_sPidFile = NULL;
  131. static int g_iPidFD = -1;
  132. static int g_iMaxMatches = 1000;
  133. static int g_iAttrFlushPeriod = 0; // in seconds; 0 means "do not flush"
  134. static int g_iMaxPacketSize = 8*1024*1024; // in bytes; for both query packets from clients and response packets from agents
  135. static int g_iMaxFilters = 256;
  136. static int g_iMaxFilterValues = 4096;
  137. //////////////////////////////////////////////////////////////////////////
  138. static CSphString g_sConfigFile;
  139. static DWORD g_uCfgCRC32 = 0;
  140. static struct stat g_tCfgStat;
  141. static CSphConfigParser * g_pCfg = NULL;
  142. #if USE_WINDOWS
  143. static bool g_bSeamlessRotate = false;
  144. #else
  145. static bool g_bSeamlessRotate = true;
  146. #endif
  147. static bool g_bIOStats = false;
  148. static bool g_bCpuStats = false;
  149. static bool g_bOptConsole = false;
  150. static bool g_bOptNoDetach = false;
  151. static volatile bool g_bDoDelete = false; // do we need to delete any indexes?
  152. static volatile bool g_bDoRotate = false; // flag that we are rotating now; set from SIGHUP; cleared on rotation success
  153. static volatile bool g_bGotSighup = false; // we just received SIGHUP; need to log
  154. static volatile bool g_bGotSigterm = false; // we just received SIGTERM; need to shutdown
  155. static volatile bool g_bGotSigchld = false; // we just received SIGCHLD; need to count dead children
  156. static volatile bool g_bGotSigusr1 = false; // we just received SIGUSR1; need to reopen logs
  157. static SmallStringHash_T<ServedIndex_t> g_hIndexes; // served indexes hash
  158. static CSphVector<const char *> g_dRotating; // names of indexes to be rotated this time
  159. static const char * g_sPrereading = NULL; // name of index currently being preread
  160. static CSphIndex * g_pPrereading = NULL; // rotation "buffer"
  161. static int g_iUpdateTag = 0; // ever-growing update tag
  162. static bool g_bFlushing = false; // update flushing in progress
  163. static int g_iFlushTag = 0; // last flushed tag
  164. enum
  165. {
  166. SPH_PIPE_UPDATED_ATTRS,
  167. SPH_PIPE_SAVED_ATTRS,
  168. SPH_PIPE_PREREAD
  169. };
  170. struct PipeInfo_t
  171. {
  172. int m_iFD; ///< read-pipe to child
  173. int m_iHandler; ///< who's my handler (SPH_PIPE_xxx)
  174. PipeInfo_t () : m_iFD ( -1 ), m_iHandler ( -1 ) {}
  175. };
  176. static CSphVector<PipeInfo_t> g_dPipes; ///< currently open read-pipes to children processes
  177. static CSphVector<DWORD> g_dMvaStorage; ///< per-query (!) pool to store MVAs received from remote agents
  178. static CSphVector<BYTE> g_dStringsStorage; ///< per-query (!) pool to store strings received from remote agents
  179. struct PoolPtrs_t
  180. {
  181. const DWORD * m_pMva;
  182. const BYTE * m_pStrings;
  183. PoolPtrs_t ()
  184. : m_pMva ( NULL )
  185. , m_pStrings ( NULL )
  186. {}
  187. };
  188. /////////////////////////////////////////////////////////////////////////////
  189. /// known commands
  190. enum SearchdCommand_e
  191. {
  192. SEARCHD_COMMAND_SEARCH = 0,
  193. SEARCHD_COMMAND_EXCERPT = 1,
  194. SEARCHD_COMMAND_UPDATE = 2,
  195. SEARCHD_COMMAND_KEYWORDS = 3,
  196. SEARCHD_COMMAND_PERSIST = 4,
  197. SEARCHD_COMMAND_STATUS = 5,
  198. SEARCHD_COMMAND_QUERY = 6,
  199. SEARCHD_COMMAND_TOTAL
  200. };
  201. /// known command versions
  202. enum
  203. {
  204. VER_COMMAND_SEARCH = 0x117,
  205. VER_COMMAND_EXCERPT = 0x100,
  206. VER_COMMAND_UPDATE = 0x102,
  207. VER_COMMAND_KEYWORDS = 0x100,
  208. VER_COMMAND_STATUS = 0x100,
  209. VER_COMMAND_QUERY = 0x100
  210. };
  211. /// known status return codes
  212. enum SearchdStatus_e
  213. {
  214. SEARCHD_OK = 0, ///< general success, command-specific reply follows
  215. SEARCHD_ERROR = 1, ///< general failure, error message follows
  216. SEARCHD_RETRY = 2, ///< temporary failure, error message follows, client should retry later
  217. SEARCHD_WARNING = 3 ///< general success, warning message and command-specific reply follow
  218. };
  219. const int MAX_RETRY_COUNT = 8;
  220. const int MAX_RETRY_DELAY = 1000;
  221. //////////////////////////////////////////////////////////////////////////
  222. // PERF COUNTERS
  223. //////////////////////////////////////////////////////////////////////////
  224. struct SearchdStats_t
  225. {
  226. DWORD m_uStarted;
  227. int64_t m_iConnections;
  228. int64_t m_iMaxedOut;
  229. int64_t m_iCommandCount[SEARCHD_COMMAND_TOTAL];
  230. int64_t m_iAgentConnect;
  231. int64_t m_iAgentRetry;
  232. int64_t m_iQueries; ///< search queries count (differs from search commands count because of multi-queries)
  233. int64_t m_iQueryTime; ///< wall time spent (including network wait time)
  234. int64_t m_iQueryCpuTime; ///< CPU time spent
  235. int64_t m_iDistQueries; ///< distributed queries count
  236. int64_t m_iDistWallTime; ///< wall time spent on distributed queries
  237. int64_t m_iDistLocalTime; ///< wall time spent searching local indexes in distributed queries
  238. int64_t m_iDistWaitTime; ///< time spent waiting for remote agents in distributed queries
  239. int64_t m_iDiskReads; ///< total read IO calls (fired by search queries)
  240. int64_t m_iDiskReadBytes; ///< total read IO traffic
  241. int64_t m_iDiskReadTime; ///< total read IO time
  242. };
  243. static SearchdStats_t * g_pStats = NULL;
  244. static CSphSharedBuffer<BYTE> g_tStatsBuffer;
  245. static CSphProcessSharedMutex g_tStatsMutex;
  246. /////////////////////////////////////////////////////////////////////////////
  247. // MACHINE-DEPENDENT STUFF
  248. /////////////////////////////////////////////////////////////////////////////
  249. #if USE_WINDOWS
  250. // Windows hacks
  251. #undef EINTR
  252. #define LOCK_EX 0
  253. #define LOCK_UN 1
  254. #define STDIN_FILENO fileno(stdin)
  255. #define STDOUT_FILENO fileno(stdout)
  256. #define STDERR_FILENO fileno(stderr)
  257. #define ETIMEDOUT WSAETIMEDOUT
  258. #define EWOULDBLOCK WSAEWOULDBLOCK
  259. #define EINPROGRESS WSAEINPROGRESS
  260. #define EINTR WSAEINTR
  261. #define ECONNRESET WSAECONNRESET
  262. #define ECONNABORTED WSAECONNABORTED
  263. #define socklen_t int
  264. #define ftruncate _chsize
  265. #define getpid GetCurrentProcessId
  266. #endif // USE_WINDOWS
  267. const int EXT_COUNT = 8;
  268. const char * g_dNewExts[EXT_COUNT] = { ".new.sph", ".new.spa", ".new.spi", ".new.spd", ".new.spp", ".new.spm", ".new.spk", ".new.sps" };
  269. const char * g_dOldExts[EXT_COUNT] = { ".old.sph", ".old.spa", ".old.spi", ".old.spd", ".old.spp", ".old.spm", ".old.spk", ".old.sps" };
  270. const char * g_dCurExts[EXT_COUNT] = { ".sph", ".spa", ".spi", ".spd", ".spp", ".spm", ".spk", ".sps" };
  271. /////////////////////////////////////////////////////////////////////////////
  272. // MISC
  273. /////////////////////////////////////////////////////////////////////////////
  274. ServedIndex_t::ServedIndex_t ()
  275. {
  276. Reset ();
  277. }
  278. void ServedIndex_t::Reset ()
  279. {
  280. m_pIndex = NULL;
  281. m_bEnabled = true;
  282. m_bMlock = false;
  283. m_bPreopen = false;
  284. m_bOnDiskDict = false;
  285. m_bStar = false;
  286. m_bExpand = false;
  287. m_bToDelete = false;
  288. m_bOnlyNew = false;
  289. m_iUpdateTag= 0;
  290. }
  291. ServedIndex_t::~ServedIndex_t ()
  292. {
  293. SafeDelete ( m_pIndex );
  294. }
  295. /////////////////////////////////////////////////////////////////////////////
  296. // LOGGING
  297. /////////////////////////////////////////////////////////////////////////////
  298. void Shutdown (); // forward ref for sphFatal()
  299. /// format current timestamp for logging
  300. int sphFormatCurrentTime ( char * sTimeBuf, int iBufLen )
  301. {
  302. #if !USE_WINDOWS
  303. struct timeval tv;
  304. gettimeofday ( &tv, NULL );
  305. struct tm tmp;
  306. time_t ts = (time_t) tv.tv_sec; // on some systems (eg. FreeBSD 6.2), tv.tv_sec has another type and we can't just pass it
  307. localtime_r ( &ts, &tmp );
  308. #else
  309. struct
  310. {
  311. time_t tv_sec;
  312. DWORD tv_usec;
  313. } tv;
  314. FILETIME ft;
  315. GetSystemTimeAsFileTime ( &ft );
  316. uint64_t ts = ( uint64_t(ft.dwHighDateTime)<<32 ) + uint64_t(ft.dwLowDateTime) - 116444736000000000ULL; // Jan 1, 1970 magic
  317. ts /= 10; // to microseconds
  318. tv.tv_sec = (DWORD)(ts/1000000);
  319. tv.tv_usec = (DWORD)(ts%1000000);
  320. struct tm tmp;
  321. tmp = *localtime ( &tv.tv_sec );
  322. #endif
  323. static const char * sWeekday[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  324. static const char * sMonth[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  325. return snprintf ( sTimeBuf, iBufLen, "%.3s %.3s%3d %.2d:%.2d:%.2d.%.3d %d",
  326. sWeekday [ tmp.tm_wday ],
  327. sMonth [ tmp.tm_mon ],
  328. tmp.tm_mday, tmp.tm_hour,
  329. tmp.tm_min, tmp.tm_sec, (int)(tv.tv_usec/1000),
  330. 1900+tmp.tm_year );
  331. }
  332. /// physically emit log entry
  333. /// buffer must have 1 extra byte for linefeed
  334. void sphLogEntry ( ESphLogLevel eLevel, char * sBuf )
  335. {
  336. #if USE_WINDOWS
  337. if ( g_bService && g_iLogFile==STDOUT_FILENO )
  338. {
  339. HANDLE hEventSource;
  340. LPCTSTR lpszStrings[2];
  341. hEventSource = RegisterEventSource ( NULL, g_sServiceName );
  342. if ( hEventSource )
  343. {
  344. lpszStrings[0] = g_sServiceName;
  345. lpszStrings[1] = sBuf;
  346. WORD eType = EVENTLOG_INFORMATION_TYPE;
  347. switch ( eLevel )
  348. {
  349. case LOG_FATAL: eType = EVENTLOG_ERROR_TYPE; break;
  350. case LOG_WARNING: eType = EVENTLOG_WARNING_TYPE; break;
  351. case LOG_INFO: eType = EVENTLOG_INFORMATION_TYPE; break;
  352. }
  353. ReportEvent ( hEventSource, // event log handle
  354. eType, // event type
  355. 0, // event category
  356. 0, // event identifier
  357. NULL, // no security identifier
  358. 2, // size of lpszStrings array
  359. 0, // no binary data
  360. lpszStrings, // array of strings
  361. NULL ); // no binary data
  362. DeregisterEventSource ( hEventSource );
  363. }
  364. } else
  365. #endif
  366. {
  367. strcat ( sBuf, "\n" );
  368. lseek ( g_iLogFile, 0, SEEK_END );
  369. write ( g_iLogFile, sBuf, strlen(sBuf) );
  370. if ( g_bLogStdout && g_iLogFile!=STDOUT_FILENO )
  371. {
  372. write ( STDOUT_FILENO, sBuf, strlen(sBuf) );
  373. }
  374. }
  375. }
  376. /// log entry (with log levels, dupe catching, etc)
  377. /// call with NULL format for dupe flushing
  378. void sphLog ( ESphLogLevel eLevel, const char * sFmt, va_list ap )
  379. {
  380. // dupe catcher state
  381. static const int FLUSH_THRESH_TIME = 1000000; // in microseconds
  382. static const int FLUSH_THRESH_COUNT = 100;
  383. static ESphLogLevel eLastLevel = LOG_INFO;
  384. static DWORD uLastEntry = 0;
  385. static int64_t tmLastStamp = -1000000-FLUSH_THRESH_TIME;
  386. static int iLastRepeats = 0;
  387. // only if we can
  388. if ( ( sFmt && eLevel>g_eLogLevel ) || ( g_iLogFile<0 && !g_bService ) )
  389. return;
  390. // format the banner
  391. char sTimeBuf[128];
  392. sphFormatCurrentTime ( sTimeBuf, sizeof(sTimeBuf) );
  393. const char * sBanner = "";
  394. if ( sFmt==NULL ) eLevel = eLastLevel;
  395. if ( eLevel==LOG_FATAL ) sBanner = "FATAL: ";
  396. if ( eLevel==LOG_WARNING ) sBanner = "WARNING: ";
  397. char sBuf [ 1024 ];
  398. if ( !g_bLogTty )
  399. snprintf ( sBuf, sizeof(sBuf)-1, "[%s] [%5d] %s", sTimeBuf, (int)getpid(), sBanner );
  400. else
  401. strcpy ( sBuf, sBanner );
  402. int iLen = strlen(sBuf);
  403. // format the message
  404. if ( sFmt )
  405. vsnprintf ( sBuf+iLen, sizeof(sBuf)-iLen-1, sFmt, ap );
  406. // catch dupes
  407. DWORD uEntry = sFmt ? sphCRC32 ( (const BYTE*)( sBuf+iLen ) ) : 0;
  408. int64_t tmNow = sphMicroTimer();
  409. // accumulate while possible
  410. if ( sFmt && eLevel==eLastLevel && uEntry==uLastEntry && iLastRepeats<FLUSH_THRESH_COUNT && tmNow<tmLastStamp+FLUSH_THRESH_TIME )
  411. {
  412. tmLastStamp = tmNow;
  413. iLastRepeats++;
  414. return;
  415. }
  416. // flush if needed
  417. if ( iLastRepeats!=0 && ( sFmt || tmNow>=tmLastStamp+FLUSH_THRESH_TIME ) )
  418. {
  419. // flush if we actually have something to flush, and
  420. // case 1: got a message we can't accumulate
  421. // case 2: got a periodic flush and been otherwise idle for a thresh period
  422. char sLast[256];
  423. strncpy ( sLast, sBuf, iLen );
  424. snprintf ( sLast+iLen, sizeof(sLast)-iLen, "last message repeated %d times", iLastRepeats );
  425. sphLogEntry ( eLastLevel, sLast );
  426. tmLastStamp = tmNow;
  427. iLastRepeats = 0;
  428. eLastLevel = LOG_INFO;
  429. uLastEntry = 0;
  430. }
  431. // was that a flush-only call?
  432. if ( !sFmt )
  433. return;
  434. tmLastStamp = tmNow;
  435. iLastRepeats = 0;
  436. eLastLevel = eLevel;
  437. uLastEntry = uEntry;
  438. // do the logging
  439. sphLogEntry ( eLevel, sBuf );
  440. }
  441. void sphFatal ( const char * sFmt, ... )
  442. {
  443. va_list ap;
  444. va_start ( ap, sFmt );
  445. sphLog ( LOG_FATAL, sFmt, ap );
  446. va_end ( ap );
  447. Shutdown ();
  448. exit ( 1 );
  449. }
  450. void sphWarning ( const char * sFmt, ... )
  451. {
  452. va_list ap;
  453. va_start ( ap, sFmt );
  454. sphLog ( LOG_WARNING, sFmt, ap );
  455. va_end ( ap );
  456. }
  457. void sphInfo ( const char * sFmt, ... )
  458. {
  459. va_list ap;
  460. va_start ( ap, sFmt );
  461. sphLog ( LOG_INFO, sFmt, ap );
  462. va_end ( ap );
  463. }
  464. void sphLogFatal ( const char * sFmt, ... )
  465. {
  466. va_list ap;
  467. va_start ( ap, sFmt );
  468. sphLog ( LOG_FATAL, sFmt, ap );
  469. va_end ( ap );
  470. }
  471. void LogInternalError ( const char * sError )
  472. {
  473. sphWarning( "INTERNAL ERROR: %s", sError );
  474. }
  475. /////////////////////////////////////////////////////////////////////////////
  476. struct StrBuf_t
  477. {
  478. protected:
  479. char m_sBuf [ 2048 ];
  480. char * m_pBuf;
  481. int m_iLeft;
  482. public:
  483. StrBuf_t ()
  484. {
  485. memset ( m_sBuf, 0, sizeof(m_sBuf) );
  486. m_iLeft = sizeof(m_sBuf)-1;
  487. m_pBuf = m_sBuf;
  488. }
  489. const char * cstr ()
  490. {
  491. return m_sBuf;
  492. }
  493. int GetLength ()
  494. {
  495. return sizeof(m_sBuf)-1-m_iLeft;
  496. }
  497. bool Append ( const char * s, bool bWhole )
  498. {
  499. int iLen = strlen(s);
  500. if ( bWhole && m_iLeft<iLen )
  501. return false;
  502. iLen = Min ( m_iLeft, iLen );
  503. memcpy ( m_pBuf, s, iLen );
  504. m_pBuf += iLen;
  505. m_iLeft -= iLen;
  506. return true;
  507. }
  508. const StrBuf_t & operator += ( const char * s )
  509. {
  510. Append ( s, false );
  511. return *this;
  512. }
  513. };
  514. struct SearchFailure_t
  515. {
  516. public:
  517. CSphString m_sIndex; ///< searched index name
  518. CSphString m_sError; ///< search error message
  519. public:
  520. SearchFailure_t () {}
  521. SearchFailure_t ( const CSphString & sIndex, const CSphString & sError )
  522. {
  523. m_sIndex = sIndex;
  524. m_sError = sError;
  525. if ( m_sIndex.IsEmpty() ) m_sIndex = "(no index name)";
  526. if ( m_sError.IsEmpty() ) m_sError = "(no message)";
  527. }
  528. public:
  529. bool operator == ( const SearchFailure_t & r ) const
  530. {
  531. return m_sIndex==r.m_sIndex && m_sError==r.m_sError;
  532. }
  533. bool operator < ( const SearchFailure_t & r ) const
  534. {
  535. int iRes = strcmp ( m_sError.cstr(), r.m_sError.cstr() );
  536. if ( !iRes )
  537. iRes = strcmp ( m_sIndex.cstr(), r.m_sIndex.cstr() );
  538. return iRes<0;
  539. }
  540. const SearchFailure_t & operator = ( const SearchFailure_t & r )
  541. {
  542. m_sIndex = r.m_sIndex;
  543. m_sError = r.m_sError;
  544. return *this;
  545. }
  546. };
  547. class SearchFailuresLog_i
  548. {
  549. public:
  550. virtual ~SearchFailuresLog_i () {}
  551. virtual void SetIndex ( const char * sIndex ) = 0;
  552. virtual void SetPrefix ( const char * sTemplate, ... ) = 0;
  553. virtual void Submit ( const char * sTemplate, ... ) = 0;
  554. };
  555. class SearchFailuresLog_c : public SearchFailuresLog_i
  556. {
  557. protected:
  558. CSphString m_sIndex;
  559. CSphString m_sPrefix;
  560. CSphVector<SearchFailure_t> m_dLog;
  561. public:
  562. void SetIndex ( const char * sIndex )
  563. {
  564. m_sIndex = sIndex;
  565. }
  566. void SetPrefix ( const char * sTemplate, ... )
  567. {
  568. va_list ap;
  569. va_start ( ap, sTemplate );
  570. m_sPrefix.SetSprintfVa ( sTemplate, ap );
  571. va_end ( ap );
  572. }
  573. void Submit ( const char * sTemplate, ... )
  574. {
  575. va_list ap;
  576. va_start ( ap, sTemplate );
  577. VaSubmit ( ap, sTemplate );
  578. va_end ( ap );
  579. }
  580. void SubmitEx ( const char * sIndex, const char * sTemplate, ... )
  581. {
  582. m_sIndex = sIndex;
  583. m_sPrefix = "";
  584. va_list ap;
  585. va_start ( ap, sTemplate );
  586. VaSubmit ( ap, sTemplate );
  587. va_end ( ap );
  588. }
  589. public:
  590. void VaSetPrefix ( va_list ap, const char * sTemplate )
  591. {
  592. m_sPrefix.SetSprintfVa ( sTemplate, ap );
  593. }
  594. void VaSubmit ( va_list ap, const char * sTemplate )
  595. {
  596. assert ( !m_sIndex.IsEmpty() );
  597. char sBuf [ 2048 ];
  598. snprintf ( sBuf, sizeof(sBuf), "%s", m_sPrefix.IsEmpty() ? "" : m_sPrefix.cstr() );
  599. int iLen = strlen(sBuf);
  600. vsnprintf ( sBuf+iLen, sizeof(sBuf)-iLen, sTemplate, ap );
  601. m_dLog.Add ( SearchFailure_t ( m_sIndex, sBuf ) );
  602. }
  603. public:
  604. bool IsEmpty ()
  605. {
  606. return m_dLog.GetLength()==0;
  607. }
  608. void BuildReport ( StrBuf_t & sReport )
  609. {
  610. if ( IsEmpty() )
  611. return;
  612. // collapse same messages
  613. m_dLog.Sort ();
  614. int iSpanStart = 0;
  615. for ( int i=1; i<=m_dLog.GetLength(); i++ )
  616. {
  617. // keep scanning while error text is the same
  618. if ( i!=m_dLog.GetLength() )
  619. if ( m_dLog[i].m_sError==m_dLog[i-1].m_sError )
  620. continue;
  621. // build current span
  622. StrBuf_t sSpan;
  623. if ( iSpanStart )
  624. sSpan += "; ";
  625. sSpan += "index ";
  626. for ( int j=iSpanStart; j<i; j++ )
  627. {
  628. if ( j!=iSpanStart )
  629. sSpan += ",";
  630. sSpan += m_dLog[j].m_sIndex.cstr();
  631. }
  632. sSpan += ": ";
  633. if ( !sSpan.Append ( m_dLog[iSpanStart].m_sError.cstr(), true ) )
  634. break;
  635. // flush current span
  636. if ( !sReport.Append ( sSpan.cstr(), true ) )
  637. break;
  638. // done
  639. iSpanStart = i;
  640. }
  641. }
  642. };
  643. class SearchFailuresLogset_c : public SearchFailuresLog_i
  644. {
  645. protected:
  646. CSphVector<SearchFailuresLog_c> m_dLogs;
  647. int m_iStart;
  648. int m_iEnd;
  649. public:
  650. SearchFailuresLogset_c ()
  651. : m_iStart ( -1 )
  652. , m_iEnd ( -1 )
  653. {}
  654. virtual void SetSize ( int iSize )
  655. {
  656. m_dLogs.Resize ( iSize );
  657. }
  658. virtual void SetSubset ( int iStart, int iEnd )
  659. {
  660. m_iStart = iStart;
  661. m_iEnd = iEnd;
  662. }
  663. public:
  664. virtual void SetIndex ( const char * sIndex )
  665. {
  666. for ( int i=m_iStart; i<=m_iEnd; i++ )
  667. m_dLogs[i].SetIndex ( sIndex );
  668. }
  669. virtual void SetPrefix ( const char * sTemplate, ... )
  670. {
  671. for ( int i=m_iStart; i<=m_iEnd; i++ )
  672. {
  673. va_list ap;
  674. va_start ( ap, sTemplate );
  675. m_dLogs[i].VaSetPrefix ( ap, sTemplate );
  676. va_end ( ap );
  677. }
  678. }
  679. virtual void Submit ( const char * sTemplate, ... )
  680. {
  681. for ( int i=m_iStart; i<=m_iEnd; i++ )
  682. {
  683. va_list ap;
  684. va_start ( ap, sTemplate );
  685. m_dLogs[i].VaSubmit ( ap, sTemplate );
  686. va_end ( ap );
  687. }
  688. }
  689. SearchFailuresLog_c & operator [] ( int iIndex )
  690. {
  691. return m_dLogs[iIndex];
  692. }
  693. };
  694. /////////////////////////////////////////////////////////////////////////////
  695. // SIGNAL HANDLERS
  696. /////////////////////////////////////////////////////////////////////////////
  697. void Shutdown ()
  698. {
  699. // some head-only shutdown procedures
  700. if ( g_bHeadDaemon )
  701. {
  702. SafeDelete ( g_pCfg );
  703. // save attribute updates for all local indexes
  704. g_hIndexes.IterateStart ();
  705. while ( g_hIndexes.IterateNext () )
  706. {
  707. const ServedIndex_t & tServed = g_hIndexes.IterateGet ();
  708. if ( !tServed.m_bEnabled )
  709. continue;
  710. if ( !tServed.m_pIndex->SaveAttributes () )
  711. sphWarning ( "index %s: attrs save failed: %s",
  712. g_hIndexes.IterateGetKey().cstr(), tServed.m_pIndex->GetLastError().cstr() );
  713. }
  714. // unlock indexes
  715. g_hIndexes.IterateStart();
  716. while ( g_hIndexes.IterateNext() )
  717. g_hIndexes.IterateGet().m_pIndex->Unlock();
  718. g_hIndexes.Reset();
  719. sphShutdownWordforms ();
  720. // remove pid
  721. if ( g_sPidFile )
  722. {
  723. ::close ( g_iPidFD );
  724. ::unlink ( g_sPidFile );
  725. }
  726. }
  727. ARRAY_FOREACH ( i, g_dListeners )
  728. if ( g_dListeners[i].m_iSock>=0 )
  729. sphSockClose ( g_dListeners[i].m_iSock );
  730. #if USE_WINDOWS
  731. CloseHandle ( g_hPipe );
  732. #endif
  733. if ( g_bHeadDaemon )
  734. sphInfo ( "shutdown complete" );
  735. }
  736. #if !USE_WINDOWS
  737. void HandleCrash ( int )
  738. {
  739. static char sBuffer[1024];
  740. int iFd;
  741. if ( !g_pCrashLog_LastQuery )
  742. return;
  743. snprintf ( sBuffer, sizeof(sBuffer), "%s.%d", g_sCrashLog_Path, (int)getpid() );
  744. if ( ( iFd = open ( sBuffer, O_WRONLY | O_CREAT | O_TRUNC, 0644 ) ) != -1 )
  745. {
  746. const int iSize = Min( g_iCrashLog_LastQuerySize, g_iMaxPacketSize );
  747. write ( iFd, g_dCrashLog_LastHello, sizeof(g_dCrashLog_LastHello) );
  748. write ( iFd, g_pCrashLog_LastQuery, iSize );
  749. close ( iFd );
  750. }
  751. else
  752. sphWarning ( "crash log creation failed, errno=%d\n", errno );
  753. }
  754. void sighup ( int )
  755. {
  756. g_bDoRotate = true;
  757. g_bGotSighup = true;
  758. }
  759. void sigterm ( int )
  760. {
  761. // in child, bail out immediately
  762. if ( !g_bHeadDaemon )
  763. exit ( 0 );
  764. // in head, perform a clean shutdown
  765. g_bGotSigterm = true;
  766. }
  767. void sigchld ( int )
  768. {
  769. g_bGotSigchld = true;
  770. }
  771. void sigusr1 ( int )
  772. {
  773. g_bGotSigusr1 = true;
  774. }
  775. #endif // !USE_WINDOWS
  776. void SetSignalHandlers ()
  777. {
  778. #if !USE_WINDOWS
  779. struct sigaction sa;
  780. sigfillset ( &sa.sa_mask );
  781. sa.sa_flags = SA_NOCLDSTOP;
  782. bool bSignalsSet = false;
  783. for ( ;; )
  784. {
  785. sa.sa_handler = sigterm; if ( sigaction ( SIGTERM, &sa, NULL )!=0 ) break;
  786. sa.sa_handler = sigterm; if ( sigaction ( SIGINT, &sa, NULL )!=0 ) break;
  787. sa.sa_handler = sighup; if ( sigaction ( SIGHUP, &sa, NULL )!=0 ) break;
  788. sa.sa_handler = sigusr1; if ( sigaction ( SIGUSR1, &sa, NULL )!=0 ) break;
  789. sa.sa_handler = sigchld; if ( sigaction ( SIGCHLD, &sa, NULL )!=0 ) break;
  790. sa.sa_handler = SIG_IGN; if ( sigaction ( SIGPIPE, &sa, NULL )!=0 ) break;
  791. if ( g_bCrashLog_Enabled )
  792. {
  793. sa.sa_flags |= SA_RESETHAND;
  794. sa.sa_handler = HandleCrash; if ( sigaction ( SIGSEGV, &sa, NULL )!=0 ) break;
  795. sa.sa_handler = HandleCrash; if ( sigaction ( SIGBUS, &sa, NULL )!=0 ) break;
  796. sa.sa_handler = HandleCrash; if ( sigaction ( SIGABRT, &sa, NULL )!=0 ) break;
  797. sa.sa_handler = HandleCrash; if ( sigaction ( SIGILL, &sa, NULL )!=0 ) break;
  798. sa.sa_handler = HandleCrash; if ( sigaction ( SIGFPE, &sa, NULL )!=0 ) break;
  799. }
  800. bSignalsSet = true;
  801. break;
  802. }
  803. if ( !bSignalsSet )
  804. sphFatal ( "sigaction(): %s", strerror(errno) );
  805. #endif
  806. }
  807. /////////////////////////////////////////////////////////////////////////////
  808. // NETWORK STUFF
  809. /////////////////////////////////////////////////////////////////////////////
  810. const int WIN32_PIPE_BUFSIZE = 32;
  811. #if USE_WINDOWS
  812. /// on Windows, the wrapper just prevents the warnings
  813. void sphFDSet ( int fd, fd_set * fdset )
  814. {
  815. #pragma warning(disable:4127) // conditional expr is const
  816. #pragma warning(disable:4389) // signed/unsigned mismatch
  817. FD_SET ( fd, fdset );
  818. #pragma warning(default:4127) // conditional expr is const
  819. #pragma warning(default:4389) // signed/unsigned mismatch
  820. }
  821. #else // !USE_WINDOWS
  822. #define SPH_FDSET_OVERFLOW(_fd) ((_fd) < 0 || (_fd) >= FD_SETSIZE)
  823. /// on UNIX, we also check that the descript won't corrupt the stack
  824. void sphFDSet ( int fd, fd_set * set)
  825. {
  826. if ( SPH_FDSET_OVERFLOW(fd) )
  827. sphFatal ( "sphFDSet() failed fd=%d, FD_SETSIZE=%d", fd, FD_SETSIZE );
  828. else
  829. FD_SET ( fd, set );
  830. }
  831. #endif // USE_WINDOWS
  832. const char * sphSockError ( int iErr=0 )
  833. {
  834. #if USE_WINDOWS
  835. if ( iErr==0 )
  836. iErr = WSAGetLastError ();
  837. static char sBuf [ 256 ];
  838. _snprintf ( sBuf, sizeof(sBuf), "WSA error %d", iErr );
  839. return sBuf;
  840. #else
  841. return strerror ( errno );
  842. #endif
  843. }
  844. int sphSockGetErrno ()
  845. {
  846. #if USE_WINDOWS
  847. return WSAGetLastError();
  848. #else
  849. return errno;
  850. #endif
  851. }
  852. void sphSockSetErrno ( int iErr )
  853. {
  854. #if USE_WINDOWS
  855. WSASetLastError ( iErr );
  856. #else
  857. errno = iErr;
  858. #endif
  859. }
  860. /// formats IP address given in network byte order into sBuffer
  861. /// returns the buffer
  862. char * sphFormatIP ( char * sBuffer, int iBufferSize, DWORD uAddress )
  863. {
  864. const BYTE *a = (const BYTE *)&uAddress;
  865. snprintf ( sBuffer, iBufferSize, "%u.%u.%u.%u", a[0], a[1], a[2], a[3] );
  866. return sBuffer;
  867. }
  868. static const bool GETADDR_STRICT = true; ///< strict check, will die with sphFatal() on failure
  869. DWORD sphGetAddress ( const char * sHost, bool bFatal=false )
  870. {
  871. struct hostent * pHost = gethostbyname ( sHost );
  872. if ( pHost==NULL || pHost->h_addrtype!=AF_INET)
  873. {
  874. if ( bFatal )
  875. sphFatal ( "no AF_INET address found for: %s", sHost );
  876. return 0;
  877. }
  878. struct in_addr ** ppAddrs = (struct in_addr **)pHost->h_addr_list;
  879. assert ( ppAddrs[0] );
  880. assert ( sizeof(DWORD)==pHost->h_length );
  881. DWORD uAddr;
  882. memcpy ( &uAddr, ppAddrs[0], sizeof(DWORD) );
  883. if ( ppAddrs[1] )
  884. {
  885. char sBuf [ SPH_ADDRESS_SIZE ];
  886. sphWarning ( "multiple addresses found for '%s', using the first one (ip=%s)",
  887. sHost, sphFormatIP ( sBuf, sizeof(sBuf), uAddr ) );
  888. }
  889. return uAddr;
  890. }
  891. #if !USE_WINDOWS
  892. int sphCreateUnixSocket ( const char * sPath )
  893. {
  894. static struct sockaddr_un uaddr;
  895. size_t len = strlen ( sPath );
  896. if ( len + 1 > sizeof( uaddr.sun_path ) )
  897. sphFatal ( "UNIX socket path is too long (len=%d)", len );
  898. sphInfo ( "listening on UNIX socket %s", sPath );
  899. memset ( &uaddr, 0, sizeof(uaddr) );
  900. uaddr.sun_family = AF_UNIX;
  901. memcpy ( uaddr.sun_path, sPath, len + 1 );
  902. int iSock = socket ( AF_UNIX, SOCK_STREAM, 0 );
  903. if ( iSock == -1 )
  904. sphFatal ( "failed to create UNIX socket: %s", sphSockError() );
  905. if ( unlink ( sPath ) == -1 )
  906. {
  907. if ( errno != ENOENT )
  908. sphFatal ( "unlink() on UNIX socket file failed: %s", sphSockError() );
  909. }
  910. int iMask = umask ( 0 );
  911. if ( bind ( iSock, (struct sockaddr *)&uaddr, sizeof(uaddr) ) != 0 )
  912. sphFatal ( "bind() on UNIX socket failed: %s", sphSockError() );
  913. umask ( iMask );
  914. return iSock;
  915. }
  916. #endif // !USE_WINDOWS
  917. int sphCreateInetSocket ( DWORD uAddr, int iPort )
  918. {
  919. char sAddress[SPH_ADDRESS_SIZE];
  920. sphFormatIP( sAddress, SPH_ADDRESS_SIZE, uAddr );
  921. if ( uAddr == htonl(INADDR_ANY) )
  922. sphInfo ( "listening on all interfaces, port=%d", iPort );
  923. else
  924. sphInfo ( "listening on %s:%d", sAddress, iPort );
  925. static struct sockaddr_in iaddr;
  926. memset ( &iaddr, 0, sizeof(iaddr) );
  927. iaddr.sin_family = AF_INET;
  928. iaddr.sin_addr.s_addr = uAddr;
  929. iaddr.sin_port = htons ( (short)iPort );
  930. int iSock = socket ( AF_INET, SOCK_STREAM, 0 );
  931. if ( iSock == -1 )
  932. sphFatal ( "failed to create TCP socket: %s", sphSockError() );
  933. int iOn = 1;
  934. if ( setsockopt ( iSock, SOL_SOCKET, SO_REUSEADDR, (char*)&iOn, sizeof(iOn) ) )
  935. sphFatal ( "setsockopt() failed: %s", sphSockError() );
  936. int iTries = 12;
  937. int iRes;
  938. do
  939. {
  940. iRes = bind ( iSock, (struct sockaddr *)&iaddr, sizeof(iaddr) );
  941. if ( iRes==0 )
  942. break;
  943. sphInfo ( "bind() failed on %s, retrying...", sAddress );
  944. sphSleepMsec ( 3000 );
  945. } while ( --iTries>0 );
  946. if ( iRes )
  947. sphFatal ( "bind() failed on %s: %s", sAddress, sphSockError() );
  948. return iSock;
  949. }
  950. inline bool IsPortInRange ( int iPort )
  951. {
  952. return ( iPort > 0 ) && ( iPort <= 0xFFFF );
  953. }
  954. void CheckPort ( int iPort )
  955. {
  956. if ( !IsPortInRange(iPort) )
  957. sphFatal ( "port %d is out of range", iPort );
  958. }
  959. ProtocolType_e ProtoByName ( const CSphString & sProto )
  960. {
  961. if ( sProto=="sphinx" ) return PROTO_SPHINX;
  962. else if ( sProto=="mysql41" ) return PROTO_MYSQL41;
  963. sphFatal ( "unknown listen protocol type '%s'", sProto.cstr() ? sProto.cstr() : "(NULL)" );
  964. return PROTO_SPHINX; // fix MSVC warning
  965. }
  966. struct ListenerDesc_t
  967. {
  968. ProtocolType_e m_eProto;
  969. CSphString m_sUnix;
  970. DWORD m_uIP;
  971. int m_iPort;
  972. };
  973. ListenerDesc_t ParseListener ( const char * sSpec )
  974. {
  975. ListenerDesc_t tRes;
  976. tRes.m_eProto = PROTO_SPHINX;
  977. tRes.m_sUnix = "";
  978. tRes.m_uIP = htonl(INADDR_ANY);
  979. tRes.m_iPort = SEARCHD_DEFAULT_PORT;
  980. // split by colon
  981. int iParts = 0;
  982. CSphString sParts[3];
  983. const char * sPart = sSpec;
  984. for ( const char * p = sSpec; ; p++ )
  985. if ( *p=='\0' || *p==':' )
  986. {
  987. if ( iParts==3 )
  988. sphFatal ( "invalid listen format (too many fields)" );
  989. sParts[iParts++].SetBinary ( sPart, p-sPart );
  990. if ( !*p )
  991. break; // bail out on zero
  992. sPart = p+1;
  993. }
  994. assert ( iParts>=1 && iParts<=3 );
  995. // handle UNIX socket case
  996. // might be either name on itself (1 part), or name+protocol (2 parts)
  997. sPart = sParts[0].cstr();
  998. if ( sPart[0]=='/' )
  999. {
  1000. if ( iParts>2 )
  1001. sphFatal ( "invalid listen format (too many fields)" );
  1002. if ( iParts==2 )
  1003. tRes.m_eProto = ProtoByName ( sParts[1] );
  1004. #if USE_WINDOWS
  1005. sphFatal ( "UNIX sockets are not supported on Windows" );
  1006. #else
  1007. tRes.m_sUnix = sPart;
  1008. return tRes;
  1009. #endif
  1010. }
  1011. // handle TCP port case
  1012. // one part. might be either port name, or host name, or UNIX socket name
  1013. if ( iParts==1 )
  1014. {
  1015. sPart = sParts[0].cstr();
  1016. int iLen = strlen(sPart);
  1017. bool bAllDigits = true;
  1018. for ( int i=0; i<iLen && bAllDigits; i++ )
  1019. if ( !isdigit ( sPart[i] ) )
  1020. bAllDigits = false;
  1021. if ( bAllDigits && iLen<=5 )
  1022. {
  1023. // port name on itself
  1024. tRes.m_uIP = htonl(INADDR_ANY);
  1025. tRes.m_iPort = atol(sSpec);
  1026. CheckPort ( tRes.m_iPort );
  1027. } else
  1028. {
  1029. // host name on itself
  1030. tRes.m_uIP = sphGetAddress ( sSpec, GETADDR_STRICT );
  1031. tRes.m_iPort = SEARCHD_DEFAULT_PORT;
  1032. }
  1033. return tRes;
  1034. }
  1035. // two or three parts. host name, port name, and optional protocol type
  1036. if ( iParts==3 )
  1037. tRes.m_eProto = ProtoByName ( sParts[2] );
  1038. tRes.m_iPort = atol ( sParts[1].cstr() );
  1039. CheckPort ( tRes.m_iPort );
  1040. tRes.m_uIP = sParts[0].IsEmpty()
  1041. ? htonl(INADDR_ANY)
  1042. : sphGetAddress ( sParts[0].cstr(), GETADDR_STRICT );
  1043. return tRes;
  1044. }
  1045. void AddListener ( const CSphString & sListen )
  1046. {
  1047. ListenerDesc_t tDesc = ParseListener ( sListen.cstr() );
  1048. Listener_t tListener;
  1049. tListener.m_eProto = tDesc.m_eProto;
  1050. #if !USE_WINDOWS
  1051. if ( !tDesc.m_sUnix.IsEmpty() )
  1052. tListener.m_iSock = sphCreateUnixSocket ( tDesc.m_sUnix.cstr() );
  1053. else
  1054. #endif
  1055. tListener.m_iSock = sphCreateInetSocket ( tDesc.m_uIP, tDesc.m_iPort );
  1056. g_dListeners.Add ( tListener );
  1057. }
  1058. int sphSetSockNB ( int iSock )
  1059. {
  1060. #if USE_WINDOWS
  1061. u_long uMode = 1;
  1062. return ioctlsocket ( iSock, FIONBIO, &uMode );
  1063. #else
  1064. return fcntl ( iSock, F_SETFL, O_NONBLOCK );
  1065. #endif
  1066. }
  1067. int sphSockRead ( int iSock, void * buf, int iLen, int iReadTimeout )
  1068. {
  1069. assert ( iLen>0 );
  1070. int64_t tmMaxTimer = sphMicroTimer() + 1000000*Max ( 1, iReadTimeout ); // in microseconds
  1071. int iLeftBytes = iLen; // bytes to read left
  1072. char * pBuf = (char*) buf;
  1073. int iRes = -1, iErr = 0;
  1074. while ( iLeftBytes>0 )
  1075. {
  1076. const int64_t tmMicroLeft = tmMaxTimer - sphMicroTimer();
  1077. if ( tmMicroLeft<=0 )
  1078. break; // timed out
  1079. fd_set fdRead;
  1080. FD_ZERO ( &fdRead );
  1081. sphFDSet ( iSock, &fdRead );
  1082. fd_set fdExcept;
  1083. FD_ZERO ( &fdExcept );
  1084. sphFDSet ( iSock, &fdExcept );
  1085. struct timeval tv;
  1086. tv.tv_sec = (int)( tmMicroLeft / 1000000 );
  1087. tv.tv_usec = (int)( tmMicroLeft % 1000000 );
  1088. iRes = ::select ( iSock+1, &fdRead, NULL, &fdExcept, &tv );
  1089. // if there was EINTR, retry
  1090. if ( iRes==-1 )
  1091. {
  1092. iErr = sphSockGetErrno();
  1093. if ( iErr==EINTR )
  1094. continue;
  1095. sphSockSetErrno ( iErr );
  1096. return -1;
  1097. }
  1098. // if there was a timeout, report it as an error
  1099. if ( iRes==0 )
  1100. {
  1101. sphSockSetErrno ( ETIMEDOUT );
  1102. return -1;
  1103. }
  1104. // try to receive next chunk
  1105. iRes = sphSockRecv ( iSock, pBuf, iLeftBytes );
  1106. // if there was eof, we're done
  1107. if ( iRes==0 )
  1108. {
  1109. sphSockSetErrno ( ECONNRESET );
  1110. return -1;
  1111. }
  1112. // if there was EINTR, retry
  1113. if ( iRes==-1 )
  1114. {
  1115. iErr = sphSockGetErrno();
  1116. if ( iErr==EINTR )
  1117. continue;
  1118. sphSockSetErrno ( iErr );
  1119. return -1;
  1120. }
  1121. // update
  1122. pBuf += iRes;
  1123. iLeftBytes -= iRes;
  1124. }
  1125. // if there was a timeout, report it as an error
  1126. if ( iLeftBytes!=0 )
  1127. {
  1128. sphSockSetErrno ( ETIMEDOUT );
  1129. return -1;
  1130. }
  1131. return iLen;
  1132. }
  1133. /////////////////////////////////////////////////////////////////////////////
  1134. // NETWORK BUFFERS
  1135. /////////////////////////////////////////////////////////////////////////////
  1136. /// fixed-memory response buffer
  1137. /// tracks usage, and flushes to network when necessary
  1138. class NetOutputBuffer_c
  1139. {
  1140. public:
  1141. NetOutputBuffer_c ( int iSock );
  1142. bool SendInt ( int iValue ) { return SendT<int> ( htonl ( iValue ) ); }
  1143. bool SendDword ( DWORD iValue ) { return SendT<DWORD> ( htonl ( iValue ) ); }
  1144. bool SendLSBDword ( DWORD v ) { SendByte ( BYTE(v&0xff) ); SendByte ( BYTE((v>>8)&0xff) ); SendByte ( BYTE((v>>16)&0xff) ); return SendByte ( BYTE((v>>24)&0xff) ); }
  1145. bool SendWord ( WORD iValue ) { return SendT<WORD> ( htons ( iValue ) ); }
  1146. bool SendUint64 ( uint64_t iValue ) { SendT<DWORD> ( htonl ( (DWORD)(iValue>>32) ) ); return SendT<DWORD> ( htonl ( (DWORD)(iValue&0xffffffffUL) ) ); }
  1147. bool SendFloat ( float fValue ) { return SendT<DWORD> ( htonl ( sphF2DW ( fValue ) ) ); }
  1148. bool SendByte ( BYTE uValue ) { return SendT<BYTE> ( uValue ); }
  1149. #if USE_64BIT
  1150. bool SendDocid ( SphDocID_t iValue ) { return SendUint64 ( iValue ); }
  1151. #else
  1152. bool SendDocid ( SphDocID_t iValue ) { return SendDword ( iValue ); }
  1153. #endif
  1154. bool SendString ( const char * sStr );
  1155. int GetMysqlPacklen ( const char * sStr ) const;
  1156. bool SendMysqlString ( const char * sStr );
  1157. bool Flush ();
  1158. bool GetError () { return m_bError; }
  1159. int GetSentCount () { return m_iSent; }
  1160. protected:
  1161. BYTE m_dBuffer[8192]; ///< my buffer
  1162. BYTE * m_pBuffer; ///< my current buffer position
  1163. int m_iSock; ///< my socket
  1164. bool m_bError; ///< if there were any write errors
  1165. int m_iSent;
  1166. protected:
  1167. bool SetError ( bool bValue ); ///< set error flag
  1168. bool FlushIf ( int iToAdd ); ///< flush if there's not enough free space to add iToAdd bytes
  1169. public:
  1170. bool SendBytes ( const void * pBuf, int iLen ); ///< (was) protected to avoid network-vs-host order bugs
  1171. template < typename T > bool SendT ( T tValue ); ///< (was) protected to avoid network-vs-host order bugs
  1172. };
  1173. /// generic request buffer
  1174. class InputBuffer_c
  1175. {
  1176. public:
  1177. InputBuffer_c ( const BYTE * pBuf, int iLen );
  1178. virtual ~InputBuffer_c () {}
  1179. int GetInt () { return ntohl ( GetT<int> () ); }
  1180. WORD GetWord () { return ntohs ( GetT<WORD> () ); }
  1181. DWORD GetDword () { return ntohl ( GetT<DWORD> () ); }
  1182. DWORD GetLSBDword () { return GetByte() + ( GetByte()<<8 ) + ( GetByte()<<16 ) + ( GetByte()<<24 ); }
  1183. uint64_t GetUint64() { uint64_t uRes = GetDword(); return (uRes<<32)+GetDword(); };
  1184. BYTE GetByte () { return GetT<BYTE> (); }
  1185. float GetFloat () { return sphDW2F ( ntohl ( GetT<DWORD> () ) ); }
  1186. CSphString GetString ();
  1187. CSphString GetRawString ( int iLen );
  1188. int GetDwords ( DWORD ** pBuffer, int iMax, const char * sErrorTemplate );
  1189. bool GetError () { return m_bError; }
  1190. template < typename T > bool GetDwords ( CSphVector<T> & dBuffer, int iMax, const char * sErrorTemplate );
  1191. template < typename T > bool GetQwords ( CSphVector<T> & dBuffer, int iMax, const char * sErrorTemplate );
  1192. virtual void SendErrorReply ( const char *, ... ) = 0;
  1193. protected:
  1194. const BYTE * m_pBuf;
  1195. const BYTE * m_pCur;
  1196. bool m_bError;
  1197. int m_iLen;
  1198. protected:
  1199. void SetError ( bool bError ) { m_bError = bError; }
  1200. bool GetBytes ( void * pBuf, int iLen );
  1201. template < typename T > T GetT ();
  1202. };
  1203. /// simple memory request buffer
  1204. class MemInputBuffer_c : public InputBuffer_c
  1205. {
  1206. public:
  1207. MemInputBuffer_c ( const BYTE * pBuf, int iLen ) : InputBuffer_c ( pBuf, iLen ) {}
  1208. virtual void SendErrorReply ( const char *, ... ) {}
  1209. };
  1210. /// simple network request buffer
  1211. class NetInputBuffer_c : public InputBuffer_c
  1212. {
  1213. public:
  1214. NetInputBuffer_c ( int iSock );
  1215. virtual ~NetInputBuffer_c ();
  1216. bool ReadFrom ( int iLen, int iTimeout );
  1217. bool ReadFrom ( int iLen ) { return ReadFrom ( iLen, g_iReadTimeout ); };
  1218. virtual void SendErrorReply ( const char *, ... );
  1219. const BYTE * GetBufferPtr () const { return m_pBuf; }
  1220. protected:
  1221. static const int NET_MINIBUFFER_SIZE = 4096;
  1222. int m_iSock;
  1223. BYTE m_dMinibufer[NET_MINIBUFFER_SIZE];
  1224. int m_iMaxibuffer;
  1225. BYTE * m_pMaxibuffer;
  1226. };
  1227. /////////////////////////////////////////////////////////////////////////////
  1228. NetOutputBuffer_c::NetOutputBuffer_c ( int iSock )
  1229. : m_pBuffer ( m_dBuffer )
  1230. , m_iSock ( iSock )
  1231. , m_bError ( false )
  1232. , m_iSent ( 0 )
  1233. {
  1234. assert ( m_iSock>0 );
  1235. }
  1236. template < typename T > bool NetOutputBuffer_c::SendT ( T tValue )
  1237. {
  1238. if ( m_bError )
  1239. return false;
  1240. FlushIf ( sizeof(T) );
  1241. sphUnalignedWrite ( m_pBuffer, tValue );
  1242. m_pBuffer += sizeof(T);
  1243. assert ( m_pBuffer<m_dBuffer+sizeof(m_dBuffer) );
  1244. return true;
  1245. }
  1246. bool NetOutputBuffer_c::SendString ( const char * sStr )
  1247. {
  1248. if ( m_bError )
  1249. return false;
  1250. FlushIf ( sizeof(DWORD) );
  1251. int iLen = strlen(sStr);
  1252. SendInt ( iLen );
  1253. return SendBytes ( sStr, iLen );
  1254. }
  1255. int NetOutputBuffer_c::GetMysqlPacklen ( const char * sStr ) const
  1256. {
  1257. int iLen = strlen(sStr);
  1258. if ( iLen<251 ) return 1+iLen;
  1259. if ( iLen<=0xffff ) return 3+iLen;
  1260. return 5+iLen;
  1261. }
  1262. bool NetOutputBuffer_c::SendMysqlString ( const char * sStr )
  1263. {
  1264. if ( m_bError )
  1265. return false;
  1266. int iLen = strlen(sStr);
  1267. if ( iLen<251 )
  1268. {
  1269. SendByte ( BYTE(iLen) );
  1270. } else
  1271. {
  1272. assert ( iLen<=0xffff );
  1273. SendByte ( 252 );
  1274. SendByte ( BYTE(iLen&0xff) );
  1275. SendByte ( BYTE(iLen>>8) );
  1276. }
  1277. return SendBytes ( sStr, iLen );
  1278. }
  1279. bool NetOutputBuffer_c::SendBytes ( const void * pBuf, int iLen )
  1280. {
  1281. BYTE * pMy = (BYTE*)pBuf;
  1282. while ( iLen>0 && !m_bError )
  1283. {
  1284. int iLeft = sizeof(m_dBuffer) - ( m_pBuffer - m_dBuffer );
  1285. if ( iLen<=iLeft )
  1286. {
  1287. memcpy ( m_pBuffer, pMy, iLen );
  1288. m_pBuffer += iLen;
  1289. break;
  1290. }
  1291. memcpy ( m_pBuffer, pMy, iLeft );
  1292. m_pBuffer += iLeft;
  1293. Flush ();
  1294. pMy += iLeft;
  1295. iLen -= iLeft;
  1296. }
  1297. return !m_bError;
  1298. }
  1299. bool NetOutputBuffer_c::Flush ()
  1300. {
  1301. if ( m_bError )
  1302. return false;
  1303. int iLen = m_pBuffer-m_dBuffer;
  1304. if ( iLen==0 )
  1305. return true;
  1306. assert ( iLen>0 );
  1307. assert ( iLen<=(int)sizeof(m_dBuffer) );
  1308. char * pBuffer = (char *)&m_dBuffer[0];
  1309. const int64_t tmMaxTimer = sphMicroTimer() + g_iWriteTimeout*1000000; // in microseconds
  1310. while ( !m_bError )
  1311. {
  1312. int iRes = sphSockSend ( m_iSock, pBuffer, iLen );
  1313. if ( iRes < 0 )
  1314. {
  1315. int iErrno = sphSockGetErrno();
  1316. if ( iErrno != EAGAIN )
  1317. {
  1318. sphWarning ( "send() failed: %d: %s", iErrno, sphSockError(iErrno) );
  1319. m_bError = true;
  1320. break;
  1321. }
  1322. }
  1323. else
  1324. {
  1325. m_iSent += iRes;
  1326. pBuffer += iRes;
  1327. iLen -= iRes;
  1328. if ( iLen==0 )
  1329. break;
  1330. }
  1331. int64_t tmMicroLeft = tmMaxTimer - sphMicroTimer();
  1332. if ( tmMicroLeft>0 )
  1333. {
  1334. fd_set fdWrite;
  1335. FD_ZERO ( &fdWrite );
  1336. sphFDSet ( m_iSock, &fdWrite );
  1337. struct timeval tvTimeout;
  1338. tvTimeout.tv_sec = (int)( tmMicroLeft / 1000000 );
  1339. tvTimeout.tv_usec = (int)( tmMicroLeft % 1000000 );
  1340. iRes = select ( m_iSock+1, NULL, &fdWrite, NULL, &tvTimeout );
  1341. }
  1342. else
  1343. iRes = 0;
  1344. switch ( iRes )
  1345. {
  1346. case 1: // ready for writing
  1347. break;
  1348. case 0: // timed out
  1349. {
  1350. sphWarning ( "timed out while trying to flush network buffers" );
  1351. m_bError = true;
  1352. break;
  1353. }
  1354. case -1: // error
  1355. {
  1356. int iErrno = sphSockGetErrno();
  1357. if ( iErrno == EINTR )
  1358. break;
  1359. sphWarning ( "select() failed: %d: %s", iErrno, sphSockError(iErrno) );
  1360. m_bError = true;
  1361. break;
  1362. }
  1363. }
  1364. }
  1365. m_pBuffer = m_dBuffer;
  1366. return !m_bError;
  1367. }
  1368. bool NetOutputBuffer_c::FlushIf ( int iToAdd )
  1369. {
  1370. if ( m_pBuffer+iToAdd >= m_dBuffer+sizeof(m_dBuffer) )
  1371. return Flush ();
  1372. return !m_bError;
  1373. }
  1374. /////////////////////////////////////////////////////////////////////////////
  1375. InputBuffer_c::InputBuffer_c ( const BYTE * pBuf, int iLen )
  1376. : m_pBuf ( pBuf )
  1377. , m_pCur ( pBuf )
  1378. , m_bError ( !pBuf || iLen<0 )
  1379. , m_iLen ( iLen )
  1380. {}
  1381. template < typename T > T InputBuffer_c::GetT ()
  1382. {
  1383. if ( m_bError || ( m_pCur+sizeof(T) > m_pBuf+m_iLen ) )
  1384. {
  1385. SetError ( true );
  1386. return 0;
  1387. }
  1388. T iRes = sphUnalignedRead ( *(T*)m_pCur );
  1389. m_pCur += sizeof(T);
  1390. return iRes;
  1391. }
  1392. CSphString InputBuffer_c::GetString ()
  1393. {
  1394. CSphString sRes;
  1395. int iLen = GetInt ();
  1396. if ( m_bError || iLen<0 || iLen>g_iMaxPacketSize || ( m_pCur+iLen > m_pBuf+m_iLen ) )
  1397. {
  1398. SetError ( true );
  1399. return sRes;
  1400. }
  1401. sRes.SetBinary ( (char*)m_pCur, iLen );
  1402. m_pCur += iLen;
  1403. return sRes;
  1404. }
  1405. CSphString InputBuffer_c::GetRawString ( int iLen )
  1406. {
  1407. CSphString sRes;
  1408. if ( m_bError || iLen<0 || iLen>g_iMaxPacketSize || ( m_pCur+iLen > m_pBuf+m_iLen ) )
  1409. {
  1410. SetError ( true );
  1411. return sRes;
  1412. }
  1413. sRes.SetBinary ( (char*)m_pCur, iLen );
  1414. m_pCur += iLen;
  1415. return sRes;
  1416. }
  1417. bool InputBuffer_c::GetBytes ( void * pBuf, int iLen )
  1418. {
  1419. assert ( pBuf );
  1420. assert ( iLen>0 && iLen<=g_iMaxPacketSize );
  1421. if ( m_bError || ( m_pCur+iLen > m_pBuf+m_iLen ) )
  1422. {
  1423. SetError ( true );
  1424. return false;
  1425. }
  1426. memcpy ( pBuf, m_pCur, iLen );
  1427. m_pCur += iLen;
  1428. return true;
  1429. }
  1430. int InputBuffer_c::GetDwords ( DWORD ** ppBuffer, int iMax, const char * sErrorTemplate )
  1431. {
  1432. assert ( ppBuffer );
  1433. assert ( !(*ppBuffer) );
  1434. int iCount = GetInt ();
  1435. if ( iCount<0 || iCount>iMax )
  1436. {
  1437. SendErrorReply ( sErrorTemplate, iCount, iMax );
  1438. SetError ( true );
  1439. return -1;
  1440. }
  1441. if ( iCount )
  1442. {
  1443. assert ( !(*ppBuffer) ); // potential leak
  1444. (*ppBuffer) = new DWORD [ iCount ];
  1445. if ( !GetBytes ( (*ppBuffer), sizeof(int)*iCount ) )
  1446. {
  1447. SafeDeleteArray ( (*ppBuffer) );
  1448. return -1;
  1449. }
  1450. for ( int i=0; i<iCount; i++ )
  1451. (*ppBuffer)[i] = htonl ( (*ppBuffer)[i] );
  1452. }
  1453. return iCount;
  1454. }
  1455. template < typename T > bool InputBuffer_c::GetDwords ( CSphVector<T> & dBuffer, int iMax, const char * sErrorTemplate )
  1456. {
  1457. int iCount = GetInt ();
  1458. if ( iCount<0 || iCount>iMax )
  1459. {
  1460. SendErrorReply ( sErrorTemplate, iCount, iMax );
  1461. SetError ( true );
  1462. return false;
  1463. }
  1464. dBuffer.Resize ( iCount );
  1465. ARRAY_FOREACH ( i, dBuffer )
  1466. dBuffer[i] = GetDword ();
  1467. if ( m_bError )
  1468. dBuffer.Reset ();
  1469. return !m_bError;
  1470. }
  1471. template < typename T > bool InputBuffer_c::GetQwords ( CSphVector<T> & dBuffer, int iMax, const char * sErrorTemplate )
  1472. {
  1473. int iCount = GetInt ();
  1474. if ( iCount<0 || iCount>iMax )
  1475. {
  1476. SendErrorReply ( sErrorTemplate, iCount, iMax );
  1477. SetError ( true );
  1478. return false;
  1479. }
  1480. dBuffer.Resize ( iCount );
  1481. ARRAY_FOREACH ( i, dBuffer )
  1482. dBuffer[i] = GetUint64 ();
  1483. if ( m_bError )
  1484. dBuffer.Reset ();
  1485. return !m_bError;
  1486. }
  1487. /////////////////////////////////////////////////////////////////////////////
  1488. NetInputBuffer_c::NetInputBuffer_c ( int iSock )
  1489. : InputBuffer_c ( m_dMinibufer, sizeof(m_dMinibufer) )
  1490. , m_iSock ( iSock )
  1491. , m_iMaxibuffer ( 0 )
  1492. , m_pMaxibuffer ( NULL )
  1493. {}
  1494. NetInputBuffer_c::~NetInputBuffer_c ()
  1495. {
  1496. SafeDeleteArray ( m_pMaxibuffer );
  1497. }
  1498. bool NetInputBuffer_c::ReadFrom ( int iLen, int iTimeout )
  1499. {
  1500. if ( iLen<=0 || iLen>g_iMaxPacketSize || m_iSock<0 )
  1501. return false;
  1502. BYTE * pBuf = m_dMinibufer;
  1503. if ( iLen>NET_MINIBUFFER_SIZE )
  1504. {
  1505. if ( iLen>m_iMaxibuffer )
  1506. {
  1507. SafeDeleteArray ( m_pMaxibuffer );
  1508. m_pMaxibuffer = new BYTE [ iLen ];
  1509. m_iMaxibuffer = iLen;
  1510. }
  1511. pBuf = m_pMaxibuffer;
  1512. }
  1513. m_pCur = m_pBuf = pBuf;
  1514. int iGot = sphSockRead ( m_iSock, pBuf, iLen, iTimeout );
  1515. m_bError = ( iGot!=iLen );
  1516. m_iLen = m_bError ? 0 : iLen;
  1517. return !m_bError;
  1518. }
  1519. void NetInputBuffer_c::SendErrorReply ( const char * sTemplate, ... )
  1520. {
  1521. char dBuf [ 2048 ];
  1522. const int iHeaderLen = 12;
  1523. const int iMaxStrLen = sizeof(dBuf) - iHeaderLen - 1;
  1524. // fill header
  1525. WORD * p0 = (WORD*)&dBuf[0];
  1526. p0[0] = htons(SEARCHD_ERROR); // error code
  1527. p0[1] = 0; // version doesn't matter
  1528. // fill error string
  1529. char * sBuf = dBuf + iHeaderLen;
  1530. va_list ap;
  1531. va_start ( ap, sTemplate );
  1532. vsnprintf ( sBuf, iMaxStrLen, sTemplate, ap );
  1533. va_end ( ap );
  1534. sBuf[iMaxStrLen] = '\0';
  1535. int iStrLen = strlen(sBuf);
  1536. // fixup lengths
  1537. DWORD * p4 = (DWORD*)&dBuf[4];
  1538. p4[0] = htonl(4+iStrLen);
  1539. p4[1] = htonl(iStrLen);
  1540. // send!
  1541. sphSockSend ( m_iSock, dBuf, iHeaderLen+iStrLen );
  1542. }
  1543. // fix MSVC 2005 fuckup
  1544. #if USE_WINDOWS
  1545. #pragma conform(forScope,on)
  1546. #endif
  1547. /////////////////////////////////////////////////////////////////////////////
  1548. // DISTRIBUTED QUERIES
  1549. /////////////////////////////////////////////////////////////////////////////
  1550. /// remote agent state
  1551. enum AgentState_e
  1552. {
  1553. AGENT_UNUSED, ///< agent is unused for this request
  1554. AGENT_CONNECT, ///< connecting to agent
  1555. AGENT_HELLO, ///< waiting for "VER x" hello
  1556. AGENT_QUERY, ///< query sent, wating for reply
  1557. AGENT_REPLY, ///< reading reply
  1558. AGENT_RETRY ///< should retry
  1559. };
  1560. /// remote agent host/port
  1561. struct Agent_t
  1562. {
  1563. public:
  1564. CSphString m_sHost; ///< remote searchd host
  1565. int m_iPort; ///< remote searchd port, 0 if local
  1566. CSphString m_sPath; ///< local searchd UNIX socket path
  1567. CSphString m_sIndexes; ///< remote index names to query
  1568. bool m_bBlackhole; ///< blackhole agent flag
  1569. int m_iSock; ///< socket number, -1 if not connected
  1570. AgentState_e m_eState; ///< current state
  1571. bool m_bSuccess; ///< whether last request was succesful (ie. there are available results)
  1572. CSphString m_sFailure; ///< failure message
  1573. int m_iReplyStatus; ///< reply status code
  1574. int m_iReplySize; ///< how many reply bytes are there
  1575. int m_iReplyRead; ///< how many reply bytes are alredy received
  1576. BYTE * m_pReplyBuf; ///< reply buffer
  1577. CSphVector<CSphQueryResult> m_dResults; ///< multi-query results
  1578. int m_iFamily;
  1579. DWORD m_uAddr;
  1580. public:
  1581. Agent_t ()
  1582. : m_iPort ( -1 )
  1583. , m_bBlackhole ( false )
  1584. , m_iSock ( -1 )
  1585. , m_eState ( AGENT_UNUSED )
  1586. , m_bSuccess ( false )
  1587. , m_iReplyStatus ( -1 )
  1588. , m_iReplySize ( 0 )
  1589. , m_iReplyRead ( 0 )
  1590. , m_pReplyBuf ( NULL )
  1591. , m_uAddr ( 0 )
  1592. {
  1593. }
  1594. ~Agent_t ()
  1595. {
  1596. Close ();
  1597. }
  1598. void Close ()
  1599. {
  1600. SafeDeleteArray ( m_pReplyBuf );
  1601. if ( m_iSock>0 )
  1602. {
  1603. sphSockClose ( m_iSock );
  1604. m_iSock = -1;
  1605. if ( m_eState!=AGENT_RETRY )
  1606. m_eState = AGENT_UNUSED;
  1607. }
  1608. }
  1609. CSphString GetName() const
  1610. {
  1611. CSphString sName;
  1612. switch ( m_iFamily )
  1613. {
  1614. case AF_INET: sName.SetSprintf ( "%s:%u", m_sHost.cstr(), m_iPort ); break;
  1615. case AF_UNIX: sName = m_sPath; break;
  1616. }
  1617. return sName;
  1618. }
  1619. };
  1620. /// distributed index
  1621. struct DistributedIndex_t
  1622. {
  1623. CSphVector<Agent_t> m_dAgents; ///< remote agents
  1624. CSphVector<CSphString> m_dLocal; ///< local indexes
  1625. int m_iAgentConnectTimeout; ///< in msec
  1626. int m_iAgentQueryTimeout; ///< in msec
  1627. bool m_bToDelete; ///< should be deleted
  1628. DistributedIndex_t ()
  1629. : m_iAgentConnectTimeout ( 1000 )
  1630. , m_iAgentQueryTimeout ( 3000 )
  1631. , m_bToDelete ( false )
  1632. {}
  1633. };
  1634. static SmallStringHash_T < DistributedIndex_t > g_hDistIndexes;
  1635. /////////////////////////////////////////////////////////////////////////////
  1636. struct IRequestBuilder_t : public ISphNoncopyable
  1637. {
  1638. virtual ~IRequestBuilder_t () {} // to avoid gcc4 warns
  1639. virtual void BuildRequest ( const char * sIndexes, NetOutputBuffer_c & tOut ) const = 0;
  1640. };
  1641. struct IReplyParser_t
  1642. {
  1643. virtual ~IReplyParser_t () {} // to avoid gcc4 warns
  1644. virtual bool ParseReply ( MemInputBuffer_c & tReq, Agent_t & tAgent ) const = 0;
  1645. };
  1646. void ConnectToRemoteAgents ( CSphVector<Agent_t> & dAgents, bool bRetryOnly )
  1647. {
  1648. ARRAY_FOREACH ( iAgent, dAgents )
  1649. {
  1650. Agent_t & tAgent = dAgents[iAgent];
  1651. if ( bRetryOnly && ( tAgent.m_eState!=AGENT_RETRY ) )
  1652. continue;
  1653. tAgent.m_eState = AGENT_UNUSED;
  1654. tAgent.m_bSuccess = false;
  1655. socklen_t len = 0;
  1656. struct sockaddr_storage ss;
  1657. memset ( &ss, 0, sizeof(ss) );
  1658. ss.ss_family = (short)tAgent.m_iFamily;
  1659. if ( ss.ss_family == AF_INET )
  1660. {
  1661. struct sockaddr_in *in = (struct sockaddr_in *)&ss;
  1662. in->sin_port = htons ( (unsigned short)tAgent.m_iPort );
  1663. in->sin_addr.s_addr = tAgent.m_uAddr;
  1664. len = sizeof(*in);
  1665. }
  1666. #if !USE_WINDOWS
  1667. else if ( ss.ss_family == AF_UNIX )
  1668. {
  1669. struct sockaddr_un *un = (struct sockaddr_un *)&ss;
  1670. snprintf ( un->sun_path, sizeof(un->sun_path), "%s", tAgent.m_sPath.cstr() );
  1671. len = sizeof(*un);
  1672. }
  1673. #endif
  1674. tAgent.m_iSock = socket ( tAgent.m_iFamily, SOCK_STREAM, 0 );
  1675. if ( tAgent.m_iSock<0 )
  1676. {
  1677. tAgent.m_sFailure.SetSprintf ( "socket() failed: %s", sphSockError() );
  1678. return;
  1679. }
  1680. if ( sphSetSockNB ( tAgent.m_iSock )<0 )
  1681. {
  1682. tAgent.m_sFailure.SetSprintf ( "sphSetSockNB() failed: %s", sphSockError() );
  1683. return;
  1684. }
  1685. // count connects
  1686. if ( g_pStats )
  1687. {
  1688. g_tStatsMutex.Lock();
  1689. g_pStats->m_iAgentConnect++;
  1690. if ( bRetryOnly )
  1691. g_pStats->m_iAgentRetry++;
  1692. g_tStatsMutex.Unlock();
  1693. }
  1694. if ( connect ( tAgent.m_iSock, (struct sockaddr*)&ss, len )<0 )
  1695. {
  1696. int iErr = sphSockGetErrno();
  1697. if ( iErr!=EINPROGRESS && iErr!=EINTR && iErr!=EWOULDBLOCK ) // check for EWOULDBLOCK is for winsock only
  1698. {
  1699. tAgent.Close ();
  1700. tAgent.m_sFailure.SetSprintf ( "connect() failed: %s", sphSockError(iErr) );
  1701. tAgent.m_eState = AGENT_RETRY; // do retry on connect() failures
  1702. return;
  1703. } else
  1704. {
  1705. // connection in progress
  1706. tAgent.m_eState = AGENT_CONNECT;
  1707. }
  1708. } else
  1709. {
  1710. // socket connected, ready to read hello message
  1711. tAgent.m_eState = AGENT_HELLO;
  1712. }
  1713. }
  1714. }
  1715. int QueryRemoteAgents ( CSphVector<Agent_t> & dAgents, int iTimeout, const IRequestBuilder_t & tBuilder, int64_t * pWaited )
  1716. {
  1717. int iAgents = 0;
  1718. assert ( iTimeout>=0 );
  1719. int64_t tmMaxTimer = sphMicroTimer() + iTimeout*1000; // in microseconds
  1720. for ( ;; )
  1721. {
  1722. fd_set fdsRead, fdsWrite;
  1723. FD_ZERO ( &fdsRead );
  1724. FD_ZERO ( &fdsWrite );
  1725. int iMax = 0;
  1726. bool bDone = true;
  1727. ARRAY_FOREACH ( i, dAgents )
  1728. {
  1729. const Agent_t & tAgent = dAgents[i];
  1730. if ( tAgent.m_eState==AGENT_CONNECT || tAgent.m_eState==AGENT_HELLO )
  1731. {
  1732. assert ( !tAgent.m_sPath.IsEmpty() || tAgent.m_iPort>0 );
  1733. assert ( tAgent.m_iSock>0 );
  1734. sphFDSet ( tAgent.m_iSock, ( tAgent.m_eState==AGENT_CONNECT ) ? &fdsWrite : &fdsRead );
  1735. iMax = Max ( iMax, tAgent.m_iSock );
  1736. bDone = false;
  1737. }
  1738. }
  1739. if ( bDone )
  1740. break;
  1741. int64_t tmSelect = sphMicroTimer();
  1742. int64_t tmMicroLeft = tmMaxTimer - tmSelect;
  1743. if ( tmMicroLeft<=0 )
  1744. break; // FIXME? what about iTimeout==0 case?
  1745. struct timeval tvTimeout;
  1746. tvTimeout.tv_sec = (int)( tmMicroLeft/ 1000000 ); // full seconds
  1747. tvTimeout.tv_usec = (int)( tmMicroLeft % 1000000 ); // microseconds
  1748. // FIXME! check exceptfds for connect() failure as well, so that actively refused
  1749. // connections would not stall for a full timeout
  1750. int iSelected = select ( 1+iMax, &fdsRead, &fdsWrite, NULL, &tvTimeout );
  1751. if ( pWaited )
  1752. *pWaited += sphMicroTimer() - tmSelect;
  1753. if ( iSelected<=0 )
  1754. continue;
  1755. ARRAY_FOREACH ( i, dAgents )
  1756. {
  1757. Agent_t & tAgent = dAgents[i];
  1758. // check if connection completed
  1759. if ( tAgent.m_eState==AGENT_CONNECT && FD_ISSET ( tAgent.m_iSock, &fdsWrite ) )
  1760. {
  1761. int iErr = 0;
  1762. socklen_t iErrLen = sizeof(iErr);
  1763. getsockopt ( tAgent.m_iSock, SOL_SOCKET, SO_ERROR, (char*)&iErr, &iErrLen );
  1764. if ( iErr )
  1765. {
  1766. // connect() failure
  1767. tAgent.m_sFailure.SetSprintf ( "connect() failed: %s", sphSockError(iErr) );
  1768. tAgent.Close ();
  1769. } else
  1770. {
  1771. // connect() success
  1772. tAgent.m_eState = AGENT_HELLO;
  1773. }
  1774. continue;
  1775. }
  1776. // check if hello was received
  1777. if ( tAgent.m_eState==AGENT_HELLO && FD_ISSET ( tAgent.m_iSock, &fdsRead ) )
  1778. {
  1779. // read reply
  1780. int iRemoteVer;
  1781. int iRes = sphSockRecv ( tAgent.m_iSock, (char*)&iRemoteVer, sizeof(iRemoteVer) );
  1782. if ( iRes!=sizeof(iRemoteVer) )
  1783. {
  1784. tAgent.Close ();
  1785. if ( iRes<0 )
  1786. {
  1787. // network error
  1788. int iErr = sphSockGetErrno();
  1789. tAgent.m_sFailure.SetSprintf ( "handshake failure (errno=%d, msg=%s)", iErr, sphSockError(iErr) );
  1790. } else if ( iRes>0 )
  1791. {
  1792. // incomplete reply
  1793. tAgent.m_sFailure.SetSprintf ( "handshake failure (exp=%d, recv=%d)", sizeof(iRemoteVer), iRes );
  1794. } else
  1795. {
  1796. // agent closed the connection
  1797. // this might happen in out-of-sync connect-accept case; so let's retry
  1798. tAgent.m_sFailure.SetSprintf ( "handshake failure (connection was closed)", iRes );
  1799. tAgent.m_eState = AGENT_RETRY;
  1800. }
  1801. continue;
  1802. }
  1803. iRemoteVer = ntohl ( iRemoteVer );
  1804. if (!( iRemoteVer==SPHINX_SEARCHD_PROTO || iRemoteVer==0x01000000UL ) ) // workaround for all the revisions that sent it in host order...
  1805. {
  1806. tAgent.m_sFailure.SetSprintf ( "handshake failure (unexpected protocol version=%d)", iRemoteVer );
  1807. tAgent.Close ();
  1808. continue;
  1809. }
  1810. // send request
  1811. NetOutputBuffer_c tOut ( tAgent.m_iSock );
  1812. tBuilder.BuildRequest ( tAgent.m_sIndexes.cstr(), tOut );
  1813. tOut.Flush (); // FIXME! handle flush failure?
  1814. tAgent.m_eState = AGENT_QUERY;
  1815. iAgents++;
  1816. }
  1817. }
  1818. }
  1819. ARRAY_FOREACH ( i, dAgents )
  1820. {
  1821. // check if connection timed out
  1822. Agent_t & tAgent = dAgents[i];
  1823. if ( tAgent.m_eState!=AGENT_QUERY && tAgent.m_eState!=AGENT_UNUSED && tAgent.m_eState!=AGENT_RETRY )
  1824. {
  1825. tAgent.Close ();
  1826. tAgent.m_sFailure.SetSprintf ( "%s() timed out", tAgent.m_eState==AGENT_HELLO ? "read" : "connect" );
  1827. tAgent.m_eState = AGENT_RETRY; // do retry on connect() failures
  1828. }
  1829. }
  1830. return iAgents;
  1831. }
  1832. int WaitForRemoteAgents ( CSphVector<Agent_t> & dAgents, int iTimeout, IReplyParser_t & tParser, int64_t * pWaited )
  1833. {
  1834. assert ( iTimeout>=0 );
  1835. int iAgents = 0;
  1836. int64_t tmMaxTimer = sphMicroTimer() + iTimeout*1000; // in microseconds
  1837. for ( ;; )
  1838. {
  1839. fd_set fdsRead;
  1840. FD_ZERO ( &fdsRead );
  1841. int iMax = 0;
  1842. bool bDone = true;
  1843. ARRAY_FOREACH ( iAgent, dAgents )
  1844. {
  1845. Agent_t & tAgent = dAgents[iAgent];
  1846. if ( tAgent.m_bBlackhole )
  1847. continue;
  1848. if ( tAgent.m_eState==AGENT_QUERY || tAgent.m_eState==AGENT_REPLY )
  1849. {
  1850. assert ( !tAgent.m_sPath.IsEmpty() || tAgent.m_iPort>0 );
  1851. assert ( tAgent.m_iSock>0 );
  1852. sphFDSet ( tAgent.m_iSock, &fdsRead );
  1853. iMax = Max ( iMax, tAgent.m_iSock );
  1854. bDone = false;
  1855. }
  1856. }
  1857. if ( bDone )
  1858. break;
  1859. int64_t tmSelect = sphMicroTimer();
  1860. int64_t tmMicroLeft = tmMaxTimer - tmSelect;
  1861. if ( tmMicroLeft<=0 ) // FIXME? what about iTimeout==0 case?
  1862. break;
  1863. struct timeval tvTimeout;
  1864. tvTimeout.tv_sec = (int)( tmMicroLeft / 1000000 ); // full seconds
  1865. tvTimeout.tv_usec = (int)( tmMicroLeft % 1000000 ); // microseconds
  1866. int iSelected = select ( 1+iMax, &fdsRead, NULL, NULL, &tvTimeout );
  1867. if ( pWaited )
  1868. *pWaited += sphMicroTimer() - tmSelect;
  1869. if ( iSelected<=0 )
  1870. continue;
  1871. ARRAY_FOREACH ( iAgent, dAgents )
  1872. {
  1873. Agent_t & tAgent = dAgents[iAgent];
  1874. if ( tAgent.m_bBlackhole )
  1875. continue;
  1876. if (!( tAgent.m_eState==AGENT_QUERY || tAgent.m_eState==AGENT_REPLY ))
  1877. continue;
  1878. if ( !FD_ISSET ( tAgent.m_iSock, &fdsRead ) )
  1879. continue;
  1880. // if there was no reply yet, read reply header
  1881. bool bFailure = true;
  1882. for ( ;; )
  1883. {
  1884. if ( tAgent.m_eState==AGENT_QUERY )
  1885. {
  1886. // try to read
  1887. struct
  1888. {
  1889. WORD m_iStatus;
  1890. WORD m_iVer;
  1891. int m_iLength;
  1892. } tReplyHeader;
  1893. STATIC_SIZE_ASSERT ( tReplyHeader, 8 );
  1894. if ( sphSockRecv ( tAgent.m_iSock, (char*)&tReplyHeader, sizeof(tReplyHeader) )!=sizeof(tReplyHeader) )
  1895. {
  1896. // bail out if failed
  1897. tAgent.m_sFailure.SetSprintf ( "failed to receive reply header" );
  1898. break;
  1899. }
  1900. tReplyHeader.m_iStatus = ntohs ( tReplyHeader.m_iStatus );
  1901. tReplyHeader.m_iVer = ntohs ( tReplyHeader.m_iVer );
  1902. tReplyHeader.m_iLength = ntohl ( tReplyHeader.m_iLength );
  1903. // check the packet
  1904. if ( tReplyHeader.m_iLength<0 || tReplyHeader.m_iLength>g_iMaxPacketSize ) // FIXME! add reasonable max packet len too
  1905. {
  1906. tAgent.m_sFailure.SetSprintf ( "invalid packet size (status=%d, len=%d, max_packet_size=%d)", tReplyHeader.m_iStatus, tReplyHeader.m_iLength, g_iMaxPacketSize );
  1907. break;
  1908. }
  1909. // header received, switch the status
  1910. assert ( tAgent.m_pReplyBuf==NULL );
  1911. tAgent.m_eState = AGENT_REPLY;
  1912. tAgent.m_pReplyBuf = new BYTE [ tReplyHeader.m_iLength ];
  1913. tAgent.m_iReplySize = tReplyHeader.m_iLength;
  1914. tAgent.m_iReplyRead = 0;
  1915. tAgent.m_iReplyStatus = tReplyHeader.m_iStatus;
  1916. if ( !tAgent.m_pReplyBuf )
  1917. {
  1918. // bail out if failed
  1919. tAgent.m_sFailure.SetSprintf ( "failed to alloc %d bytes for reply buffer", tAgent.m_iReplySize );
  1920. break;
  1921. }
  1922. }
  1923. // if we are reading reply, read another chunk
  1924. if ( tAgent.m_eState==AGENT_REPLY )
  1925. {
  1926. // do read
  1927. assert ( tAgent.m_iReplyRead<tAgent.m_iReplySize );
  1928. int iRes = sphSockRecv ( tAgent.m_iSock, (char*)tAgent.m_pReplyBuf+tAgent.m_iReplyRead,
  1929. tAgent.m_iReplySize-tAgent.m_iReplyRead );
  1930. // bail out if read failed
  1931. if ( iRes<0 )
  1932. {
  1933. tAgent.m_sFailure.SetSprintf ( "failed to receive reply body: %s", sphSockError() );
  1934. break;
  1935. }
  1936. assert ( iRes>0 );
  1937. assert ( tAgent.m_iReplyRead+iRes<=tAgent.m_iReplySize );
  1938. tAgent.m_iReplyRead += iRes;
  1939. }
  1940. // if reply was fully received, parse it
  1941. if ( tAgent.m_eState==AGENT_REPLY && tAgent.m_iReplyRead==tAgent.m_iReplySize )
  1942. {
  1943. MemInputBuffer_c tReq ( tAgent.m_pReplyBuf, tAgent.m_iReplySize );
  1944. // absolve thy former sins
  1945. tAgent.m_sFailure = "";
  1946. // check for general errors/warnings first
  1947. if ( tAgent.m_iReplyStatus==SEARCHD_WARNING )
  1948. {
  1949. CSphString sAgentWarning = tReq.GetString ();
  1950. tAgent.m_sFailure.SetSprintf ( "remote warning: %s", sAgentWarning.cstr() );
  1951. } else if ( tAgent.m_iReplyStatus==SEARCHD_RETRY )
  1952. {
  1953. tAgent.m_eState = AGENT_RETRY;
  1954. break;
  1955. } else if ( tAgent.m_iReplyStatus!=SEARCHD_OK )
  1956. {
  1957. CSphString sAgentError = tReq.GetString ();
  1958. tAgent.m_sFailure.SetSprintf ( "remote error: %s", sAgentError.cstr() );
  1959. break;
  1960. }
  1961. // call parser
  1962. if ( !tParser.ParseReply ( tReq, tAgent ) )
  1963. break;
  1964. // check if there was enough data
  1965. if ( tReq.GetError() )
  1966. {
  1967. tAgent.m_sFailure.SetSprintf ( "incomplete reply" );
  1968. break;
  1969. }
  1970. // all is well
  1971. iAgents++;
  1972. tAgent.Close ();
  1973. tAgent.m_bSuccess = true;
  1974. }
  1975. bFailure = false;
  1976. break;
  1977. }
  1978. if ( bFailure )
  1979. {
  1980. tAgent.Close ();
  1981. tAgent.m_dResults.Reset ();
  1982. }
  1983. }
  1984. }
  1985. // close timed-out agents
  1986. ARRAY_FOREACH ( iAgent, dAgents )
  1987. {
  1988. Agent_t & tAgent = dAgents[iAgent];
  1989. if ( tAgent.m_bBlackhole )
  1990. tAgent.Close ();
  1991. else if ( tAgent.m_eState==AGENT_QUERY )
  1992. {
  1993. assert ( !tAgent.m_dResults.GetLength() );
  1994. assert ( !tAgent.m_bSuccess );
  1995. tAgent.Close ();
  1996. tAgent.m_sFailure.SetSprintf ( "query timed out" );
  1997. }
  1998. }
  1999. return iAgents;
  2000. }
  2001. /////////////////////////////////////////////////////////////////////////////
  2002. // SEARCH HANDLER
  2003. /////////////////////////////////////////////////////////////////////////////
  2004. inline bool operator < ( const CSphMatch & a, const CSphMatch & b )
  2005. {
  2006. if ( a.m_iDocID==b.m_iDocID )
  2007. return a.m_iTag > b.m_iTag;
  2008. else
  2009. return a.m_iDocID < b.m_iDocID;
  2010. };
  2011. /////////////////////////////////////////////////////////////////////////////
  2012. struct SearchRequestBuilder_t : public IRequestBuilder_t
  2013. {
  2014. SearchRequestBuilder_t ( const CSphVector<CSphQuery> & dQueries, int iStart, int iEnd ) : m_dQueries ( dQueries ), m_iStart ( iStart ), m_iEnd ( iEnd ) {}
  2015. virtual void BuildRequest ( const char * sIndexes, NetOutputBuffer_c & tOut ) const;
  2016. protected:
  2017. int CalcQueryLen ( const char * sIndexes, const CSphQuery & q ) const;
  2018. void SendQuery ( const char * sIndexes, NetOutputBuffer_c & tOut, const CSphQuery & q ) const;
  2019. protected:
  2020. const CSphVector<CSphQuery> & m_dQueries;
  2021. int m_iStart;
  2022. int m_iEnd;
  2023. };
  2024. struct SearchReplyParser_t : public IReplyParser_t
  2025. {
  2026. SearchReplyParser_t ( int iStart, int iEnd ) : m_iStart ( iStart ), m_iEnd ( iEnd ) {}
  2027. virtual bool ParseReply ( MemInputBuffer_c & tReq, Agent_t & tAgent ) const;
  2028. protected:
  2029. int m_iStart;
  2030. int m_iEnd;
  2031. };
  2032. /////////////////////////////////////////////////////////////////////////////
  2033. int SearchRequestBuilder_t::CalcQueryLen ( const char * sIndexes, const CSphQuery & q ) const
  2034. {
  2035. int iReqSize = 104 + 2*sizeof(SphDocID_t) + 4*q.m_iWeights
  2036. + strlen ( q.m_sSortBy.cstr() )
  2037. + strlen ( q.m_sQuery.cstr() )
  2038. + strlen ( sIndexes )
  2039. + strlen ( q.m_sGroupBy.cstr() )
  2040. + strlen ( q.m_sGroupSortBy.cstr() )
  2041. + strlen ( q.m_sGroupDistinct.cstr() )
  2042. + strlen ( q.m_sComment.cstr() )
  2043. + strlen ( q.m_sSelect.cstr() );
  2044. ARRAY_FOREACH ( j, q.m_dFilters )
  2045. {
  2046. const CSphFilterSettings & tFilter = q.m_dFilters[j];
  2047. iReqSize += 12 + strlen ( tFilter.m_sAttrName.cstr() ); // string attr-name; int type; int exclude-flag
  2048. switch ( tFilter.m_eType )
  2049. {
  2050. case SPH_FILTER_VALUES: iReqSize += 4 + 8*tFilter.GetNumValues (); break; // int values-count; uint64[] values
  2051. case SPH_FILTER_RANGE: iReqSize += 16; break; // uint64 min-val, max-val
  2052. case SPH_FILTER_FLOATRANGE: iReqSize += 8; break; // int/float min-val,max-val
  2053. }
  2054. }
  2055. if ( q.m_bGeoAnchor )
  2056. iReqSize += 16 + strlen ( q.m_sGeoLatAttr.cstr() ) + strlen ( q.m_sGeoLongAttr.cstr() ); // string lat-attr, long-attr; float lat, long
  2057. ARRAY_FOREACH ( i, q.m_dIndexWeights )
  2058. iReqSize += 8 + strlen ( q.m_dIndexWeights[i].m_sName.cstr() ); // string index-name; int index-weight
  2059. ARRAY_FOREACH ( i, q.m_dFieldWeights )
  2060. iReqSize += 8 + strlen ( q.m_dFieldWeights[i].m_sName.cstr() ); // string field-name; int field-weight
  2061. ARRAY_FOREACH ( i, q.m_dOverrides )
  2062. iReqSize += 12 + strlen ( q.m_dOverrides[i].m_sAttr.cstr() ) + // string attr-name; int type; int values-count
  2063. ( q.m_dOverrides[i].m_uAttrType==SPH_ATTR_BIGINT ? 16 : 12 )*q.m_dOverrides[i].m_dValues.GetLength(); // ( bigint id; int/float/bigint value )[] values
  2064. return iReqSize;
  2065. }
  2066. void SearchRequestBuilder_t::SendQuery ( const char * sIndexes, NetOutputBuffer_c & tOut, const CSphQuery & q ) const
  2067. {
  2068. tOut.SendInt ( 0 ); // offset is 0
  2069. tOut.SendInt ( q.m_iMaxMatches ); // limit is MAX_MATCHES
  2070. tOut.SendInt ( (DWORD)q.m_eMode ); // match mode
  2071. tOut.SendInt ( (DWORD)q.m_eRanker ); // ranking mode
  2072. tOut.SendInt ( q.m_eSort ); // sort mode
  2073. tOut.SendString ( q.m_sSortBy.cstr() ); // sort attr
  2074. tOut.SendString ( q.m_sQuery.cstr() ); // query
  2075. tOut.SendInt ( q.m_iWeights );
  2076. for ( int j=0; j<q.m_iWeights; j++ )
  2077. tOut.SendInt ( q.m_pWeights[j] ); // weights
  2078. tOut.SendString ( sIndexes ); // indexes
  2079. tOut.SendInt ( USE_64BIT ); // id range bits
  2080. tOut.SendDocid ( q.m_iMinID ); // id/ts ranges
  2081. tOut.SendDocid ( q.m_iMaxID );
  2082. tOut.SendInt ( q.m_dFilters.GetLength() );
  2083. ARRAY_FOREACH ( j, q.m_dFilters )
  2084. {
  2085. const CSphFilterSettings & tFilter = q.m_dFilters[j];
  2086. tOut.SendString ( tFilter.m_sAttrName.cstr() );
  2087. tOut.SendInt ( tFilter.m_eType );
  2088. switch ( tFilter.m_eType )
  2089. {
  2090. case SPH_FILTER_VALUES:
  2091. tOut.SendInt ( tFilter.GetNumValues () );
  2092. for ( int k = 0; k < tFilter.GetNumValues (); k++ )
  2093. tOut.SendUint64 ( tFilter.GetValue ( k ) );
  2094. break;
  2095. case SPH_FILTER_RANGE:
  2096. tOut.SendUint64 ( tFilter.m_uMinValue );
  2097. tOut.SendUint64 ( tFilter.m_uMaxValue );
  2098. break;
  2099. case SPH_FILTER_FLOATRANGE:
  2100. tOut.SendFloat ( tFilter.m_fMinValue );
  2101. tOut.SendFloat ( tFilter.m_fMaxValue );
  2102. break;
  2103. }
  2104. tOut.SendInt ( tFilter.m_bExclude );
  2105. }
  2106. tOut.SendInt ( q.m_eGroupFunc );
  2107. tOut.SendString ( q.m_sGroupBy.cstr() );
  2108. tOut.SendInt ( q.m_iMaxMatches );
  2109. tOut.SendString ( q.m_sGroupSortBy.cstr() );
  2110. tOut.SendInt ( q.m_iCutoff );
  2111. tOut.SendInt ( q.m_iRetryCount );
  2112. tOut.SendInt ( q.m_iRetryDelay );
  2113. tOut.SendString ( q.m_sGroupDistinct.cstr() );
  2114. tOut.SendInt ( q.m_bGeoAnchor );
  2115. if ( q.m_bGeoAnchor )
  2116. {
  2117. tOut.SendString ( q.m_sGeoLatAttr.cstr() );
  2118. tOut.SendString ( q.m_sGeoLongAttr.cstr() );
  2119. tOut.SendFloat ( q.m_fGeoLatitude );
  2120. tOut.SendFloat ( q.m_fGeoLongitude );
  2121. }
  2122. tOut.SendInt ( q.m_dIndexWeights.GetLength() );
  2123. ARRAY_FOREACH ( i, q.m_dIndexWeights )
  2124. {
  2125. tOut.SendString ( q.m_dIndexWeights[i].m_sName.cstr() );
  2126. tOut.SendInt ( q.m_dIndexWeights[i].m_iValue );
  2127. }
  2128. tOut.SendDword ( q.m_uMaxQueryMsec );
  2129. tOut.SendInt ( q.m_dFieldWeights.GetLength() );
  2130. ARRAY_FOREACH ( i, q.m_dFieldWeights )
  2131. {
  2132. tOut.SendString ( q.m_dFieldWeights[i].m_sName.cstr() );
  2133. tOut.SendInt ( q.m_dFieldWeights[i].m_iValue );
  2134. }
  2135. tOut.SendString ( q.m_sComment.cstr() );
  2136. tOut.SendInt ( q.m_dOverrides.GetLength() );
  2137. ARRAY_FOREACH ( i, q.m_dOverrides )
  2138. {
  2139. const CSphAttrOverride & tEntry = q.m_dOverrides[i];
  2140. tOut.SendString ( tEntry.m_sAttr.cstr() );
  2141. tOut.SendDword ( tEntry.m_uAttrType );
  2142. tOut.SendInt ( tEntry.m_dValues.GetLength() );
  2143. ARRAY_FOREACH ( j, tEntry.m_dValues )
  2144. {
  2145. tOut.SendUint64 ( tEntry.m_dValues[j].m_uDocID );
  2146. switch ( tEntry.m_uAttrType )
  2147. {
  2148. case SPH_ATTR_FLOAT: tOut.SendFloat ( tEntry.m_dValues[j].m_fValue ); break;
  2149. case SPH_ATTR_BIGINT: tOut.SendUint64 ( tEntry.m_dValues[j].m_uValue ); break;
  2150. default: tOut.SendDword ( (DWORD)tEntry.m_dValues[j].m_uValue ); break;
  2151. }
  2152. }
  2153. }
  2154. tOut.SendString ( q.m_sSelect.cstr() );
  2155. }
  2156. void SearchRequestBuilder_t::BuildRequest ( const char * sIndexes, NetOutputBuffer_c & tOut ) const
  2157. {
  2158. int iReqLen = 4; // int num-queries
  2159. for ( int i=m_iStart; i<=m_iEnd; i++ )
  2160. iReqLen += CalcQueryLen ( sIndexes, m_dQueries[i] );
  2161. tOut.SendDword ( SPHINX_SEARCHD_PROTO );
  2162. tOut.SendWord ( SEARCHD_COMMAND_SEARCH ); // command id
  2163. tOut.SendWord ( VER_COMMAND_SEARCH ); // command version
  2164. tOut.SendInt ( iReqLen ); // request body length
  2165. tOut.SendInt ( m_iEnd-m_iStart+1 );
  2166. for ( int i=m_iStart; i<=m_iEnd; i++ )
  2167. SendQuery ( sIndexes, tOut, m_dQueries[i] );
  2168. }
  2169. /////////////////////////////////////////////////////////////////////////////
  2170. bool SearchReplyParser_t::ParseReply ( MemInputBuffer_c & tReq, Agent_t & tAgent ) const
  2171. {
  2172. int iResults = m_iEnd-m_iStart+1;
  2173. assert ( iResults>0 );
  2174. tAgent.m_dResults.Resize ( iResults );
  2175. for ( int iRes=0; iRes<iResults; iRes++ )
  2176. tAgent.m_dResults[iRes].m_iSuccesses = 0;
  2177. for ( int iRes=0; iRes<iResults; iRes++ )
  2178. {
  2179. CSphQueryResult & tRes = tAgent.m_dResults [ iRes ];
  2180. tRes.m_sError = "";
  2181. tRes.m_sWarning = "";
  2182. // get status and message
  2183. DWORD eStatus = tReq.GetDword ();
  2184. if ( eStatus!=SEARCHD_OK )
  2185. {
  2186. CSphString sMessage = tReq.GetString ();
  2187. switch ( eStatus )
  2188. {
  2189. case SEARCHD_ERROR: tRes.m_sError = sMessage; continue;
  2190. case SEARCHD_RETRY: tRes.m_sError = sMessage; break;
  2191. case SEARCHD_WARNING: tRes.m_sWarning = sMessage; break;
  2192. default: tAgent.m_sFailure.SetSprintf ( "internal error: unknown status %d", eStatus ); break;
  2193. }
  2194. }
  2195. // get schema
  2196. CSphSchema & tSchema = tRes.m_tSchema;
  2197. tSchema.Reset ();
  2198. tSchema.m_dFields.Resize ( tReq.GetInt() ); // FIXME! add a sanity check
  2199. ARRAY_FOREACH ( j, tSchema.m_dFields )
  2200. tSchema.m_dFields[j].m_sName = tReq.GetString ();
  2201. int iNumAttrs = tReq.GetInt(); // FIXME! add a sanity check
  2202. for ( int j=0; j<iNumAttrs; j++ )
  2203. {
  2204. CSphColumnInfo tCol;
  2205. tCol.m_sName = tReq.GetString ();
  2206. tCol.m_eAttrType = tReq.GetDword (); // FIXME! add a sanity check
  2207. tSchema.AddAttr ( tCol );
  2208. }
  2209. // get matches
  2210. int iMatches = tReq.GetInt ();
  2211. if ( iMatches<0 || iMatches>g_iMaxMatches )
  2212. {
  2213. tAgent.m_sFailure.SetSprintf ( "invalid match count received (count=%d)", iMatches );
  2214. return false;
  2215. }
  2216. int bAgent64 = tReq.GetInt ();
  2217. #if !USE_64BIT
  2218. if ( bAgent64 )
  2219. tAgent.m_sFailure.SetSprintf ( "id64 agent, id32 master, docids might be wrapped" );
  2220. #endif
  2221. assert ( !tRes.m_dMatches.GetLength() );
  2222. if ( iMatches )
  2223. {
  2224. tRes.m_dMatches.Resize ( iMatches );
  2225. ARRAY_FOREACH ( i, tRes.m_dMatches )
  2226. {
  2227. CSphMatch & tMatch = tRes.m_dMatches[i];
  2228. tMatch.Reset ( tSchema.GetRowSize() );
  2229. tMatch.m_iDocID = bAgent64 ? (SphDocID_t)tReq.GetUint64() : tReq.GetDword();
  2230. tMatch.m_iWeight = tReq.GetInt ();
  2231. for ( int j=0; j<tSchema.GetAttrsCount(); j++ )
  2232. {
  2233. const CSphColumnInfo & tAttr = tSchema.GetAttr(j);
  2234. if ( tAttr.m_eAttrType & SPH_ATTR_MULTI )
  2235. {
  2236. tMatch.SetAttr ( tAttr.m_tLocator, g_dMvaStorage.GetLength() );
  2237. int iValues = tReq.GetDword ();
  2238. g_dMvaStorage.Add ( iValues );
  2239. while ( iValues-- )
  2240. g_dMvaStorage.Add ( tReq.GetDword() );
  2241. }
  2242. else if ( tAttr.m_eAttrType == SPH_ATTR_FLOAT )
  2243. {
  2244. float fRes = tReq.GetFloat();
  2245. tMatch.SetAttr ( tAttr.m_tLocator, sphF2DW(fRes) );
  2246. }
  2247. else if ( tAttr.m_eAttrType == SPH_ATTR_BIGINT )
  2248. {
  2249. tMatch.SetAttr ( tAttr.m_tLocator, tReq.GetUint64() );
  2250. }
  2251. else if ( tAttr.m_eAttrType == SPH_ATTR_STRING )
  2252. {
  2253. CSphString sValue = tReq.GetString();
  2254. int iLen = strlen ( sValue.cstr() );
  2255. int iOff = g_dStringsStorage.GetLength();
  2256. tMatch.SetAttr ( tAttr.m_tLocator, iOff );
  2257. g_dStringsStorage.Resize ( iOff+3+iLen );
  2258. BYTE * pBuf = &g_dStringsStorage[iOff];
  2259. pBuf += sphPackStrlen ( pBuf, iLen );
  2260. memcpy ( pBuf, sValue.cstr(), iLen );
  2261. }
  2262. else
  2263. {
  2264. tMatch.SetAttr ( tAttr.m_tLocator, tReq.GetDword() );
  2265. }
  2266. }
  2267. }
  2268. }
  2269. // read totals (retrieved count, total count, query time, word count)
  2270. int iRetrieved = tReq.GetInt ();
  2271. tRes.m_iTotalMatches = tReq.GetInt ();
  2272. tRes.m_iQueryTime = tReq.GetInt ();
  2273. tRes.m_dWordStats.Resize ( tReq.GetInt () ); // FIXME! sanity check?
  2274. if ( iRetrieved!=iMatches )
  2275. {
  2276. tAgent.m_sFailure.SetSprintf ( "expected %d retrieved documents, got %d", iMatches, iRetrieved );
  2277. return false;
  2278. }
  2279. // read per-word stats
  2280. ARRAY_FOREACH ( i, tRes.m_dWordStats )
  2281. {
  2282. CSphString sWord = tReq.GetString ();
  2283. int iDocs = tReq.GetInt ();
  2284. int iHits = tReq.GetInt ();
  2285. tRes.m_dWordStats[i].m_sWord = sWord;
  2286. tRes.m_dWordStats[i].m_iDocs = iDocs;
  2287. tRes.m_dWordStats[i].m_iHits = iHits;
  2288. }
  2289. // mark this result as ok
  2290. tRes.m_iSuccesses = 1;
  2291. }
  2292. // all seems OK (and buffer length checks are performed by caller)
  2293. return true;
  2294. }
  2295. /////////////////////////////////////////////////////////////////////////////
  2296. // returns true if incoming schema (src) is equal to existing (dst); false otherwise
  2297. bool MinimizeSchema ( CSphSchema & tDst, const CSphSchema & tSrc )
  2298. {
  2299. // if dst is empty, result is also empty
  2300. if ( tDst.GetAttrsCount()==0 )
  2301. return tSrc.GetAttrsCount()==0;
  2302. // check for equality, and remove all dst attributes that are not present in src
  2303. CSphVector<CSphColumnInfo> dDst;
  2304. for ( int i=0; i<tDst.GetAttrsCount(); i++ )
  2305. dDst.Add ( tDst.GetAttr(i) );
  2306. bool bEqual = ( tDst.GetAttrsCount()==tSrc.GetAttrsCount() );
  2307. ARRAY_FOREACH ( i, dDst )
  2308. {
  2309. int iSrcIdx = tSrc.GetAttrIndex ( dDst[i].m_sName.cstr() );
  2310. // check for index mismatch
  2311. if ( iSrcIdx!=i )
  2312. bEqual = false;
  2313. // check for type/size mismatch (and fixup if needed)
  2314. if ( iSrcIdx>=0 )
  2315. {
  2316. const CSphColumnInfo & tSrcAttr = tSrc.GetAttr(iSrcIdx);
  2317. if ( tSrcAttr.m_eAttrType!=dDst[i].m_eAttrType )
  2318. {
  2319. // different types? remove the attr
  2320. iSrcIdx = -1;
  2321. bEqual = false;
  2322. } else if ( tSrcAttr.m_tLocator.m_iBitCount!=dDst[i].m_tLocator.m_iBitCount )
  2323. {
  2324. // different bit sizes? choose the max one
  2325. dDst[i].m_tLocator.m_iBitCount = Max ( dDst[i].m_tLocator.m_iBitCount, tSrcAttr.m_tLocator.m_iBitCount );
  2326. bEqual = false;
  2327. }
  2328. }
  2329. // check for presence
  2330. if ( iSrcIdx<0 )
  2331. {
  2332. dDst.Remove ( i );
  2333. i--;
  2334. }
  2335. }
  2336. tDst.ResetAttrs ();
  2337. ARRAY_FOREACH ( i, dDst )
  2338. tDst.AddAttr ( dDst[i] );
  2339. return bEqual;
  2340. }
  2341. bool FixupQuery ( CSphQuery * pQuery, const CSphSchema * pSchema, const char * sIndexName, CSphString & sError )
  2342. {
  2343. // already?
  2344. if ( !pQuery->m_iOldVersion )
  2345. return true;
  2346. if ( pQuery->m_iOldGroups>0 || pQuery->m_iOldMinGID!=0 || pQuery->m_iOldMaxGID!=UINT_MAX )
  2347. {
  2348. int iAttr = -1;
  2349. for ( int i=0; i<pSchema->GetAttrsCount(); i++ )
  2350. if ( pSchema->GetAttr(i).m_eAttrType==SPH_ATTR_INTEGER )
  2351. {
  2352. iAttr = i;
  2353. break;
  2354. }
  2355. if ( iAttr<0 )
  2356. {
  2357. sError.SetSprintf ( "index '%s': no group attribute found", sIndexName );
  2358. return false;
  2359. }
  2360. CSphFilterSettings tFilter;
  2361. tFilter.m_sAttrName = pSchema->GetAttr(iAttr).m_sName;
  2362. tFilter.m_dValues.Resize ( pQuery->m_iOldGroups );
  2363. ARRAY_FOREACH ( i, tFilter.m_dValues )
  2364. tFilter.m_dValues[i] = pQuery->m_pOldGroups[i];
  2365. tFilter.m_uMinValue = pQuery->m_iOldMinGID;
  2366. tFilter.m_uMaxValue = pQuery->m_iOldMaxGID;
  2367. pQuery->m_dFilters.Add ( tFilter );
  2368. }
  2369. if ( pQuery->m_iOldMinTS!=0 || pQuery->m_iOldMaxTS!=UINT_MAX )
  2370. {
  2371. int iAttr = -1;
  2372. for ( int i=0; i<pSchema->GetAttrsCount(); i++ )
  2373. if ( pSchema->GetAttr(i).m_eAttrType==SPH_ATTR_TIMESTAMP )
  2374. {
  2375. iAttr = i;
  2376. break;
  2377. }
  2378. if ( iAttr<0 )
  2379. {
  2380. sError.SetSprintf ( "index '%s': no timestamp attribute found", sIndexName );
  2381. return false;
  2382. }
  2383. CSphFilterSettings tFilter;
  2384. tFilter.m_sAttrName = pSchema->GetAttr(iAttr).m_sName;
  2385. tFilter.m_uMinValue = pQuery->m_iOldMinTS;
  2386. tFilter.m_uMaxValue = pQuery->m_iOldMaxTS;
  2387. pQuery->m_dFilters.Add ( tFilter );
  2388. }
  2389. pQuery->m_iOldVersion = 0;
  2390. return true;
  2391. }
  2392. void ParseIndexList ( const CSphString & sIndexes, CSphVector<CSphString> & dOut )
  2393. {
  2394. CSphString sSplit = sIndexes;
  2395. char * p = (char*)sSplit.cstr();
  2396. while ( *p )
  2397. {
  2398. // skip non-alphas
  2399. while ( (*p) && !sphIsAlpha(*p) ) p++;
  2400. if ( !(*p) ) break;
  2401. // this is my next index name
  2402. const char * sNext = p;
  2403. while ( sphIsAlpha(*p) ) p++;
  2404. assert ( sNext!=p );
  2405. if ( *p ) *p++ = '\0'; // if it was not the end yet, we'll continue from next char
  2406. dOut.Add ( sNext );
  2407. }
  2408. }
  2409. void CheckQuery ( const CSphQuery & tQuery, CSphString & sError )
  2410. {
  2411. sError = NULL;
  2412. if ( tQuery.m_iMinID>tQuery.m_iMaxID )
  2413. {
  2414. sError.SetSprintf ( "invalid ID range (min greater than max)" );
  2415. return;
  2416. }
  2417. if ( tQuery.m_eMode<0 || tQuery.m_eMode>SPH_MATCH_TOTAL )
  2418. {
  2419. sError.SetSprintf ( "invalid match mode %d", tQuery.m_eMode );
  2420. return;
  2421. }
  2422. if ( tQuery.m_eRanker<0 || tQuery.m_eRanker>SPH_RANK_TOTAL )
  2423. {
  2424. sError.SetSprintf ( "invalid ranking mode %d", tQuery.m_eRanker );
  2425. return;
  2426. }
  2427. if ( tQuery.m_iMaxMatches<1 || tQuery.m_iMaxMatches>g_iMaxMatches )
  2428. {
  2429. sError.SetSprintf ( "per-query max_matches=%d out of bounds (per-server max_matches=%d)",
  2430. tQuery.m_iMaxMatches, g_iMaxMatches );
  2431. return;
  2432. }
  2433. if ( tQuery.m_iOffset<0 || tQuery.m_iOffset>=tQuery.m_iMaxMatches )
  2434. {
  2435. sError.SetSprintf ( "offset out of bounds (offset=%d, max_matches=%d)",
  2436. tQuery.m_iOffset, tQuery.m_iMaxMatches );
  2437. return;
  2438. }
  2439. if ( tQuery.m_iLimit<0 )
  2440. {
  2441. sError.SetSprintf ( "limit out of bounds (limit=%d)", tQuery.m_iLimit );
  2442. return;
  2443. }
  2444. if ( tQuery.m_iCutoff<0 )
  2445. {
  2446. sError.SetSprintf ( "cutoff out of bounds (cutoff=%d)", tQuery.m_iCutoff );
  2447. return;
  2448. }
  2449. if ( tQuery.m_iRetryCount<0 || tQuery.m_iRetryCount>MAX_RETRY_COUNT )
  2450. {
  2451. sError.SetSprintf ( "retry count out of bounds (count=%d)", tQuery.m_iRetryCount );
  2452. return;
  2453. }
  2454. if ( tQuery.m_iRetryDelay<0 || tQuery.m_iRetryDelay>MAX_RETRY_DELAY )
  2455. {
  2456. sError.SetSprintf ( "retry delay out of bounds (delay=%d)", tQuery.m_iRetryDelay );
  2457. return;
  2458. }
  2459. }
  2460. bool ParseSearchQuery ( InputBuffer_c & tReq, CSphQuery & tQuery, int iVer )
  2461. {
  2462. tQuery.m_iOldVersion = iVer;
  2463. // v.1.0. mode, limits, weights, ID/TS ranges
  2464. tQuery.m_iOffset = tReq.GetInt ();
  2465. tQuery.m_iLimit = tReq.GetInt ();
  2466. tQuery.m_eMode = (ESphMatchMode) tReq.GetInt ();
  2467. if ( iVer>=0x110 )
  2468. tQuery.m_eRanker= (ESphRankMode) tReq.GetInt ();
  2469. tQuery.m_eSort = (ESphSortOrder) tReq.GetInt ();
  2470. if ( iVer<=0x101 )
  2471. tQuery.m_iOldGroups = tReq.GetDwords ( &tQuery.m_pOldGroups, g_iMaxFilterValues, "invalid group count %d (should be in 0..%d range)" );
  2472. if ( iVer>=0x102 )
  2473. {
  2474. tQuery.m_sSortBy = tReq.GetString ();
  2475. tQuery.m_sSortBy.ToLower ();
  2476. }
  2477. tQuery.m_sQuery = tReq.GetString ();
  2478. tQuery.m_iWeights = tReq.GetDwords ( (DWORD**)&tQuery.m_pWeights, SPH_MAX_FIELDS, "invalid weight count %d (should be in 0..%d range)" );
  2479. tQuery.m_sIndexes = tReq.GetString ();
  2480. bool bIdrange64 = false;
  2481. if ( iVer>=0x108 )
  2482. bIdrange64 = ( tReq.GetInt()!=0 );
  2483. if ( bIdrange64 )
  2484. {
  2485. tQuery.m_iMinID = (SphDocID_t)tReq.GetUint64 ();
  2486. tQuery.m_iMaxID = (SphDocID_t)tReq.GetUint64 ();
  2487. // FIXME? could report clamp here if I'm id32 and client passed id64 range,
  2488. // but frequently this won't affect anything at all
  2489. } else
  2490. {
  2491. tQuery.m_iMinID = tReq.GetDword ();
  2492. tQuery.m_iMaxID = tReq.GetDword ();
  2493. }
  2494. if ( iVer<0x108 && tQuery.m_iMaxID==0xffffffffUL )
  2495. tQuery.m_iMaxID = 0; // fixup older clients which send 32-bit UINT_MAX by default
  2496. if ( tQuery.m_iMaxID==0 )
  2497. tQuery.m_iMaxID = DOCID_MAX;
  2498. // v.1.0, v.1.1
  2499. if ( iVer<=0x101 )
  2500. {
  2501. tQuery.m_iOldMinTS = tReq.GetDword ();
  2502. tQuery.m_iOldMaxTS = tReq.GetDword ();
  2503. }
  2504. // v.1.1 specific
  2505. if ( iVer==0x101 )
  2506. {
  2507. tQuery.m_iOldMinGID = tReq.GetDword ();
  2508. tQuery.m_iOldMaxGID = tReq.GetDword ();
  2509. }
  2510. // v.1.2
  2511. if ( iVer>=0x102 )
  2512. {
  2513. int iAttrFilters = tReq.GetInt ();
  2514. if ( iAttrFilters>g_iMaxFilters )
  2515. {
  2516. tReq.SendErrorReply ( "too much attribute filters (req=%d, max=%d)", iAttrFilters, g_iMaxFilters );
  2517. return false;
  2518. }
  2519. tQuery.m_dFilters.Resize ( iAttrFilters );
  2520. ARRAY_FOREACH ( iFilter, tQuery.m_dFilters )
  2521. {
  2522. CSphFilterSettings & tFilter = tQuery.m_dFilters[iFilter];
  2523. tFilter.m_sAttrName = tReq.GetString ();
  2524. tFilter.m_sAttrName.ToLower ();
  2525. if ( iVer>=0x10E )
  2526. {
  2527. // v.1.14+
  2528. tFilter.m_eType = (ESphFilter) tReq.GetDword ();
  2529. switch ( tFilter.m_eType )
  2530. {
  2531. case SPH_FILTER_RANGE:
  2532. tFilter.m_uMinValue = ( iVer>=0x114 ) ? tReq.GetUint64() : tReq.GetDword ();
  2533. tFilter.m_uMaxValue = ( iVer>=0x114 ) ? tReq.GetUint64() : tReq.GetDword ();
  2534. break;
  2535. case SPH_FILTER_FLOATRANGE:
  2536. tFilter.m_fMinValue = tReq.GetFloat ();
  2537. tFilter.m_fMaxValue = tReq.GetFloat ();
  2538. break;
  2539. case SPH_FILTER_VALUES:
  2540. {
  2541. bool bRes = ( iVer>=0x114 )
  2542. ? tReq.GetQwords ( tFilter.m_dValues, g_iMaxFilterValues, "invalid attribute set length %d (should be in 0..%d range)" )
  2543. : tReq.GetDwords ( tFilter.m_dValues, g_iMaxFilterValues, "invalid attribute set length %d (should be in 0..%d range)" );
  2544. if ( !bRes )
  2545. return false;
  2546. }
  2547. break;
  2548. default:
  2549. tReq.SendErrorReply ( "unknown filter type (type-id=%d)", tFilter.m_eType );
  2550. return false;
  2551. }
  2552. } else
  2553. {
  2554. // pre-1.14
  2555. if ( !tReq.GetDwords ( tFilter.m_dValues, g_iMaxFilterValues, "invalid attribute set length %d (should be in 0..%d range)" ) )
  2556. return false;
  2557. if ( !tFilter.m_dValues.GetLength() )
  2558. {
  2559. // 0 length means this is range, not set
  2560. tFilter.m_uMinValue = tReq.GetDword ();
  2561. tFilter.m_uMaxValue = tReq.GetDword ();
  2562. }
  2563. tFilter.m_eType = tFilter.m_dValues.GetLength() ? SPH_FILTER_VALUES : SPH_FILTER_RANGE;
  2564. }
  2565. if ( iVer>=0x106 )
  2566. tFilter.m_bExclude = !!tReq.GetDword ();
  2567. }
  2568. }
  2569. // v.1.3
  2570. if ( iVer>=0x103 )
  2571. {
  2572. tQuery.m_eGroupFunc = (ESphGroupBy) tReq.GetDword ();
  2573. tQuery.m_sGroupBy = tReq.GetString ();
  2574. tQuery.m_sGroupBy.ToLower ();
  2575. }
  2576. // v.1.4
  2577. tQuery.m_iMaxMatches = g_iMaxMatches;
  2578. if ( iVer>=0x104 )
  2579. tQuery.m_iMaxMatches = tReq.GetInt ();
  2580. // v.1.5, v.1.7
  2581. if ( iVer>=0x107 )
  2582. {
  2583. tQuery.m_sGroupSortBy = tReq.GetString ();
  2584. } else if ( iVer>=0x105 )
  2585. {
  2586. bool bSortByGroup = ( tReq.GetInt()!=0 );
  2587. if ( !bSortByGroup )
  2588. {
  2589. char sBuf[256];
  2590. switch ( tQuery.m_eSort )
  2591. {
  2592. case SPH_SORT_RELEVANCE:
  2593. tQuery.m_sGroupSortBy = "@weight desc";
  2594. break;
  2595. case SPH_SORT_ATTR_DESC:
  2596. case SPH_SORT_ATTR_ASC:
  2597. snprintf ( sBuf, sizeof(sBuf), "%s %s", tQuery.m_sSortBy.cstr(),
  2598. tQuery.m_eSort==SPH_SORT_ATTR_ASC ? "asc" : "desc" );
  2599. tQuery.m_sGroupSortBy = sBuf;
  2600. break;
  2601. case SPH_SORT_EXTENDED:
  2602. tQuery.m_sGroupSortBy = tQuery.m_sSortBy;
  2603. break;
  2604. default:
  2605. tReq.SendErrorReply ( "INTERNAL ERROR: unsupported sort mode %d in groupby sort fixup", tQuery.m_eSort );
  2606. return false;
  2607. }
  2608. }
  2609. }
  2610. // v.1.9
  2611. if ( iVer>=0x109 )
  2612. tQuery.m_iCutoff = tReq.GetInt();
  2613. // v.1.10
  2614. if ( iVer>=0x10A )
  2615. {
  2616. tQuery.m_iRetryCount = tReq.GetInt ();
  2617. tQuery.m_iRetryDelay = tReq.GetInt ();
  2618. }
  2619. // v.1.11
  2620. if ( iVer>=0x10B )
  2621. tQuery.m_sGroupDistinct = tReq.GetString ();
  2622. // v.1.14
  2623. if ( iVer>=0x10E )
  2624. {
  2625. tQuery.m_bGeoAnchor = ( tReq.GetInt()!=0 );
  2626. if ( tQuery.m_bGeoAnchor )
  2627. {
  2628. tQuery.m_sGeoLatAttr = tReq.GetString ();
  2629. tQuery.m_sGeoLongAttr = tReq.GetString ();
  2630. tQuery.m_fGeoLatitude = tReq.GetFloat ();
  2631. tQuery.m_fGeoLongitude = tReq.GetFloat ();
  2632. }
  2633. }
  2634. // v.1.15
  2635. if ( iVer>=0x10F )
  2636. {
  2637. tQuery.m_dIndexWeights.Resize ( tReq.GetInt() ); // FIXME! add sanity check
  2638. ARRAY_FOREACH ( i, tQuery.m_dIndexWeights )
  2639. {
  2640. tQuery.m_dIndexWeights[i].m_sName = tReq.GetString ();
  2641. tQuery.m_dIndexWeights[i].m_iValue = tReq.GetInt ();
  2642. }
  2643. }
  2644. // v.1.17
  2645. if ( iVer>=0x111 )
  2646. tQuery.m_uMaxQueryMsec = tReq.GetDword ();
  2647. // v.1.18
  2648. if ( iVer>=0x112 )
  2649. {
  2650. tQuery.m_dFieldWeights.Resize ( tReq.GetInt() ); // FIXME! add sanity check
  2651. ARRAY_FOREACH ( i, tQuery.m_dFieldWeights )
  2652. {
  2653. tQuery.m_dFieldWeights[i].m_sName = tReq.GetString ();
  2654. tQuery.m_dFieldWeights[i].m_iValue = tReq.GetInt ();
  2655. }
  2656. }
  2657. // v.1.19
  2658. if ( iVer>=0x113 )
  2659. tQuery.m_sComment = tReq.GetString ();
  2660. // v.1.21
  2661. if ( iVer>=0x115 )
  2662. {
  2663. tQuery.m_dOverrides.Resize ( tReq.GetInt() ); // FIXME! add sanity check
  2664. ARRAY_FOREACH ( i, tQuery.m_dOverrides )
  2665. {
  2666. CSphAttrOverride & tOverride = tQuery.m_dOverrides[i];
  2667. tOverride.m_sAttr = tReq.GetString ();
  2668. tOverride.m_uAttrType = tReq.GetDword ();
  2669. tOverride.m_dValues.Resize ( tReq.GetInt() ); // FIXME! add sanity check
  2670. ARRAY_FOREACH ( iVal, tOverride.m_dValues )
  2671. {
  2672. CSphAttrOverride::IdValuePair_t & tEntry = tOverride.m_dValues[iVal];
  2673. tEntry.m_uDocID = (SphDocID_t) tReq.GetUint64 ();
  2674. if ( tOverride.m_uAttrType==SPH_ATTR_FLOAT ) tEntry.m_fValue = tReq.GetFloat ();
  2675. else if ( tOverride.m_uAttrType==SPH_ATTR_BIGINT ) tEntry.m_uValue = tReq.GetUint64 ();
  2676. else tEntry.m_uValue = tReq.GetDword ();
  2677. }
  2678. }
  2679. }
  2680. // v.1.22
  2681. if ( iVer>=0x116 )
  2682. {
  2683. tQuery.m_sSelect = tReq.GetString ();
  2684. CSphString sError;
  2685. if ( !tQuery.ParseSelectList ( sError ) )
  2686. {
  2687. tReq.SendErrorReply ( "select: %s", sError.cstr() );
  2688. return false;
  2689. }
  2690. }
  2691. /////////////////////
  2692. // additional checks
  2693. /////////////////////
  2694. if ( tReq.GetError() )
  2695. {
  2696. tReq.SendErrorReply ( "invalid or truncated request" );
  2697. return false;
  2698. }
  2699. CSphString sError;
  2700. CheckQuery ( tQuery, sError );
  2701. if ( !sError.IsEmpty() )
  2702. {
  2703. tReq.SendErrorReply ( "%s", sError.cstr() );
  2704. return false;
  2705. }
  2706. // all ok
  2707. return true;
  2708. }
  2709. void LogQuery ( const CSphQuery & tQuery, const CSphQueryResult & tRes )
  2710. {
  2711. if ( g_iQueryLogFile<0 || !tRes.m_sError.IsEmpty() )
  2712. return;
  2713. char sBuf[2048];
  2714. char * p = sBuf;
  2715. char * pMax = sBuf+sizeof(sBuf)-4;
  2716. // [time]
  2717. *p++ = '[';
  2718. p += sphFormatCurrentTime ( p, pMax-p );
  2719. *p++ = ']';
  2720. // querytime sec
  2721. int iQueryTime = Max ( tRes.m_iQueryTime, 0 );
  2722. p += snprintf ( p, pMax-p, " %d.%03d sec", iQueryTime/1000, iQueryTime%1000 );
  2723. // optional multi-query multiplier
  2724. if ( tRes.m_iMultiplier>1 )
  2725. p += snprintf ( p, pMax-p, " x%d", tRes.m_iMultiplier );
  2726. // [matchmode/numfilters/sortmode matches (offset,limit)
  2727. static const char * sModes [ SPH_MATCH_TOTAL ] = { "all", "any", "phr", "bool", "ext", "scan", "ext2" };
  2728. static const char * sSort [ SPH_SORT_TOTAL ] = { "rel", "attr-", "attr+", "tsegs", "ext", "expr" };
  2729. p += snprintf ( p, pMax-p, " [%s/%d/%s %d (%d,%d)",
  2730. sModes [ tQuery.m_eMode ], tQuery.m_dFilters.GetLength(), sSort [ tQuery.m_eSort ],
  2731. tRes.m_iTotalMatches, tQuery.m_iOffset, tQuery.m_iLimit );
  2732. // optional groupby info
  2733. if ( !tQuery.m_sGroupBy.IsEmpty() )
  2734. p += snprintf ( p, pMax-p, " @%s", tQuery.m_sGroupBy.cstr() );
  2735. // ] [indexes]
  2736. p += snprintf ( p, pMax-p, "] [%s]", tQuery.m_sIndexes.cstr() );
  2737. // optional performance counters
  2738. if ( g_bIOStats || g_bCpuStats )
  2739. {
  2740. const CSphIOStats & IOStats = sphStopIOStats ();
  2741. *p++ = ' ';
  2742. char * pBracket = p; // can't fill yet, will be overwritten by sprintfs
  2743. if ( g_bIOStats )
  2744. p += snprintf ( p, pMax-p, " ios=%d kb=%d.%d ioms=%d.%d",
  2745. IOStats.m_iReadOps, int(IOStats.m_iReadBytes/1024), int(IOStats.m_iReadBytes%1024)*10/1024,
  2746. int(IOStats.m_iReadTime/1000), int(IOStats.m_iReadTime%1000)/100 );
  2747. if ( g_bCpuStats )
  2748. p += snprintf ( p, pMax-p, " cpums=%d.%d", int(tRes.m_iCpuTime/1000), int(tRes.m_iCpuTime%1000)/100 );
  2749. *pBracket = '[';
  2750. if ( p<pMax )
  2751. *p++ = ']';
  2752. }
  2753. // optional query comment
  2754. if ( !tQuery.m_sComment.IsEmpty() )
  2755. p += snprintf ( p, pMax-p, " [%s]", tQuery.m_sComment.cstr() );
  2756. // query
  2757. if ( !tQuery.m_sQuery.IsEmpty() )
  2758. {
  2759. *p++ = ' ';
  2760. for ( const char * q = tQuery.m_sQuery.cstr(); p<pMax && *q; p++, q++ )
  2761. *p = ( *q=='\n' ) ? ' ' : *q;
  2762. }
  2763. // line feed
  2764. if ( p<pMax-1 )
  2765. {
  2766. *p++ = '\n';
  2767. *p++ = '\0';
  2768. }
  2769. sBuf[sizeof(sBuf)-2] = '\n';
  2770. sBuf[sizeof(sBuf)-1] = '\0';
  2771. lseek ( g_iQueryLogFile, 0, SEEK_END );
  2772. write ( g_iQueryLogFile, sBuf, strlen(sBuf) );
  2773. }
  2774. int CalcResultLength ( int iVer, const CSphQueryResult * pRes, const CSphVector<PoolPtrs_t> & dTag2Pools )
  2775. {
  2776. int iRespLen = 0;
  2777. // query status
  2778. if ( iVer>=0x10D )
  2779. {
  2780. // multi-query status
  2781. iRespLen += 4; // status code
  2782. if ( !pRes->m_sError.IsEmpty() )
  2783. return iRespLen + 4 +strlen ( pRes->m_sError.cstr() );
  2784. if ( !pRes->m_sWarning.IsEmpty() )
  2785. iRespLen += 4+strlen ( pRes->m_sWarning.cstr() );
  2786. } else if ( iVer>=0x106 )
  2787. {
  2788. // warning message
  2789. if ( !pRes->m_sWarning.IsEmpty() )
  2790. iRespLen += 4 + strlen ( pRes->m_sWarning.cstr() );
  2791. }
  2792. // query stats
  2793. iRespLen += 20;
  2794. // schema
  2795. if ( iVer>=0x102 )
  2796. {
  2797. iRespLen += 8; // 4 for field count, 4 for attr count
  2798. ARRAY_FOREACH ( i, pRes->m_tSchema.m_dFields )
  2799. iRespLen += 4 + strlen ( pRes->m_tSchema.m_dFields[i].m_sName.cstr() ); // namelen, name
  2800. for ( int i=0; i<pRes->m_tSchema.GetAttrsCount(); i++ )
  2801. iRespLen += 8 + strlen ( pRes->m_tSchema.GetAttr(i).m_sName.cstr() ); // namelen, name, type
  2802. }
  2803. // matches
  2804. if ( iVer<0x102 )
  2805. iRespLen += 16*pRes->m_iCount; // matches
  2806. else if ( iVer<0x108 )
  2807. iRespLen += ( 8+4*pRes->m_tSchema.GetAttrsCount() )*pRes->m_iCount; // matches
  2808. else
  2809. iRespLen += 4 + ( 8+4*USE_64BIT+4*pRes->m_tSchema.GetAttrsCount() )*pRes->m_iCount; // id64 tag and matches
  2810. if ( iVer>=0x114 )
  2811. {
  2812. // 64bit matches
  2813. int iWideAttrs = 0;
  2814. for ( int i=0; i<pRes->m_tSchema.GetAttrsCount(); i++ )
  2815. if ( pRes->m_tSchema.GetAttr(i).m_eAttrType==SPH_ATTR_BIGINT )
  2816. iWideAttrs++;
  2817. iRespLen += 4*pRes->m_iCount*iWideAttrs; // extra 4 bytes per attr per match
  2818. }
  2819. ARRAY_FOREACH ( i, pRes->m_dWordStats ) // per-word stats
  2820. iRespLen += 12 + strlen ( pRes->m_dWordStats[i].m_sWord.cstr() ); // wordlen, word, docs, hits
  2821. // MVA and string values
  2822. CSphVector<CSphAttrLocator> dMvaItems;
  2823. CSphVector<CSphAttrLocator> dStringItems;
  2824. for ( int i=0; i<pRes->m_tSchema.GetAttrsCount(); i++ )
  2825. {
  2826. const CSphColumnInfo & tCol = pRes->m_tSchema.GetAttr(i);
  2827. if ( tCol.m_eAttrType & SPH_ATTR_MULTI )
  2828. dMvaItems.Add ( tCol.m_tLocator );
  2829. if ( tCol.m_eAttrType==SPH_ATTR_STRING )
  2830. dStringItems.Add ( tCol.m_tLocator );
  2831. }
  2832. if ( iVer>=0x10C && dMvaItems.GetLength() )
  2833. {
  2834. for ( int i=0; i<pRes->m_iCount; i++ )
  2835. {
  2836. const CSphMatch & tMatch = pRes->m_dMatches [ pRes->m_iOffset+i ];
  2837. const DWORD * pMvaPool = dTag2Pools [ tMatch.m_iTag ].m_pMva;
  2838. ARRAY_FOREACH ( j, dMvaItems )
  2839. {
  2840. const DWORD * pMva = tMatch.GetAttrMVA ( dMvaItems[j], pMvaPool );
  2841. if ( pMva )
  2842. iRespLen += pMva[0]*4; // FIXME? maybe add some sanity check here
  2843. }
  2844. }
  2845. }
  2846. if ( iVer>=0x117 && dStringItems.GetLength() )
  2847. {
  2848. for ( int i=0; i<pRes->m_iCount; i++ )
  2849. {
  2850. const CSphMatch & tMatch = pRes->m_dMatches [ pRes->m_iOffset+i ];
  2851. const BYTE * pStrings = dTag2Pools [ tMatch.m_iTag ].m_pStrings;
  2852. ARRAY_FOREACH ( j, dStringItems )
  2853. {
  2854. DWORD uOffset = (DWORD) tMatch.GetAttr ( dStringItems[j] );
  2855. if ( uOffset ) // magic zero
  2856. iRespLen += sphUnpackStr ( pStrings+uOffset, NULL );
  2857. }
  2858. }
  2859. }
  2860. return iRespLen;
  2861. }
  2862. void SendResult ( int iVer, NetOutputBuffer_c & tOut, const CSphQueryResult * pRes, const CSphVector<PoolPtrs_t> & dTag2Pools )
  2863. {
  2864. // status
  2865. if ( iVer>=0x10D )
  2866. {
  2867. // multi-query status
  2868. bool bError = !pRes->m_sError.IsEmpty();
  2869. bool bWarning = !bError && !pRes->m_sWarning.IsEmpty();
  2870. if ( bError )
  2871. {
  2872. tOut.SendInt ( SEARCHD_ERROR );
  2873. tOut.SendString ( pRes->m_sError.cstr() );
  2874. return;
  2875. } else if ( bWarning )
  2876. {
  2877. tOut.SendInt ( SEARCHD_WARNING );
  2878. tOut.SendString ( pRes->m_sWarning.cstr() );
  2879. } else
  2880. {
  2881. tOut.SendInt ( SEARCHD_OK );
  2882. }
  2883. } else
  2884. {
  2885. // single-query warning
  2886. if ( iVer>=0x106 && !pRes->m_sWarning.IsEmpty() )
  2887. tOut.SendString ( pRes->m_sWarning.cstr() );
  2888. }
  2889. // send schema
  2890. if ( iVer>=0x102 )
  2891. {
  2892. tOut.SendInt ( pRes->m_tSchema.m_dFields.GetLength() );
  2893. ARRAY_FOREACH ( i, pRes->m_tSchema.m_dFields )
  2894. tOut.SendString ( pRes->m_tSchema.m_dFields[i].m_sName.cstr() );
  2895. tOut.SendInt ( pRes->m_tSchema.GetAttrsCount() );
  2896. for ( int i=0; i<pRes->m_tSchema.GetAttrsCount(); i++ )
  2897. {
  2898. const CSphColumnInfo & tCol = pRes->m_tSchema.GetAttr(i);
  2899. tOut.SendString ( tCol.m_sName.cstr() );
  2900. tOut.SendDword ( (DWORD)tCol.m_eAttrType );
  2901. }
  2902. }
  2903. // send matches
  2904. CSphAttrLocator iGIDLoc, iTSLoc;
  2905. if ( iVer<=0x101 )
  2906. {
  2907. for ( int i=0; i<pRes->m_tSchema.GetAttrsCount(); i++ )
  2908. {
  2909. const CSphColumnInfo & tAttr = pRes->m_tSchema.GetAttr(i);
  2910. if ( iTSLoc.m_iBitOffset<0 && tAttr.m_eAttrType==SPH_ATTR_TIMESTAMP )
  2911. iTSLoc = tAttr.m_tLocator;
  2912. if ( iGIDLoc.m_iBitOffset<0 && tAttr.m_eAttrType==SPH_ATTR_INTEGER )
  2913. iGIDLoc = tAttr.m_tLocator;
  2914. }
  2915. }
  2916. tOut.SendInt ( pRes->m_iCount );
  2917. if ( iVer>=0x108 )
  2918. tOut.SendInt ( USE_64BIT );
  2919. for ( int i=0; i<pRes->m_iCount; i++ )
  2920. {
  2921. const CSphMatch & tMatch = pRes->m_dMatches [ pRes->m_iOffset+i ];
  2922. #if USE_64BIT
  2923. if ( iVer>=0x108 )
  2924. tOut.SendUint64 ( tMatch.m_iDocID );
  2925. else
  2926. #endif
  2927. tOut.SendDword ( (DWORD)tMatch.m_iDocID );
  2928. if ( iVer<=0x101 )
  2929. {
  2930. tOut.SendDword ( iGIDLoc.m_iBitOffset>=0 ? (DWORD) tMatch.GetAttr ( iGIDLoc ) : 1 );
  2931. tOut.SendDword ( iTSLoc.m_iBitOffset>=0 ? (DWORD) tMatch.GetAttr ( iTSLoc ) : 1 );
  2932. tOut.SendInt ( tMatch.m_iWeight );
  2933. } else
  2934. {
  2935. tOut.SendInt ( tMatch.m_iWeight );
  2936. const DWORD * pMvaPool = dTag2Pools [ tMatch.m_iTag ].m_pMva;
  2937. const BYTE * pStrings = dTag2Pools [ tMatch.m_iTag ].m_pStrings;
  2938. assert ( tMatch.m_iRowitems==pRes->m_tSchema.GetRowSize() );
  2939. for ( int j=0; j<pRes->m_tSchema.GetAttrsCount(); j++ )
  2940. {
  2941. const CSphColumnInfo & tAttr = pRes->m_tSchema.GetAttr(j);
  2942. if ( tAttr.m_eAttrType & SPH_ATTR_MULTI )
  2943. {
  2944. const DWORD * pValues = tMatch.GetAttrMVA ( tAttr.m_tLocator, pMvaPool );
  2945. if ( iVer<0x10C || !pValues )
  2946. {
  2947. // for older clients, fixups column value to 0
  2948. // for newer clients, means that there are 0 values
  2949. tOut.SendDword ( 0 );
  2950. } else
  2951. {
  2952. // send MVA values
  2953. int iValues = *pValues++;
  2954. tOut.SendDword ( iValues );
  2955. while ( iValues-- )
  2956. tOut.SendDword ( *pValues++ );
  2957. }
  2958. } else if ( tAttr.m_eAttrType==SPH_ATTR_STRING )
  2959. {
  2960. // send string attr
  2961. if ( iVer<0x117 )
  2962. {
  2963. // for older clients, just send int value of 0
  2964. tOut.SendDword ( 0 );
  2965. } else
  2966. {
  2967. // for newer clients, send binary string
  2968. DWORD uOffset = (DWORD) tMatch.GetAttr ( tAttr.m_tLocator );
  2969. if ( !uOffset ) // magic zero
  2970. {
  2971. tOut.SendDword ( 0 ); // null string
  2972. } else
  2973. {
  2974. const BYTE * pStr;
  2975. int iLen = sphUnpackStr ( pStrings+uOffset, &pStr );
  2976. tOut.SendDword ( iLen );
  2977. tOut.SendBytes ( pStr, iLen );
  2978. }
  2979. }
  2980. } else
  2981. {
  2982. // send plain attr
  2983. if ( tAttr.m_eAttrType==SPH_ATTR_FLOAT )
  2984. tOut.SendFloat ( tMatch.GetAttrFloat ( tAttr.m_tLocator ) );
  2985. else if ( iVer>=0x114 && tAttr.m_eAttrType==SPH_ATTR_BIGINT )
  2986. tOut.SendUint64 ( tMatch.GetAttr ( tAttr.m_tLocator ) );
  2987. else
  2988. tOut.SendDword ( (DWORD)tMatch.GetAttr ( tAttr.m_tLocator ) );
  2989. }
  2990. }
  2991. }
  2992. }
  2993. tOut.SendInt ( pRes->m_dMatches.GetLength() );
  2994. tOut.SendInt ( pRes->m_iTotalMatches );
  2995. tOut.SendInt ( Max ( pRes->m_iQueryTime, 0 ) );
  2996. tOut.SendInt ( pRes->m_dWordStats.GetLength() );
  2997. ARRAY_FOREACH ( i, pRes->m_dWordStats )
  2998. {
  2999. tOut.SendString ( pRes->m_dWordStats[i].m_sWord.cstr() );
  3000. tOut.SendInt ( pRes->m_dWordStats[i].m_iDocs );
  3001. tOut.SendInt ( pRes->m_dWordStats[i].m_iHits );
  3002. }
  3003. }
  3004. /////////////////////////////////////////////////////////////////////////////
  3005. struct AggrResult_t : CSphQueryResult
  3006. {
  3007. int m_iTag; ///< current tag
  3008. CSphVector<CSphSchema> m_dSchemas; ///< aggregated resultsets schemas (for schema minimization)
  3009. CSphVector<int> m_dMatchCounts; ///< aggregated resultsets lengths (for schema minimization)
  3010. CSphVector<int> m_dIndexWeights;///< aggregated resultsets per-index weights (optional)
  3011. CSphVector<PoolPtrs_t> m_dTag2Pools; ///< tag to MVA and strings storage pools mapping
  3012. };
  3013. bool MinimizeAggrResult ( AggrResult_t & tRes, const CSphQuery & tQuery )
  3014. {
  3015. // sanity check
  3016. int iExpected = 0;
  3017. ARRAY_FOREACH ( i, tRes.m_dMatchCounts )
  3018. iExpected += tRes.m_dMatchCounts[i];
  3019. if ( iExpected!=tRes.m_dMatches.GetLength() )
  3020. {
  3021. tRes.m_sError.SetSprintf ( "INTERNAL ERROR: expected %d matches in combined result set, got %d",
  3022. iExpected, tRes.m_dMatches.GetLength() );
  3023. return false;
  3024. }
  3025. if ( !tRes.m_dMatches.GetLength() )
  3026. return true;
  3027. // build minimal schema
  3028. bool bAllEqual = true;
  3029. tRes.m_tSchema = tRes.m_dSchemas[0];
  3030. for ( int i=1; i<tRes.m_dSchemas.GetLength(); i++ )
  3031. {
  3032. if ( !MinimizeSchema ( tRes.m_tSchema, tRes.m_dSchemas[i] ) )
  3033. bAllEqual = false;
  3034. }
  3035. // apply select-items on top of that
  3036. bool bStar = false;
  3037. ARRAY_FOREACH ( i, tQuery.m_dItems )
  3038. if ( tQuery.m_dItems[i].m_sExpr=="*" )
  3039. {
  3040. bStar = true;
  3041. break;
  3042. }
  3043. if ( !bStar && tQuery.m_dItems.GetLength() )
  3044. {
  3045. CSphSchema tItems;
  3046. for ( int i=0; i<tRes.m_tSchema.GetAttrsCount(); i++ )
  3047. {
  3048. const CSphColumnInfo & tCol = tRes.m_tSchema.GetAttr(i);
  3049. if ( !tCol.m_pExpr )
  3050. {
  3051. bool bAdd = false;
  3052. ARRAY_FOREACH ( i, tQuery.m_dItems )
  3053. if ( tQuery.m_dItems[i].m_sExpr==tCol.m_sName )
  3054. {
  3055. bAdd = true;
  3056. break;
  3057. }
  3058. if ( !bAdd )
  3059. continue;
  3060. }
  3061. tItems.AddAttr ( tCol );
  3062. }
  3063. if ( tRes.m_tSchema.GetAttrsCount()!=tItems.GetAttrsCount() )
  3064. {
  3065. tRes.m_tSchema = tItems;
  3066. bAllEqual = false;
  3067. }
  3068. }
  3069. // convert all matches to minimal schema
  3070. if ( !bAllEqual )
  3071. {
  3072. int iCur = 0;
  3073. int * dMapFrom = NULL;
  3074. CSphDocInfo tRow;
  3075. tRow.Reset ( tRes.m_tSchema.GetRowSize() );
  3076. if ( tRow.m_iRowitems )
  3077. dMapFrom = new int [ tRes.m_tSchema.GetAttrsCount() ];
  3078. ARRAY_FOREACH ( iSchema, tRes.m_dSchemas )
  3079. {
  3080. for ( int i=0; i<tRes.m_tSchema.GetAttrsCount(); i++ )
  3081. {
  3082. dMapFrom[i] = tRes.m_dSchemas[iSchema].GetAttrIndex ( tRes.m_tSchema.GetAttr(i).m_sName.cstr() );
  3083. assert ( dMapFrom[i]>=0 );
  3084. }
  3085. for ( int i=iCur; i<iCur+tRes.m_dMatchCounts[iSchema]; i++ )
  3086. {
  3087. CSphMatch & tMatch = tRes.m_dMatches[i];
  3088. if ( tRow.m_iRowitems )
  3089. {
  3090. // remap attrs
  3091. for ( int j=0; j<tRes.m_tSchema.GetAttrsCount(); j++ )
  3092. {
  3093. const CSphColumnInfo & tDst = tRes.m_tSchema.GetAttr(j);
  3094. const CSphColumnInfo & tSrc = tRes.m_dSchemas[iSchema].GetAttr ( dMapFrom[j] );
  3095. tRow.SetAttr ( tDst.m_tLocator, tMatch.GetAttr(tSrc.m_tLocator) );
  3096. }
  3097. // remapped row might need *more* space because of unpacked attributes; allocate if so
  3098. if ( tMatch.m_iRowitems<tRow.m_iRowitems )
  3099. {
  3100. SafeDeleteArray ( tMatch.m_pRowitems );
  3101. tMatch.m_iRowitems = tRow.m_iRowitems;
  3102. tMatch.m_pRowitems = new CSphRowitem [ tRow.m_iRowitems ];
  3103. }
  3104. // copy remapped row
  3105. for ( int j=0; j<tRow.m_iRowitems; j++ )
  3106. tMatch.m_pRowitems[j] = tRow.m_pRowitems[j];
  3107. }
  3108. tMatch.m_iRowitems = tRow.m_iRowitems;
  3109. }
  3110. iCur += tRes.m_dMatchCounts[iSchema];
  3111. }
  3112. assert ( iCur==tRes.m_dMatches.GetLength() );
  3113. SafeDeleteArray ( dMapFrom );
  3114. }
  3115. // we do not need to re-sort if there's exactly one result set
  3116. if ( tRes.m_iSuccesses==1 )
  3117. return true;
  3118. // create queue
  3119. // at this point, we do not need to compute anything; it all must be here
  3120. ISphMatchSorter * pSorter = sphCreateQueue ( &tQuery, tRes.m_tSchema, tRes.m_sError, false );
  3121. if ( !pSorter )
  3122. return false;
  3123. // kill all dupes
  3124. int iDupes = 0;
  3125. if ( pSorter->IsGroupby () )
  3126. {
  3127. // groupby sorter does that automagically
  3128. pSorter->SetMVAPool ( NULL ); // because we must be able to group on @groupby anyway
  3129. ARRAY_FOREACH ( i, tRes.m_dMatches )
  3130. if ( !pSorter->Push ( tRes.m_dMatches[i] ) )
  3131. iDupes++;
  3132. } else
  3133. {
  3134. // normal sorter needs massasging
  3135. // sort by docid and then by tag to guarantee the replacement order
  3136. tRes.m_dMatches.Sort ();
  3137. // fold them matches
  3138. if ( tQuery.m_dIndexWeights.GetLength() )
  3139. {
  3140. // if there were per-index weights, compute weighted ranks sum
  3141. int iCur = 0;
  3142. int iMax = tRes.m_dMatches.GetLength();
  3143. while ( iCur<iMax )
  3144. {
  3145. CSphMatch & tMatch = tRes.m_dMatches[iCur++];
  3146. if ( tMatch.m_iTag>=0 )
  3147. tMatch.m_iWeight *= tRes.m_dIndexWeights[tMatch.m_iTag];
  3148. while ( iCur<iMax && tRes.m_dMatches[iCur].m_iDocID==tMatch.m_iDocID )
  3149. {
  3150. const CSphMatch & tDupe = tRes.m_dMatches[iCur];
  3151. int iAddWeight = tDupe.m_iWeight;
  3152. if ( tDupe.m_iTag>=0 )
  3153. iAddWeight *= tRes.m_dIndexWeights[tDupe.m_iTag];
  3154. tMatch.m_iWeight += iAddWeight;
  3155. iDupes++;
  3156. iCur++;
  3157. }
  3158. pSorter->Push ( tMatch );
  3159. }
  3160. } else
  3161. {
  3162. // by default, simply remove dupes (select first by tag)
  3163. ARRAY_FOREACH ( i, tRes.m_dMatches )
  3164. {
  3165. if ( i==0 || tRes.m_dMatches[i].m_iDocID!=tRes.m_dMatches[i-1].m_iDocID )
  3166. pSorter->Push ( tRes.m_dMatches[i] );
  3167. else
  3168. iDupes++;
  3169. }
  3170. }
  3171. }
  3172. tRes.m_dMatches.Reset ();
  3173. sphFlattenQueue ( pSorter, &tRes, -1 );
  3174. SafeDelete ( pSorter );
  3175. tRes.m_iTotalMatches -= iDupes;
  3176. return true;
  3177. }
  3178. void SetupKillListFilter ( CSphFilterSettings & tFilter, const SphAttr_t * pKillList, int nEntries )
  3179. {
  3180. assert ( nEntries && pKillList );
  3181. tFilter.m_bExclude = true;
  3182. tFilter.m_eType = SPH_FILTER_VALUES;
  3183. tFilter.m_uMinValue = pKillList [0];
  3184. tFilter.m_uMaxValue = pKillList [nEntries-1];
  3185. tFilter.m_sAttrName = "@id";
  3186. tFilter.SetExternalValues ( pKillList, nEntries );
  3187. }
  3188. /////////////////////////////////////////////////////////////////////////////
  3189. class SearchHandler_c
  3190. {
  3191. public:
  3192. SearchHandler_c ( int iQueries );
  3193. void RunQueries (); ///< run all queries, get all results
  3194. public:
  3195. CSphVector<CSphQuery> m_dQueries; ///< queries which i need to search
  3196. CSphVector<AggrResult_t> m_dResults; ///< results which i obtained
  3197. SearchFailuresLogset_c m_dFailuresSet; ///< failure logs for each query
  3198. protected:
  3199. void RunSubset ( int iStart, int iEnd ); ///< run queries against index(es) from first query in the subset
  3200. };
  3201. SearchHandler_c::SearchHandler_c ( int iQueries )
  3202. {
  3203. m_dQueries.Resize ( iQueries );
  3204. m_dResults.Resize ( iQueries );
  3205. m_dFailuresSet.SetSize ( iQueries );
  3206. ARRAY_FOREACH ( i, m_dResults )
  3207. {
  3208. assert ( m_dResults[i].m_dIndexWeights.GetLength()==0 );
  3209. m_dResults[i].m_iTag = 1; // first avail tag for local storage ptrs
  3210. m_dResults[i].m_dIndexWeights.Add ( 1 ); // reserved index 0 with weight 1 for remote matches
  3211. m_dResults[i].m_dTag2Pools.Add (); // reserved index 0 for remote mva storage ptr; we'll fix this up later
  3212. }
  3213. }
  3214. void SearchHandler_c::RunQueries ()
  3215. {
  3216. ///////////////////////////////
  3217. // choose path and run queries
  3218. ///////////////////////////////
  3219. g_dMvaStorage.Reserve ( 1024 );
  3220. g_dMvaStorage.Resize ( 0 );
  3221. g_dMvaStorage.Add ( 0 ); // dummy value
  3222. g_dStringsStorage.Reserve ( 1024 );
  3223. g_dStringsStorage.Resize ( 0 );
  3224. g_dStringsStorage.Add ( 0 );
  3225. // check if all queries are to the same index
  3226. bool bSameIndex = false;
  3227. if ( m_dQueries.GetLength()>1 )
  3228. {
  3229. bSameIndex = true;
  3230. ARRAY_FOREACH ( i, m_dQueries )
  3231. if ( m_dQueries[i].m_sIndexes!=m_dQueries[0].m_sIndexes )
  3232. {
  3233. bSameIndex = false;
  3234. break;
  3235. }
  3236. }
  3237. if ( bSameIndex )
  3238. {
  3239. ///////////////////////////////
  3240. // batch queries to same index
  3241. ///////////////////////////////
  3242. RunSubset ( 0, m_dQueries.GetLength()-1 );
  3243. ARRAY_FOREACH ( i, m_dQueries )
  3244. LogQuery ( m_dQueries[i], m_dResults[i] );
  3245. } else
  3246. {
  3247. /////////////////////////////////////////////
  3248. // fallback; just work each query separately
  3249. /////////////////////////////////////////////
  3250. ARRAY_FOREACH ( i, m_dQueries )
  3251. {
  3252. RunSubset ( i, i );
  3253. LogQuery ( m_dQueries[i], m_dResults[i] );
  3254. }
  3255. }
  3256. // final fixup
  3257. ARRAY_FOREACH ( i, m_dResults )
  3258. {
  3259. m_dResults[i].m_dTag2Pools[0].m_pMva = g_dMvaStorage.GetLength() ? &g_dMvaStorage[0] : NULL;
  3260. m_dResults[i].m_dTag2Pools[0].m_pStrings = g_dStringsStorage.GetLength() ? &g_dStringsStorage[0] : NULL;
  3261. }
  3262. }
  3263. /// return cpu time, in microseconds
  3264. int64_t sphCpuTimer ()
  3265. {
  3266. #ifdef HAVE_CLOCK_GETTIME
  3267. if ( !g_bCpuStats )
  3268. return 0;
  3269. struct timespec tp;
  3270. if ( clock_gettime ( CLOCK_PROCESS_CPUTIME_ID, &tp ) )
  3271. return 0;
  3272. return tp.tv_sec*1000000 + tp.tv_nsec/1000;
  3273. #else
  3274. return 0;
  3275. #endif
  3276. }
  3277. void SearchHandler_c::RunSubset ( int iStart, int iEnd )
  3278. {
  3279. // all my stats
  3280. int64_t tmSubset = sphMicroTimer();
  3281. int64_t tmLocal = 0;
  3282. int64_t tmWait = 0;
  3283. int64_t tmCpu = sphCpuTimer ();
  3284. if ( g_bIOStats )
  3285. sphStartIOStats ();
  3286. // prepare for descent
  3287. CSphQuery & tFirst = m_dQueries[iStart];
  3288. m_dFailuresSet.SetSubset ( iStart, iEnd );
  3289. for ( int iRes=iStart; iRes<=iEnd; iRes++ )
  3290. m_dResults[iRes].m_iSuccesses = 0;
  3291. ////////////////////////////////////////////////////////////////
  3292. // check for single-query, multi-queue optimization possibility
  3293. ////////////////////////////////////////////////////////////////
  3294. bool bMultiQueue = ( iStart<iEnd );
  3295. for ( int iCheck=iStart+1; iCheck<=iEnd; iCheck++ )
  3296. {
  3297. const CSphQuery & qFirst = m_dQueries[iStart];
  3298. const CSphQuery & qCheck = m_dQueries[iCheck];
  3299. // these parameters must be the same
  3300. if (
  3301. ( qCheck.m_sQuery!=qFirst.m_sQuery ) || // query string
  3302. ( qCheck.m_iWeights!=qFirst.m_iWeights ) || // weights count
  3303. ( qCheck.m_pWeights && memcmp ( qCheck.m_pWeights, qFirst.m_pWeights, sizeof(int)*qCheck.m_iWeights ) ) || // weights
  3304. ( qCheck.m_eMode!=qFirst.m_eMode ) || // search mode
  3305. ( qCheck.m_eRanker!=qFirst.m_eRanker ) || // ranking mode
  3306. ( qCheck.m_iMinID!=qFirst.m_iMinID ) || // min-id filter
  3307. ( qCheck.m_iMaxID!=qFirst.m_iMaxID ) || // max-id filter
  3308. ( qCheck.m_dFilters.GetLength()!=qFirst.m_dFilters.GetLength() ) || // attr filters count
  3309. ( qCheck.m_iCutoff!=qFirst.m_iCutoff ) || // cutoff
  3310. ( qCheck.m_eSort==SPH_SORT_EXPR && qFirst.m_eSort==SPH_SORT_EXPR && qCheck.m_sSortBy!=qFirst.m_sSortBy ) || // sort expressions
  3311. ( qCheck.m_bGeoAnchor!=qFirst.m_bGeoAnchor ) || // geodist expression
  3312. ( qCheck.m_bGeoAnchor && qFirst.m_bGeoAnchor && ( qCheck.m_fGeoLatitude!=qFirst.m_fGeoLatitude || qCheck.m_fGeoLongitude!=qFirst.m_fGeoLongitude ) ) ) // some geodist cases
  3313. {
  3314. bMultiQueue = false;
  3315. break;
  3316. }
  3317. // filters must be the same too
  3318. assert ( qCheck.m_dFilters.GetLength()==qFirst.m_dFilters.GetLength() );
  3319. ARRAY_FOREACH ( i, qCheck.m_dFilters )
  3320. if ( qCheck.m_dFilters[i]!=qFirst.m_dFilters[i] )
  3321. {
  3322. bMultiQueue = false;
  3323. break;
  3324. }
  3325. if ( !bMultiQueue )
  3326. break;
  3327. }
  3328. ////////////////////////////
  3329. // build local indexes list
  3330. ////////////////////////////
  3331. CSphVector<CSphString> dLocal;
  3332. DistributedIndex_t * pDist = g_hDistIndexes ( tFirst.m_sIndexes );
  3333. if ( !pDist )
  3334. {
  3335. // they're all local, build the list
  3336. if ( tFirst.m_sIndexes=="*" )
  3337. {
  3338. // search through all local indexes
  3339. g_hIndexes.IterateStart ();
  3340. while ( g_hIndexes.IterateNext () )
  3341. if ( g_hIndexes.IterateGet ().m_bEnabled )
  3342. dLocal.Add ( g_hIndexes.IterateGetKey() );
  3343. } else
  3344. {
  3345. // search through specified local indexes
  3346. ParseIndexList ( tFirst.m_sIndexes, dLocal );
  3347. ARRAY_FOREACH ( i, dLocal )
  3348. {
  3349. // check that it exists
  3350. if ( !g_hIndexes(dLocal[i]) )
  3351. {
  3352. for ( int iRes=iStart; iRes<=iEnd; iRes++ )
  3353. m_dResults[iRes].m_sError.SetSprintf ( "unknown local index '%s' in search request", dLocal[i].cstr() );
  3354. return;
  3355. }
  3356. // if it exists but is not enabled, remove it from the list and force recheck
  3357. if ( !g_hIndexes[dLocal[i]].m_bEnabled )
  3358. dLocal.RemoveFast ( i-- );
  3359. }
  3360. }
  3361. // sanity check
  3362. if ( !dLocal.GetLength() )
  3363. {
  3364. for ( int iRes=iStart; iRes<=iEnd; iRes++ )
  3365. m_dResults[iRes].m_sError.SetSprintf ( "no enabled local indexes to search" );
  3366. return;
  3367. }
  3368. } else
  3369. {
  3370. // copy local indexes list from distributed definition, but filter out disabled ones
  3371. ARRAY_FOREACH ( i, pDist->m_dLocal )
  3372. if ( g_hIndexes[pDist->m_dLocal[i]].m_bEnabled )
  3373. dLocal.Add ( pDist->m_dLocal[i] );
  3374. }
  3375. /////////////////////////////////////////////////////
  3376. // optimize single-query, same-schema local searches
  3377. /////////////////////////////////////////////////////
  3378. ISphMatchSorter * pLocalSorter = NULL;
  3379. while ( iStart==iEnd && dLocal.GetLength()>1 )
  3380. {
  3381. CSphString sError;
  3382. // check if all schemas are equal
  3383. bool bAllEqual = true;
  3384. const CSphSchema * pFirstSchema = g_hIndexes [ dLocal[0] ].m_pSchema;
  3385. for ( int i=1; i<dLocal.GetLength() && bAllEqual; i++ )
  3386. {
  3387. if ( !pFirstSchema->CompareTo ( *g_hIndexes [ dLocal[i] ].m_pSchema, sError ) )
  3388. bAllEqual = false;
  3389. }
  3390. // we can reuse the very same sorter
  3391. if ( bAllEqual )
  3392. if ( FixupQuery ( &m_dQueries[iStart], pFirstSchema, "local-sorter", sError ) )
  3393. pLocalSorter = sphCreateQueue ( &m_dQueries[iStart], *pFirstSchema, sError );
  3394. break;
  3395. }
  3396. ///////////////////////////////////////////////////////////
  3397. // main query loop (with multiple retries for distributed)
  3398. ///////////////////////////////////////////////////////////
  3399. tFirst.m_iRetryCount = Min ( Max ( tFirst.m_iRetryCount, 0 ), MAX_RETRY_COUNT ); // paranoid clamp
  3400. if ( !pDist )
  3401. tFirst.m_iRetryCount = 0;
  3402. for ( int iRetry=0; iRetry<=tFirst.m_iRetryCount; iRetry++ )
  3403. {
  3404. ////////////////////////
  3405. // issue remote queries
  3406. ////////////////////////
  3407. // delay between retries
  3408. if ( iRetry>0 )
  3409. sphSleepMsec ( tFirst.m_iRetryDelay );
  3410. // connect to remote agents and query them, if required
  3411. int iRemote = 0;
  3412. if ( pDist )
  3413. {
  3414. m_dFailuresSet.SetIndex ( tFirst.m_sIndexes.cstr() );
  3415. ConnectToRemoteAgents ( pDist->m_dAgents, iRetry!=0 );
  3416. SearchRequestBuilder_t tReqBuilder ( m_dQueries, iStart, iEnd );
  3417. iRemote = QueryRemoteAgents ( pDist->m_dAgents, pDist->m_iAgentConnectTimeout, tReqBuilder, &tmWait );
  3418. }
  3419. /////////////////////
  3420. // run local queries
  3421. //////////////////////
  3422. // while the remote queries are running, do local searches
  3423. // FIXME! what if the remote agents finish early, could they timeout?
  3424. if ( iRetry==0 )
  3425. {
  3426. if ( pDist && !iRemote && !dLocal.GetLength() )
  3427. {
  3428. for ( int iRes=iStart; iRes<=iEnd; iRes++ )
  3429. m_dResults[iRes].m_sError = "all remote agents unreachable and no available local indexes found";
  3430. return;
  3431. }
  3432. tmLocal = -sphMicroTimer();
  3433. ARRAY_FOREACH ( iLocal, dLocal )
  3434. {
  3435. const ServedIndex_t & tServed = g_hIndexes [ dLocal[iLocal] ];
  3436. assert ( tServed.m_pIndex );
  3437. assert ( tServed.m_bEnabled );
  3438. if ( bMultiQueue )
  3439. {
  3440. ////////////////////////////////
  3441. // run single multi-queue query
  3442. ////////////////////////////////
  3443. CSphVector<int> dSorterIndexes;
  3444. dSorterIndexes.Resize ( iEnd+1 );
  3445. ARRAY_FOREACH ( j, dSorterIndexes )
  3446. dSorterIndexes[j] = -1;
  3447. CSphVector<ISphMatchSorter*> dSorters;
  3448. for ( int iQuery=iStart; iQuery<=iEnd; iQuery++ )
  3449. {
  3450. CSphString sError;
  3451. CSphQuery & tQuery = m_dQueries[iQuery];
  3452. ISphMatchSorter * pSorter = sphCreateQueue ( &tQuery, *tServed.m_pSchema, sError );
  3453. if ( !pSorter )
  3454. {
  3455. m_dFailuresSet[iQuery].SubmitEx ( dLocal[iLocal].cstr(), "%s", sError.cstr() );
  3456. continue;
  3457. }
  3458. dSorterIndexes[iQuery] = dSorters.GetLength();
  3459. dSorters.Add ( pSorter );
  3460. }
  3461. if ( dSorters.GetLength() )
  3462. {
  3463. AggrResult_t tStats;
  3464. // set killlist
  3465. CSphQuery * pQuery = &m_dQueries[iStart];
  3466. int iNumFilters = pQuery->m_dFilters.GetLength ();
  3467. for ( int i = iLocal + 1; i < dLocal.GetLength (); i++ )
  3468. {
  3469. const ServedIndex_t & tServed = g_hIndexes [ dLocal[i] ];
  3470. if ( tServed.m_pIndex->GetKillListSize () )
  3471. {
  3472. CSphFilterSettings tKillListFilter;
  3473. SetupKillListFilter ( tKillListFilter, tServed.m_pIndex->GetKillList (), tServed.m_pIndex->GetKillListSize () );
  3474. pQuery->m_dFilters.Add ( tKillListFilter );
  3475. }
  3476. }
  3477. if ( !tServed.m_pIndex->MultiQuery ( &m_dQueries[iStart], &tStats,
  3478. dSorters.GetLength(), &dSorters[0] ) )
  3479. {
  3480. // failed
  3481. for ( int iQuery=iStart; iQuery<=iEnd; iQuery++ )
  3482. m_dFailuresSet[iQuery].SubmitEx ( dLocal[iLocal].cstr(), "%s", tServed.m_pIndex->GetLastError().cstr() );
  3483. } else
  3484. {
  3485. // multi-query succeeded
  3486. for ( int iQuery=iStart; iQuery<=iEnd; iQuery++ )
  3487. {
  3488. // but some of the sorters could had failed at "create sorter" stage
  3489. if ( dSorterIndexes[iQuery]<0 )
  3490. continue;
  3491. // this one seems OK
  3492. ISphMatchSorter * pSorter = dSorters [ dSorterIndexes[iQuery] ];
  3493. AggrResult_t & tRes = m_dResults[iQuery];
  3494. tRes.m_iSuccesses++;
  3495. tRes.m_iTotalMatches += pSorter->GetTotalCount();
  3496. tRes.m_iQueryTime += ( iQuery==iStart ) ? tStats.m_iQueryTime : 0;
  3497. tRes.m_pMva = tStats.m_pMva;
  3498. tRes.m_dWordStats = tStats.m_dWordStats;
  3499. tRes.m_tSchema = pSorter->GetOutgoingSchema();
  3500. // extract matches from sorter
  3501. assert ( pSorter );
  3502. if ( pSorter->GetLength() )
  3503. {
  3504. tRes.m_dMatchCounts.Add ( pSorter->GetLength() );
  3505. tRes.m_dSchemas.Add ( tRes.m_tSchema );
  3506. tRes.m_dIndexWeights.Add ( m_dQueries[iQuery].GetIndexWeight ( dLocal[iLocal].cstr() ) );
  3507. PoolPtrs_t & tPoolPtrs = tRes.m_dTag2Pools.Add ();
  3508. tPoolPtrs.m_pMva = tRes.m_pMva;
  3509. tPoolPtrs.m_pStrings = tRes.m_pStrings;
  3510. sphFlattenQueue ( pSorter, &tRes, tRes.m_iTag++ );
  3511. }
  3512. }
  3513. }
  3514. pQuery->m_dFilters.Resize ( iNumFilters );
  3515. ARRAY_FOREACH ( i, dSorters )
  3516. SafeDelete ( dSorters[i] );
  3517. }
  3518. } else
  3519. {
  3520. ////////////////////////////////
  3521. // run local queries one by one
  3522. ////////////////////////////////
  3523. for ( int iQuery=iStart; iQuery<=iEnd; iQuery++ )
  3524. {
  3525. CSphQuery & tQuery = m_dQueries[iQuery];
  3526. CSphString sError;
  3527. int iNumFilters = tQuery.m_dFilters.GetLength ();
  3528. for ( int i = iLocal + 1; i < dLocal.GetLength (); i++ )
  3529. {
  3530. const ServedIndex_t & tServed = g_hIndexes [ dLocal[i] ];
  3531. if ( tServed.m_pIndex->GetKillListSize () )
  3532. {
  3533. CSphFilterSettings tKillListFilter;
  3534. SetupKillListFilter ( tKillListFilter, tServed.m_pIndex->GetKillList (), tServed.m_pIndex->GetKillListSize () );
  3535. tQuery.m_dFilters.Add ( tKillListFilter );
  3536. }
  3537. }
  3538. // create sorter, if needed
  3539. ISphMatchSorter * pSorter = pLocalSorter;
  3540. if ( !pLocalSorter )
  3541. {
  3542. // fixup old queries
  3543. if ( !FixupQuery ( &tQuery, tServed.m_pSchema, dLocal[iLocal].cstr(), sError ) )
  3544. {
  3545. m_dFailuresSet[iQuery].SubmitEx ( dLocal[iLocal].cstr(), "%s", sError.cstr() );
  3546. continue;
  3547. }
  3548. // create queue
  3549. pSorter = sphCreateQueue ( &tQuery, *tServed.m_pSchema, sError );
  3550. if ( !pSorter )
  3551. {
  3552. m_dFailuresSet[iQuery].SubmitEx ( dLocal[iLocal].cstr(), "%s", sError.cstr() );
  3553. continue;
  3554. }
  3555. }
  3556. // do query
  3557. AggrResult_t & tRes = m_dResults[iQuery];
  3558. if ( !tServed.m_pIndex->QueryEx ( &tQuery, &tRes, pSorter ) )
  3559. m_dFailuresSet[iQuery].SubmitEx ( dLocal[iLocal].cstr(), "%s", tServed.m_pIndex->GetLastError().cstr() );
  3560. else
  3561. tRes.m_iSuccesses++;
  3562. // extract my results and store schema
  3563. if ( pSorter->GetLength() )
  3564. {
  3565. tRes.m_dMatchCounts.Add ( pSorter->GetLength() );
  3566. tRes.m_dSchemas.Add ( tRes.m_tSchema );
  3567. tRes.m_dIndexWeights.Add ( tQuery.GetIndexWeight ( dLocal[iLocal].cstr() ) );
  3568. PoolPtrs_t & tPoolPtrs = tRes.m_dTag2Pools.Add ();
  3569. tPoolPtrs.m_pMva = tRes.m_pMva;
  3570. tPoolPtrs.m_pStrings = tRes.m_pStrings;
  3571. sphFlattenQueue ( pSorter, &tRes, tRes.m_iTag++ );
  3572. }
  3573. // throw away the sorter
  3574. if ( !pLocalSorter )
  3575. SafeDelete ( pSorter );
  3576. tQuery.m_dFilters.Resize ( iNumFilters );
  3577. }
  3578. }
  3579. }
  3580. tmLocal += sphMicroTimer();
  3581. }
  3582. ///////////////////////
  3583. // poll remote queries
  3584. ///////////////////////
  3585. // wait for remote queries to complete
  3586. if ( iRemote )
  3587. {
  3588. m_dFailuresSet.SetIndex ( tFirst.m_sIndexes.cstr() );
  3589. SearchReplyParser_t tParser ( iStart, iEnd );
  3590. int iMsecLeft = pDist->m_iAgentQueryTimeout - int(tmLocal/1000);
  3591. int iReplys = WaitForRemoteAgents ( pDist->m_dAgents, Max(iMsecLeft,0), tParser, &tmWait );
  3592. // check if there were valid (though might be 0-matches) replys, and merge them
  3593. if ( iReplys )
  3594. ARRAY_FOREACH ( iAgent, pDist->m_dAgents )
  3595. {
  3596. Agent_t & tAgent = pDist->m_dAgents[iAgent];
  3597. if ( !tAgent.m_bSuccess )
  3598. continue;
  3599. // merge this agent's results
  3600. for ( int iRes=iStart; iRes<=iEnd; iRes++ )
  3601. {
  3602. const CSphQueryResult & tRemoteResult = tAgent.m_dResults[iRes-iStart];
  3603. // copy errors or warnings
  3604. m_dFailuresSet[iRes].SetPrefix ( "agent %s: ", tAgent.GetName().cstr() );
  3605. if ( !tRemoteResult.m_sError.IsEmpty() )
  3606. m_dFailuresSet[iRes].Submit ( "remote query error: %s", tRemoteResult.m_sError.cstr() );
  3607. if ( !tRemoteResult.m_sWarning.IsEmpty() )
  3608. m_dFailuresSet[iRes].Submit ( "remote query warning: %s", tRemoteResult.m_sWarning.cstr() );
  3609. if ( tRemoteResult.m_iSuccesses<=0 )
  3610. continue;
  3611. AggrResult_t & tRes = m_dResults[iRes];
  3612. tRes.m_iSuccesses++;
  3613. ARRAY_FOREACH ( i, tRemoteResult.m_dMatches )
  3614. {
  3615. tRes.m_dMatches.Add ( tRemoteResult.m_dMatches[i] );
  3616. tRes.m_dMatches.Last().m_iTag = 0; // all remote MVA values go to special pool which is at index 0
  3617. }
  3618. tRes.m_dMatchCounts.Add ( tRemoteResult.m_dMatches.GetLength() );
  3619. tRes.m_dSchemas.Add ( tRemoteResult.m_tSchema );
  3620. // note how we do NOT add per-index weight here; remote agents are all tagged 0 (which contains weight 1)
  3621. // merge this agent's stats
  3622. tRes.m_iTotalMatches += tRemoteResult.m_iTotalMatches;
  3623. tRes.m_iQueryTime += tRemoteResult.m_iQueryTime;
  3624. // merge this agent's words
  3625. if ( !tRes.m_dWordStats.GetLength() )
  3626. {
  3627. // nothing has been set yet; just copy
  3628. tRes.m_dWordStats = tRemoteResult.m_dWordStats;
  3629. } else if ( tRes.m_dWordStats.GetLength()!=tRemoteResult.m_dWordStats.GetLength() )
  3630. {
  3631. // word count mismatch
  3632. m_dFailuresSet[iRes].Submit ( "query words mismatch (%d local, %d remote)",
  3633. tRes.m_dWordStats.GetLength(), tRemoteResult.m_dWordStats.GetLength() );
  3634. } else
  3635. {
  3636. // check for word contents mismatch
  3637. assert ( tRes.m_dWordStats.GetLength()>0 && tRes.m_dWordStats.GetLength()==tRemoteResult.m_dWordStats.GetLength() );
  3638. int iMismatch = -1;
  3639. for ( int i=0; i<tRemoteResult.m_dWordStats.GetLength() && iMismatch<0; i++ )
  3640. if ( tRes.m_dWordStats[i].m_sWord!=tRemoteResult.m_dWordStats[i].m_sWord )
  3641. iMismatch = i;
  3642. if ( iMismatch<0 )
  3643. {
  3644. // everything matches, update stats
  3645. ARRAY_FOREACH ( i, tRemoteResult.m_dWordStats )
  3646. {
  3647. tRes.m_dWordStats[i].m_iDocs += tRemoteResult.m_dWordStats[i].m_iDocs;
  3648. tRes.m_dWordStats[i].m_iHits += tRemoteResult.m_dWordStats[i].m_iHits;
  3649. }
  3650. } else
  3651. {
  3652. // there are mismatches, warn
  3653. m_dFailuresSet[iRes].Submit ( "query words mismatch (word %d, '%s' local vs '%s' remote)",
  3654. iMismatch, tRes.m_dWordStats[iMismatch].m_sWord.cstr(), tRemoteResult.m_dWordStats[iMismatch].m_sWord.cstr() );
  3655. }
  3656. }
  3657. }
  3658. // dismissed
  3659. tAgent.m_dResults.Reset ();
  3660. tAgent.m_bSuccess = false;
  3661. tAgent.m_sFailure = "";
  3662. }
  3663. }
  3664. // check if we need to retry again
  3665. int iToRetry = 0;
  3666. if ( pDist )
  3667. ARRAY_FOREACH ( i, pDist->m_dAgents )
  3668. if ( pDist->m_dAgents[i].m_eState==AGENT_RETRY )
  3669. iToRetry++;
  3670. if ( !iToRetry )
  3671. break;
  3672. }
  3673. // submit failures from failed agents
  3674. if ( pDist )
  3675. {
  3676. m_dFailuresSet.SetIndex ( tFirst.m_sIndexes.cstr() );
  3677. ARRAY_FOREACH ( i, pDist->m_dAgents )
  3678. {
  3679. const Agent_t & tAgent = pDist->m_dAgents[i];
  3680. if ( !tAgent.m_bSuccess && !tAgent.m_sFailure.IsEmpty() )
  3681. m_dFailuresSet.Submit ( "agent %s: %s", tAgent.GetName().cstr(), tAgent.m_sFailure.cstr() );
  3682. }
  3683. }
  3684. ARRAY_FOREACH ( i, m_dResults )
  3685. assert ( m_dResults[i].m_iTag==m_dResults[i].m_dTag2Pools.GetLength() );
  3686. // cleanup
  3687. SafeDelete ( pLocalSorter );
  3688. /////////////////////
  3689. // merge all results
  3690. /////////////////////
  3691. for ( int iRes=iStart; iRes<=iEnd; iRes++ )
  3692. {
  3693. AggrResult_t & tRes = m_dResults[iRes];
  3694. CSphQuery & tQuery = m_dQueries[iRes];
  3695. // if there were no succesful searches at all, this is an error
  3696. if ( !tRes.m_iSuccesses )
  3697. {
  3698. StrBuf_t sFailures;
  3699. m_dFailuresSet[iRes].BuildReport ( sFailures );
  3700. tRes.m_sError = sFailures.cstr();
  3701. continue;
  3702. }
  3703. // minimize schema and remove dupes
  3704. if ( tRes.m_dSchemas.GetLength() )
  3705. tRes.m_tSchema = tRes.m_dSchemas[0];
  3706. if ( tRes.m_iSuccesses>1 || tQuery.m_dItems.GetLength() )
  3707. if ( !MinimizeAggrResult ( tRes, tQuery ) )
  3708. return;
  3709. if ( !m_dFailuresSet[iRes].IsEmpty() )
  3710. {
  3711. StrBuf_t sFailures;
  3712. m_dFailuresSet[iRes].BuildReport ( sFailures );
  3713. tRes.m_sWarning = sFailures.cstr();
  3714. }
  3715. ////////////
  3716. // finalize
  3717. ////////////
  3718. tRes.m_iOffset = tQuery.m_iOffset;
  3719. tRes.m_iCount = Max ( Min ( tQuery.m_iLimit, tRes.m_dMatches.GetLength()-tQuery.m_iOffset ), 0 );
  3720. }
  3721. // stats
  3722. tmSubset = sphMicroTimer() - tmSubset;
  3723. tmCpu = sphCpuTimer() - tmCpu;
  3724. const int iQueries = iEnd-iStart+1;
  3725. for ( int iRes=iStart; iRes<=iEnd; iRes++ )
  3726. {
  3727. m_dResults[iRes].m_iQueryTime = int(tmSubset/1000/iQueries);
  3728. m_dResults[iRes].m_iCpuTime = tmCpu/iQueries;
  3729. m_dResults[iRes].m_iMultiplier = iQueries;
  3730. }
  3731. const CSphIOStats & tIO = sphStopIOStats ();
  3732. if ( g_pStats )
  3733. {
  3734. g_tStatsMutex.Lock();
  3735. g_pStats->m_iQueries += iQueries;
  3736. g_pStats->m_iQueryTime += tmSubset;
  3737. g_pStats->m_iQueryCpuTime += tmCpu;
  3738. if ( pDist && pDist->m_dAgents.GetLength() )
  3739. {
  3740. // do *not* count queries to dist indexes w/o actual remote agents
  3741. g_pStats->m_iDistQueries++;
  3742. g_pStats->m_iDistWallTime += tmSubset;
  3743. g_pStats->m_iDistLocalTime += tmLocal;
  3744. g_pStats->m_iDistWaitTime += tmWait;
  3745. }
  3746. g_pStats->m_iDiskReads += tIO.m_iReadOps;
  3747. g_pStats->m_iDiskReadTime += tIO.m_iReadTime;
  3748. g_pStats->m_iDiskReadBytes += tIO.m_iReadBytes;
  3749. g_tStatsMutex.Unlock();
  3750. }
  3751. }
  3752. bool CheckCommandVersion ( int iVer, int iDaemonVersion, InputBuffer_c & tReq )
  3753. {
  3754. if ( (iVer>>8)!=(iDaemonVersion>>8) )
  3755. {
  3756. tReq.SendErrorReply ( "major command version mismatch (expected v.%d.x, got v.%d.%d)",
  3757. iDaemonVersion>>8, iVer>>8, iVer&0xff );
  3758. return false;
  3759. }
  3760. if ( iVer>iDaemonVersion )
  3761. {
  3762. tReq.SendErrorReply ( "client version is higher than daemon version (client is v.%d.%d, daemon is v.%d.%d)",
  3763. iVer>>8, iVer&0xff, iDaemonVersion>>8, iDaemonVersion&0xff );
  3764. return false;
  3765. }
  3766. return true;
  3767. }
  3768. void SendSearchResponse ( SearchHandler_c & tHandler, InputBuffer_c & tReq, int iSock, int iVer )
  3769. {
  3770. // serve the response
  3771. NetOutputBuffer_c tOut ( iSock );
  3772. int iReplyLen = 0;
  3773. if ( iVer<=0x10C )
  3774. {
  3775. assert ( tHandler.m_dQueries.GetLength()==1 );
  3776. assert ( tHandler.m_dResults.GetLength()==1 );
  3777. const AggrResult_t & tRes = tHandler.m_dResults[0];
  3778. if ( !tRes.m_sError.IsEmpty() )
  3779. {
  3780. tReq.SendErrorReply ( "%s", tRes.m_sError.cstr() );
  3781. return;
  3782. }
  3783. iReplyLen = CalcResultLength ( iVer, &tRes, tRes.m_dTag2Pools );
  3784. bool bWarning = ( iVer>=0x106 && !tRes.m_sWarning.IsEmpty() );
  3785. // send it
  3786. tOut.SendWord ( (WORD)( bWarning ? SEARCHD_WARNING : SEARCHD_OK ) );
  3787. tOut.SendWord ( VER_COMMAND_SEARCH );
  3788. tOut.SendInt ( iReplyLen );
  3789. SendResult ( iVer, tOut, &tRes, tRes.m_dTag2Pools );
  3790. } else
  3791. {
  3792. ARRAY_FOREACH ( i, tHandler.m_dQueries )
  3793. iReplyLen += CalcResultLength ( iVer, &tHandler.m_dResults[i], tHandler.m_dResults[i].m_dTag2Pools );
  3794. // send it
  3795. tOut.SendWord ( (WORD)SEARCHD_OK );
  3796. tOut.SendWord ( VER_COMMAND_SEARCH );
  3797. tOut.SendInt ( iReplyLen );
  3798. ARRAY_FOREACH ( i, tHandler.m_dQueries )
  3799. SendResult ( iVer, tOut, &tHandler.m_dResults[i], tHandler.m_dResults[i].m_dTag2Pools );
  3800. }
  3801. tOut.Flush ();
  3802. assert ( tOut.GetError()==true || tOut.GetSentCount()==iReplyLen+8 );
  3803. // clean up
  3804. ARRAY_FOREACH ( i, tHandler.m_dQueries )
  3805. SafeDeleteArray ( tHandler.m_dQueries[i].m_pWeights );
  3806. }
  3807. void HandleCommandSearch ( int iSock, int iVer, InputBuffer_c & tReq )
  3808. {
  3809. if ( !CheckCommandVersion ( iVer, VER_COMMAND_SEARCH, tReq ) )
  3810. return;
  3811. // parse request
  3812. int iQueries = 1;
  3813. if ( iVer>=0x10D )
  3814. iQueries = tReq.GetDword ();
  3815. const int MAX_QUERIES = 32;
  3816. if ( iQueries<=0 || iQueries>MAX_QUERIES )
  3817. {
  3818. tReq.SendErrorReply ( "bad multi-query count %d (must be in 1..%d range)", iQueries, MAX_QUERIES );
  3819. return;
  3820. }
  3821. SearchHandler_c tHandler ( iQueries );
  3822. ARRAY_FOREACH ( i, tHandler.m_dQueries )
  3823. if ( !ParseSearchQuery ( tReq, tHandler.m_dQueries[i], iVer ) )
  3824. return;
  3825. // run queries, send response
  3826. tHandler.RunQueries ();
  3827. SendSearchResponse ( tHandler, tReq, iSock, iVer );
  3828. }
  3829. //////////////////////////////////////////////////////////////////////////
  3830. // SQL PARSER
  3831. //////////////////////////////////////////////////////////////////////////
  3832. enum SqlStmt_e
  3833. {
  3834. STMT_PARSE_ERROR,
  3835. STMT_SELECT,
  3836. STMT_SHOW_WARNINGS,
  3837. STMT_SHOW_STATUS,
  3838. STMT_SHOW_META
  3839. };
  3840. struct SqlNode_t
  3841. {
  3842. int m_iStart;
  3843. int m_iEnd;
  3844. CSphString m_sValue;
  3845. int64_t m_iValue;
  3846. CSphVector<SphAttr_t> m_dValues;
  3847. SqlNode_t() : m_iValue ( 0 ) {}
  3848. };
  3849. #define YYSTYPE SqlNode_t
  3850. struct SqlParser_t
  3851. {
  3852. const char * m_pBuf;
  3853. const char * m_pLastTokenStart;
  3854. CSphString * m_pParseError;
  3855. CSphQuery * m_pQuery;
  3856. SqlStmt_e m_eStmt;
  3857. bool m_bGotQuery;
  3858. bool AddOption ( SqlNode_t tIdent, SqlNode_t tValue );
  3859. void AddItem ( YYSTYPE * pExpr, YYSTYPE * pAlias, ESphAggrFunc eFunc=SPH_AGGR_NONE );
  3860. };
  3861. void SqlUnescape ( CSphString & sRes, const char * sEscaped, int iLen )
  3862. {
  3863. assert ( iLen>=2 );
  3864. assert ( sEscaped[0]=='\'' );
  3865. assert ( sEscaped[iLen-1]=='\'' );
  3866. // skip heading and trailing quotes
  3867. const char * s = sEscaped+1;
  3868. const char * sMax = s+iLen-2;
  3869. sRes.Reserve ( iLen );
  3870. char * d = (char*) sRes.cstr();
  3871. while ( s<sMax )
  3872. {
  3873. if ( s[0]=='\\' )
  3874. {
  3875. *d++ = s[1];
  3876. s += 2;
  3877. } else
  3878. {
  3879. *d++ = *s++;
  3880. }
  3881. }
  3882. *d++ = '\0';
  3883. }
  3884. //////////////////////////////////////////////////////////////////////////
  3885. // unused parameter, simply to avoid type clash between all my yylex() functions
  3886. #define YY_DECL int yylex ( YYSTYPE * lvalp, SqlParser_t * pParser )
  3887. #include "llsphinxql.c"
  3888. void yyerror ( SqlParser_t * pParser, const char * sMessage )
  3889. {
  3890. pParser->m_pParseError->SetSprintf ( "%s near '%s'", sMessage, pParser->m_pLastTokenStart ? pParser->m_pLastTokenStart : "(null)" );
  3891. }
  3892. #include "yysphinxql.c"
  3893. //////////////////////////////////////////////////////////////////////////
  3894. bool SqlParser_t::AddOption ( SqlNode_t tIdent, SqlNode_t tValue )
  3895. {
  3896. CSphString & sOpt = tIdent.m_sValue;
  3897. CSphString & sVal = tValue.m_sValue;
  3898. sOpt.ToLower ();
  3899. sVal.ToLower ();
  3900. if ( sOpt=="ranker" )
  3901. {
  3902. if ( sVal=="proximity_bm25" ) m_pQuery->m_eRanker = SPH_RANK_PROXIMITY_BM25;
  3903. else if ( sVal=="bm25" ) m_pQuery->m_eRanker = SPH_RANK_BM25;
  3904. else if ( sVal=="none" ) m_pQuery->m_eRanker = SPH_RANK_NONE;
  3905. else if ( sVal=="wordcount" ) m_pQuery->m_eRanker = SPH_RANK_WORDCOUNT;
  3906. else if ( sVal=="proximity" ) m_pQuery->m_eRanker = SPH_RANK_PROXIMITY;
  3907. else if ( sVal=="matchany" ) m_pQuery->m_eRanker = SPH_RANK_MATCHANY;
  3908. else if ( sVal=="fieldmask" ) m_pQuery->m_eRanker = SPH_RANK_FIELDMASK;
  3909. else if ( sVal=="sph04" ) m_pQuery->m_eRanker = SPH_RANK_SPH04;
  3910. else
  3911. {
  3912. m_pParseError->SetSprintf ( "unknown ranker '%s'", sVal.cstr() );
  3913. return false;
  3914. }
  3915. } else if ( sOpt=="max_matches" )
  3916. {
  3917. m_pQuery->m_iMaxMatches = (int)tValue.m_iValue;
  3918. } else if ( sOpt=="cutoff" )
  3919. {
  3920. m_pQuery->m_iCutoff = (int)tValue.m_iValue;
  3921. } else if ( sOpt=="max_query_time" )
  3922. {
  3923. m_pQuery->m_uMaxQueryMsec = (int)tValue.m_iValue;
  3924. } else if ( sOpt=="retry_count" )
  3925. {
  3926. m_pQuery->m_iRetryCount = (int)tValue.m_iValue;
  3927. } else if ( sOpt=="retry_delay" )
  3928. {
  3929. m_pQuery->m_iRetryDelay = (int)tValue.m_iValue;
  3930. } else
  3931. {
  3932. m_pParseError->SetSprintf ( "unknown option '%s'", tIdent.m_sValue.cstr() );
  3933. return false;
  3934. }
  3935. return true;
  3936. }
  3937. void SqlParser_t::AddItem ( YYSTYPE * pExpr, YYSTYPE * pAlias, ESphAggrFunc eFunc )
  3938. {
  3939. CSphQueryItem tItem;
  3940. tItem.m_sExpr.SetBinary ( m_pBuf + pExpr->m_iStart, pExpr->m_iEnd - pExpr->m_iStart );
  3941. if ( pAlias )
  3942. tItem.m_sAlias.SetBinary ( m_pBuf + pAlias->m_iStart, pAlias->m_iEnd - pAlias->m_iStart );
  3943. tItem.m_eAggrFunc = eFunc;
  3944. m_pQuery->m_dItems.Add ( tItem );
  3945. }
  3946. SqlStmt_e ParseSqlQuery ( const CSphString & sQuery, CSphQuery & tQuery, CSphString & sError )
  3947. {
  3948. SqlParser_t tParser;
  3949. tParser.m_pBuf = sQuery.cstr();
  3950. tParser.m_pLastTokenStart = NULL;
  3951. tParser.m_pParseError = &sError;
  3952. tParser.m_pQuery = &tQuery;
  3953. tParser.m_bGotQuery = false;
  3954. tQuery.m_eMode = SPH_MATCH_EXTENDED2; // only new and shiny matching and sorting
  3955. tQuery.m_eSort = SPH_SORT_EXTENDED;
  3956. tQuery.m_sSortBy = "@weight desc"; // default order
  3957. tQuery.m_sOrderBy = "@weight desc";
  3958. int iLen = strlen ( sQuery.cstr() );
  3959. char * sEnd = (char*)sQuery.cstr() + iLen;
  3960. sEnd[0] = 0; // prepare for yy_scan_buffer
  3961. sEnd[1] = 0; // this is ok because string allocates a small gap
  3962. YY_BUFFER_STATE tLexerBuffer = yy_scan_buffer ( (char*)sQuery.cstr(), iLen+2 );
  3963. if ( !tLexerBuffer )
  3964. {
  3965. sError = "internal error: yy_scan_buffer() failed";
  3966. return STMT_PARSE_ERROR;
  3967. }
  3968. int iRes = yyparse ( &tParser );
  3969. yy_delete_buffer ( tLexerBuffer );
  3970. // set proper result-set order
  3971. if ( tQuery.m_sGroupBy.IsEmpty() )
  3972. tQuery.m_sSortBy = tQuery.m_sOrderBy;
  3973. else
  3974. tQuery.m_sGroupSortBy = tQuery.m_sOrderBy;
  3975. if ( iRes!=0 )
  3976. return STMT_PARSE_ERROR;
  3977. else
  3978. return tParser.m_eStmt;
  3979. }
  3980. /////////////////////////////////////////////////////////////////////////////
  3981. void HandleCommandQuery ( int iSock, int iVer, InputBuffer_c & tReq )
  3982. {
  3983. if ( !CheckCommandVersion ( iVer, VER_COMMAND_QUERY, tReq ) )
  3984. return;
  3985. // parse request packet
  3986. DWORD uResponseVer = tReq.GetDword(); // how shall we pack the response packet?
  3987. CSphString sQuery = tReq.GetString(); // what is our query?
  3988. // check for errors
  3989. if ( uResponseVer<0x100 || uResponseVer>VER_COMMAND_SEARCH )
  3990. {
  3991. tReq.SendErrorReply ( "unsupported search response format v.%d.%d requested", uResponseVer>>8, uResponseVer&0xff );
  3992. return;
  3993. }
  3994. if ( tReq.GetError() )
  3995. {
  3996. tReq.SendErrorReply ( "invalid or truncated request" );
  3997. return;
  3998. }
  3999. // parse SQL query
  4000. SearchHandler_c tHandler ( 1 );
  4001. CSphString sError;
  4002. SqlStmt_e eStmt = ParseSqlQuery ( sQuery, tHandler.m_dQueries[0], sError );
  4003. if ( eStmt==STMT_PARSE_ERROR )
  4004. {
  4005. tReq.SendErrorReply ( "%s", sError.cstr() );
  4006. return;
  4007. }
  4008. if ( eStmt!=STMT_SELECT )
  4009. {
  4010. tReq.SendErrorReply ( "this protocol currently supports SELECT only" );
  4011. return;
  4012. }
  4013. // do the dew
  4014. tHandler.RunQueries ();
  4015. SendSearchResponse ( tHandler, tReq, iSock, uResponseVer );
  4016. }
  4017. /////////////////////////////////////////////////////////////////////////////
  4018. // EXCERPTS HANDLER
  4019. /////////////////////////////////////////////////////////////////////////////
  4020. void HandleCommandExcerpt ( int iSock, int iVer, InputBuffer_c & tReq )
  4021. {
  4022. if ( !CheckCommandVersion ( iVer, VER_COMMAND_EXCERPT, tReq ) )
  4023. return;
  4024. /////////////////////////////
  4025. // parse and process request
  4026. /////////////////////////////
  4027. const int EXCERPT_MAX_ENTRIES = 1024;
  4028. const int EXCERPT_FLAG_REMOVESPACES = 1;
  4029. const int EXCERPT_FLAG_EXACTPHRASE = 2;
  4030. const int EXCERPT_FLAG_SINGLEPASSAGE = 4;
  4031. const int EXCERPT_FLAG_USEBOUNDARIES = 8;
  4032. const int EXCERPT_FLAG_WEIGHTORDER = 16;
  4033. const int EXCERPT_FLAG_QUERY = 32;
  4034. // v.1.0
  4035. ExcerptQuery_t q;
  4036. tReq.GetInt (); // mode field is for now reserved and ignored
  4037. int iFlags = tReq.GetInt ();
  4038. CSphString sIndex = tReq.GetString ();
  4039. const ServedIndex_t * pIndex = g_hIndexes(sIndex);
  4040. if ( !pIndex )
  4041. {
  4042. tReq.SendErrorReply ( "unknown local index '%s' in search request", sIndex.cstr() );
  4043. return;
  4044. }
  4045. CSphDict * pDict = pIndex->m_pIndex->GetDictionary ();
  4046. ISphTokenizer * pTokenizer = pIndex->m_pIndex->GetCleanTokenizer ();
  4047. q.m_sWords = tReq.GetString ();
  4048. q.m_sBeforeMatch = tReq.GetString ();
  4049. q.m_sAfterMatch = tReq.GetString ();
  4050. q.m_sChunkSeparator = tReq.GetString ();
  4051. q.m_iLimit = tReq.GetInt ();
  4052. q.m_iAround = tReq.GetInt ();
  4053. q.m_bRemoveSpaces = ( iFlags & EXCERPT_FLAG_REMOVESPACES )!=0;
  4054. q.m_bExactPhrase = ( iFlags & EXCERPT_FLAG_EXACTPHRASE )!=0;
  4055. q.m_bSinglePassage = ( iFlags & EXCERPT_FLAG_SINGLEPASSAGE )!=0;
  4056. q.m_bUseBoundaries = ( iFlags & EXCERPT_FLAG_USEBOUNDARIES )!=0;
  4057. q.m_bWeightOrder = ( iFlags & EXCERPT_FLAG_WEIGHTORDER )!=0;
  4058. q.m_bHighlightQuery = ( iFlags & EXCERPT_FLAG_QUERY )!=0;
  4059. int iCount = tReq.GetInt ();
  4060. if ( iCount<0 || iCount>EXCERPT_MAX_ENTRIES )
  4061. {
  4062. tReq.SendErrorReply ( "invalid entries count %d", iCount );
  4063. return;
  4064. }
  4065. CSphVector<char*> dExcerpts;
  4066. for ( int i=0; i<iCount; i++ )
  4067. {
  4068. q.m_sSource = tReq.GetString ();
  4069. if ( tReq.GetError() )
  4070. {
  4071. tReq.SendErrorReply ( "invalid or truncated request" );
  4072. return;
  4073. }
  4074. const CSphIndexSettings & tSettings = pIndex->m_pIndex->GetSettings ();
  4075. if ( tSettings.m_bHtmlStrip )
  4076. {
  4077. CSphString sError;
  4078. CSphHTMLStripper tStripper;
  4079. if (
  4080. !tStripper.SetIndexedAttrs ( tSettings.m_sHtmlIndexAttrs.cstr (), sError ) ||
  4081. !tStripper.SetRemovedElements ( tSettings.m_sHtmlRemoveElements.cstr (), sError ) )
  4082. {
  4083. tReq.SendErrorReply ( "HTML stripper config error: %s", sError.cstr() );
  4084. return;
  4085. }
  4086. tStripper.Strip ( (BYTE*)q.m_sSource.cstr() );
  4087. }
  4088. CSphString sError;
  4089. char * sResult = sphBuildExcerpt ( q, pDict, pTokenizer, pIndex->m_pSchema, pIndex->m_pIndex, sError );
  4090. if ( !sResult )
  4091. {
  4092. tReq.SendErrorReply ( "highlighting failed: %s", sError.cstr() );
  4093. return;
  4094. }
  4095. dExcerpts.Add ( sResult );
  4096. }
  4097. ////////////////
  4098. // serve result
  4099. ////////////////
  4100. int iRespLen = 0;
  4101. ARRAY_FOREACH ( i, dExcerpts )
  4102. iRespLen += 4 + strlen ( dExcerpts[i] );
  4103. NetOutputBuffer_c tOut ( iSock );
  4104. tOut.SendWord ( SEARCHD_OK );
  4105. tOut.SendWord ( VER_COMMAND_EXCERPT );
  4106. tOut.SendInt ( iRespLen );
  4107. ARRAY_FOREACH ( i, dExcerpts )
  4108. {
  4109. tOut.SendString ( dExcerpts[i] );
  4110. SafeDeleteArray ( dExcerpts[i] );
  4111. }
  4112. tOut.Flush ();
  4113. assert ( tOut.GetError()==true || tOut.GetSentCount()==iRespLen+8 );
  4114. }
  4115. /////////////////////////////////////////////////////////////////////////////
  4116. // KEYWORDS HANDLER
  4117. /////////////////////////////////////////////////////////////////////////////
  4118. void HandleCommandKeywords ( int iSock, int iVer, InputBuffer_c & tReq )
  4119. {
  4120. if ( !CheckCommandVersion ( iVer, VER_COMMAND_KEYWORDS, tReq ) )
  4121. return;
  4122. CSphString sQuery = tReq.GetString ();
  4123. CSphString sIndex = tReq.GetString ();
  4124. bool bGetStats = !!tReq.GetInt ();
  4125. const ServedIndex_t * pIndex = g_hIndexes(sIndex);
  4126. if ( !pIndex )
  4127. {
  4128. tReq.SendErrorReply ( "unknown local index '%s' in search request", sIndex.cstr() );
  4129. return;
  4130. }
  4131. CSphVector < CSphKeywordInfo > dKeywords;
  4132. if ( !pIndex->m_pIndex->GetKeywords ( dKeywords, sQuery.cstr (), bGetStats ) )
  4133. {
  4134. tReq.SendErrorReply ( "error generating keywords: %s", pIndex->m_pIndex->GetLastError ().cstr () );
  4135. return;
  4136. }
  4137. int iRespLen = 4;
  4138. ARRAY_FOREACH ( i, dKeywords )
  4139. {
  4140. iRespLen += 4 + strlen ( dKeywords [i].m_sTokenized.cstr () );
  4141. iRespLen += 4 + strlen ( dKeywords [i].m_sNormalized.cstr () );
  4142. if ( bGetStats )
  4143. iRespLen += 8;
  4144. }
  4145. NetOutputBuffer_c tOut ( iSock );
  4146. tOut.SendWord ( SEARCHD_OK );
  4147. tOut.SendWord ( VER_COMMAND_KEYWORDS );
  4148. tOut.SendInt ( iRespLen );
  4149. tOut.SendInt ( dKeywords.GetLength () );
  4150. ARRAY_FOREACH ( i, dKeywords )
  4151. {
  4152. tOut.SendString ( dKeywords [i].m_sTokenized.cstr () );
  4153. tOut.SendString ( dKeywords [i].m_sNormalized.cstr () );
  4154. if ( bGetStats )
  4155. {
  4156. tOut.SendInt ( dKeywords [i].m_iDocs );
  4157. tOut.SendInt ( dKeywords [i].m_iHits );
  4158. }
  4159. }
  4160. tOut.Flush ();
  4161. assert ( tOut.GetError()==true || tOut.GetSentCount()==iRespLen+8 );
  4162. }
  4163. /////////////////////////////////////////////////////////////////////////////
  4164. // UPDATES HANDLER
  4165. /////////////////////////////////////////////////////////////////////////////
  4166. struct UpdateRequestBuilder_t : public IRequestBuilder_t
  4167. {
  4168. UpdateRequestBuilder_t ( const CSphAttrUpdate & pUpd ) : m_tUpd ( pUpd ) {}
  4169. virtual void BuildRequest ( const char * sIndexes, NetOutputBuffer_c & tOut ) const;
  4170. protected:
  4171. const CSphAttrUpdate & m_tUpd;
  4172. };
  4173. struct UpdateReplyParser_t : public IReplyParser_t
  4174. {
  4175. UpdateReplyParser_t ( int * pUpd )
  4176. : m_pUpdated ( pUpd )
  4177. {}
  4178. virtual bool ParseReply ( MemInputBuffer_c & tReq, Agent_t & ) const
  4179. {
  4180. *m_pUpdated += tReq.GetDword ();
  4181. return true;
  4182. }
  4183. protected:
  4184. int * m_pUpdated;
  4185. };
  4186. void UpdateRequestBuilder_t::BuildRequest ( const char * sIndexes, NetOutputBuffer_c & tOut ) const
  4187. {
  4188. int iReqSize = 4+strlen(sIndexes); // indexes string
  4189. iReqSize += 4; // attrs array len, data
  4190. ARRAY_FOREACH ( i, m_tUpd.m_dAttrs )
  4191. iReqSize += 8+strlen(m_tUpd.m_dAttrs[i].m_sName.cstr());
  4192. iReqSize += 4; // number of updates
  4193. iReqSize += 8*m_tUpd.m_dDocids.GetLength() + 4*m_tUpd.m_dPool.GetLength(); // 64bit ids, 32bit values
  4194. // header
  4195. tOut.SendDword ( SPHINX_SEARCHD_PROTO );
  4196. tOut.SendWord ( SEARCHD_COMMAND_UPDATE );
  4197. tOut.SendWord ( VER_COMMAND_UPDATE );
  4198. tOut.SendInt ( iReqSize );
  4199. tOut.SendString ( sIndexes );
  4200. tOut.SendInt ( m_tUpd.m_dAttrs.GetLength() );
  4201. ARRAY_FOREACH ( i, m_tUpd.m_dAttrs )
  4202. {
  4203. tOut.SendString ( m_tUpd.m_dAttrs[i].m_sName.cstr() );
  4204. tOut.SendInt ( ( m_tUpd.m_dAttrs[i].m_eAttrType & SPH_ATTR_MULTI ) ? 1 : 0 );
  4205. }
  4206. tOut.SendInt ( m_tUpd.m_dDocids.GetLength() );
  4207. ARRAY_FOREACH ( i, m_tUpd.m_dDocids )
  4208. {
  4209. int iHead = m_tUpd.m_dRowOffset[i];
  4210. int iTail = ( (i+1)<m_tUpd.m_dDocids.GetLength() ) ? m_tUpd.m_dRowOffset[i+1] : m_tUpd.m_dPool.GetLength ();
  4211. tOut.SendUint64 ( m_tUpd.m_dDocids[i] );
  4212. for ( int j=iHead; j<iTail; j++ )
  4213. tOut.SendDword ( m_tUpd.m_dPool[j] );
  4214. }
  4215. }
  4216. template < typename T, typename U >
  4217. struct CSphPair
  4218. {
  4219. T m_tFirst;
  4220. U m_tSecond;
  4221. };
  4222. void HandleCommandUpdate ( int iSock, int iVer, InputBuffer_c & tReq, int iPipeFD )
  4223. {
  4224. if ( !CheckCommandVersion ( iVer, VER_COMMAND_UPDATE, tReq ) )
  4225. return;
  4226. // parse request
  4227. CSphString sIndexes = tReq.GetString ();
  4228. CSphAttrUpdate tUpd;
  4229. tUpd.m_dAttrs.Resize ( tReq.GetDword() ); // FIXME! check this
  4230. ARRAY_FOREACH ( i, tUpd.m_dAttrs )
  4231. {
  4232. tUpd.m_dAttrs[i].m_sName = tReq.GetString ();
  4233. tUpd.m_dAttrs[i].m_sName.ToLower ();
  4234. tUpd.m_dAttrs[i].m_eAttrType = SPH_ATTR_INTEGER;
  4235. if ( iVer>=0x102 )
  4236. if ( tReq.GetDword() )
  4237. tUpd.m_dAttrs[i].m_eAttrType |= SPH_ATTR_MULTI;
  4238. }
  4239. int iNumUpdates = tReq.GetInt (); // FIXME! check this
  4240. tUpd.m_dDocids.Reserve ( iNumUpdates );
  4241. tUpd.m_dRowOffset.Reserve ( iNumUpdates );
  4242. for ( int i=0; i<iNumUpdates; i++ )
  4243. {
  4244. // v.1.0 always sends 32-bit ids; v.1.1+ always send 64-bit ones
  4245. uint64_t uDocid = ( iVer>=0x101 ) ? tReq.GetUint64 () : tReq.GetDword ();
  4246. tUpd.m_dDocids.Add ( (SphDocID_t)uDocid ); // FIXME! check this
  4247. tUpd.m_dRowOffset.Add ( tUpd.m_dPool.GetLength() );
  4248. ARRAY_FOREACH ( iAttr, tUpd.m_dAttrs )
  4249. {
  4250. DWORD uCount = 1;
  4251. if ( tUpd.m_dAttrs[iAttr].m_eAttrType & SPH_ATTR_MULTI )
  4252. {
  4253. uCount = tReq.GetDword ();
  4254. tUpd.m_dPool.Add ( uCount );
  4255. }
  4256. for ( DWORD j=0; j<uCount; j++ )
  4257. tUpd.m_dPool.Add ( tReq.GetDword() );
  4258. }
  4259. }
  4260. if ( tReq.GetError() )
  4261. {
  4262. tReq.SendErrorReply ( "invalid or truncated request" );
  4263. return;
  4264. }
  4265. // check index names
  4266. CSphVector<CSphString> dIndexNames;
  4267. ParseIndexList ( sIndexes, dIndexNames );
  4268. if ( !dIndexNames.GetLength() )
  4269. {
  4270. tReq.SendErrorReply ( "no valid indexes in update request" );
  4271. return;
  4272. }
  4273. ARRAY_FOREACH ( i, dIndexNames )
  4274. {
  4275. if ( !g_hIndexes(dIndexNames[i]) && !g_hDistIndexes(dIndexNames[i]) )
  4276. {
  4277. tReq.SendErrorReply ( "unknown index '%s' in update request", dIndexNames[i].cstr() );
  4278. return;
  4279. }
  4280. }
  4281. // do update
  4282. SearchFailuresLogset_c dFailuresSet;
  4283. dFailuresSet.SetSize ( 1 );
  4284. dFailuresSet.SetSubset ( 0, 0 );
  4285. int iSuccesses = 0;
  4286. int iUpdated = 0;
  4287. CSphVector < CSphPair < CSphString, DWORD > > dUpdated;
  4288. ARRAY_FOREACH ( iIdx, dIndexNames )
  4289. {
  4290. const char * sReqIndex = dIndexNames[iIdx].cstr();
  4291. CSphVector<CSphString> dLocal;
  4292. const CSphVector<CSphString> * pLocal = NULL;
  4293. if ( g_hIndexes(sReqIndex) )
  4294. {
  4295. dLocal.Add ( sReqIndex );
  4296. pLocal = &dLocal;
  4297. } else
  4298. {
  4299. assert ( g_hDistIndexes(sReqIndex) );
  4300. pLocal = &g_hDistIndexes[sReqIndex].m_dLocal;
  4301. }
  4302. // update local indexes
  4303. assert ( pLocal );
  4304. ARRAY_FOREACH ( i, (*pLocal) )
  4305. {
  4306. const char * sIndex = (*pLocal)[i].cstr();
  4307. ServedIndex_t * pServed = g_hIndexes(sIndex);
  4308. dFailuresSet.SetIndex ( sIndex );
  4309. dFailuresSet.SetPrefix ( "" );
  4310. if ( !pServed || !pServed->m_pIndex )
  4311. {
  4312. dFailuresSet.Submit ( "index not available" );
  4313. continue;
  4314. }
  4315. DWORD uStatusDelta = pServed->m_pIndex->m_uAttrsStatus;
  4316. int iUpd = pServed->m_pIndex->UpdateAttributes ( tUpd );
  4317. uStatusDelta = pServed->m_pIndex->m_uAttrsStatus & ~uStatusDelta;
  4318. if ( iUpd<0 )
  4319. {
  4320. dFailuresSet.Submit ( "%s", pServed->m_pIndex->GetLastError().cstr() );
  4321. } else
  4322. {
  4323. iUpdated += iUpd;
  4324. iSuccesses++;
  4325. CSphPair<CSphString,DWORD> tAdd;
  4326. tAdd.m_tFirst = sIndex;
  4327. tAdd.m_tSecond = uStatusDelta;
  4328. dUpdated.Add ( tAdd );
  4329. }
  4330. }
  4331. // update remote agents
  4332. if ( g_hDistIndexes(sReqIndex) )
  4333. {
  4334. DistributedIndex_t & tDist = g_hDistIndexes[sReqIndex];
  4335. dFailuresSet.SetIndex ( sReqIndex );
  4336. // connect to remote agents and query them
  4337. ConnectToRemoteAgents ( tDist.m_dAgents, false );
  4338. UpdateRequestBuilder_t tReqBuilder ( tUpd );
  4339. int iRemote = QueryRemoteAgents ( tDist.m_dAgents, tDist.m_iAgentConnectTimeout, tReqBuilder, NULL ); // FIXME? profile update time too?
  4340. if ( iRemote )
  4341. {
  4342. UpdateReplyParser_t tParser ( &iUpdated );
  4343. iSuccesses += WaitForRemoteAgents ( tDist.m_dAgents, tDist.m_iAgentQueryTimeout, tParser, NULL ); // FIXME? profile update time too?
  4344. }
  4345. }
  4346. }
  4347. // notify head daemon of local updates
  4348. if ( iPipeFD>=0 )
  4349. {
  4350. DWORD uTmp = SPH_PIPE_UPDATED_ATTRS;
  4351. ::write ( iPipeFD, &uTmp, sizeof(DWORD) );
  4352. uTmp = dUpdated.GetLength();
  4353. ::write ( iPipeFD, &uTmp, sizeof(DWORD) );
  4354. ARRAY_FOREACH ( i, dUpdated )
  4355. {
  4356. uTmp = strlen ( dUpdated[i].m_tFirst.cstr() );
  4357. ::write ( iPipeFD, &uTmp, sizeof(DWORD) );
  4358. ::write ( iPipeFD, dUpdated[i].m_tFirst.cstr(), uTmp );
  4359. uTmp = dUpdated[i].m_tSecond;
  4360. ::write ( iPipeFD, &uTmp, sizeof(DWORD) );
  4361. }
  4362. }
  4363. // serve reply to client
  4364. StrBuf_t sReport;
  4365. dFailuresSet[0].BuildReport ( sReport );
  4366. if ( !iSuccesses )
  4367. {
  4368. tReq.SendErrorReply ( "%s", sReport.cstr() );
  4369. return;
  4370. }
  4371. NetOutputBuffer_c tOut ( iSock );
  4372. if ( dFailuresSet[0].IsEmpty() )
  4373. {
  4374. tOut.SendWord ( SEARCHD_OK );
  4375. tOut.SendWord ( VER_COMMAND_UPDATE );
  4376. tOut.SendInt ( 4 );
  4377. } else
  4378. {
  4379. tOut.SendWord ( SEARCHD_WARNING );
  4380. tOut.SendWord ( VER_COMMAND_UPDATE );
  4381. tOut.SendInt ( 8+strlen(sReport.cstr()) );
  4382. tOut.SendString ( sReport.cstr() );
  4383. }
  4384. tOut.SendInt ( iUpdated );
  4385. tOut.Flush ();
  4386. }
  4387. //////////////////////////////////////////////////////////////////////////
  4388. // STATUS HANDLER
  4389. //////////////////////////////////////////////////////////////////////////
  4390. static inline void FormatMsec ( CSphString & sOut, int64_t tmTime )
  4391. {
  4392. sOut.SetSprintf ( "%d.%03d", int(tmTime/1000000), int((tmTime%1000000)/1000) );
  4393. }
  4394. void BuildStatus ( CSphVector<CSphString> & dStatus )
  4395. {
  4396. assert ( g_pStats );
  4397. const char * FMT64 = "%"PRIu64;
  4398. const char * OFF = "OFF";
  4399. const int64_t iQueriesDiv = Max ( g_pStats->m_iQueries, 1 );
  4400. const int64_t iDistQueriesDiv = Max ( g_pStats->m_iDistQueries, 1 );
  4401. // FIXME? non-transactional!!!
  4402. dStatus.Add ( "uptime" ); dStatus.Add().SetSprintf ( "%u", (DWORD)time(NULL)-g_pStats->m_uStarted );
  4403. dStatus.Add ( "connections" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iConnections );
  4404. dStatus.Add ( "maxed_out" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iMaxedOut );
  4405. dStatus.Add ( "command_search" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iCommandCount[SEARCHD_COMMAND_SEARCH] );
  4406. dStatus.Add ( "command_excerpt" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iCommandCount[SEARCHD_COMMAND_EXCERPT] );
  4407. dStatus.Add ( "command_update" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iCommandCount[SEARCHD_COMMAND_UPDATE] );
  4408. dStatus.Add ( "command_keywords" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iCommandCount[SEARCHD_COMMAND_KEYWORDS] );
  4409. dStatus.Add ( "command_persist" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iCommandCount[SEARCHD_COMMAND_PERSIST] );
  4410. dStatus.Add ( "command_status" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iCommandCount[SEARCHD_COMMAND_STATUS] );
  4411. dStatus.Add ( "agent_connect" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iAgentConnect );
  4412. dStatus.Add ( "agent_retry" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iAgentRetry );
  4413. dStatus.Add ( "queries" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iQueries );
  4414. dStatus.Add ( "dist_queries" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iDistQueries );
  4415. dStatus.Add ( "query_wall" ); FormatMsec ( dStatus.Add(), g_pStats->m_iQueryTime );
  4416. dStatus.Add ( "query_cpu" );
  4417. if ( g_bCpuStats )
  4418. FormatMsec ( dStatus.Add(), g_pStats->m_iQueryCpuTime );
  4419. else
  4420. dStatus.Add() = OFF;
  4421. dStatus.Add ( "dist_wall" ); FormatMsec ( dStatus.Add(), g_pStats->m_iDistWallTime );
  4422. dStatus.Add ( "dist_local" ); FormatMsec ( dStatus.Add(), g_pStats->m_iDistLocalTime );
  4423. dStatus.Add ( "dist_wait" ); FormatMsec ( dStatus.Add(), g_pStats->m_iDistWaitTime );
  4424. if ( g_bIOStats )
  4425. {
  4426. dStatus.Add ( "query_reads" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iDiskReads );
  4427. dStatus.Add ( "query_readkb" ); dStatus.Add().SetSprintf ( FMT64, g_pStats->m_iDiskReadBytes/1024 );
  4428. dStatus.Add ( "query_readtime" ); FormatMsec ( dStatus.Add(), g_pStats->m_iDiskReadTime );
  4429. } else
  4430. {
  4431. dStatus.Add ( "query_reads" ); dStatus.Add() = OFF;
  4432. dStatus.Add ( "query_readkb" ); dStatus.Add() = OFF;
  4433. dStatus.Add ( "query_readtime" ); dStatus.Add() = OFF;
  4434. }
  4435. dStatus.Add ( "avg_query_wall" ); FormatMsec ( dStatus.Add(), g_pStats->m_iQueryTime / iQueriesDiv );
  4436. dStatus.Add ( "avg_query_cpu" );
  4437. if ( g_bCpuStats )
  4438. FormatMsec ( dStatus.Add(), g_pStats->m_iQueryCpuTime / iQueriesDiv );
  4439. else
  4440. dStatus.Add ( OFF );
  4441. dStatus.Add ( "avg_dist_wall" ); FormatMsec ( dStatus.Add(), g_pStats->m_iDistWallTime / iDistQueriesDiv );
  4442. dStatus.Add ( "avg_dist_local" ); FormatMsec ( dStatus.Add(), g_pStats->m_iDistLocalTime / iDistQueriesDiv );
  4443. dStatus.Add ( "avg_dist_wait" ); FormatMsec ( dStatus.Add(), g_pStats->m_iDistWaitTime / iDistQueriesDiv );
  4444. if ( g_bIOStats )
  4445. {
  4446. dStatus.Add ( "avg_query_reads" ); dStatus.Add().SetSprintf ( "%.1f", float(g_pStats->m_iDiskReads*10/iQueriesDiv)/10.0f );
  4447. dStatus.Add ( "avg_query_readkb" ); dStatus.Add().SetSprintf ( "%.1f", float(g_pStats->m_iDiskReadBytes/iQueriesDiv)/1024.0f );
  4448. dStatus.Add ( "avg_query_readtime" ); FormatMsec ( dStatus.Add(), g_pStats->m_iDiskReadTime/iQueriesDiv );
  4449. } else
  4450. {
  4451. dStatus.Add ( "avg_query_reads" ); dStatus.Add() = OFF;
  4452. dStatus.Add ( "avg_query_readkb" ); dStatus.Add() = OFF;
  4453. dStatus.Add ( "avg_query_readtime" ); dStatus.Add() = OFF;
  4454. }
  4455. }
  4456. void BuildMeta ( CSphVector<CSphString> & dStatus, const CSphQueryResultMeta & tMeta )
  4457. {
  4458. if ( !tMeta.m_sError.IsEmpty() )
  4459. {
  4460. dStatus.Add ( "error" );
  4461. dStatus.Add ( tMeta.m_sError );
  4462. }
  4463. if ( !tMeta.m_sWarning.IsEmpty() )
  4464. {
  4465. dStatus.Add ( "warning" );
  4466. dStatus.Add ( tMeta.m_sWarning );
  4467. }
  4468. dStatus.Add ( "total" );
  4469. dStatus.Add().SetSprintf ( "%d", tMeta.m_iMatches );
  4470. dStatus.Add ( "total_found" );
  4471. dStatus.Add().SetSprintf ( "%d", tMeta.m_iTotalMatches );
  4472. dStatus.Add ( "time" );
  4473. dStatus.Add().SetSprintf ( "%d.%03d", tMeta.m_iQueryTime/1000, tMeta.m_iQueryTime%1000 );
  4474. ARRAY_FOREACH ( i, tMeta.m_dWordStats )
  4475. {
  4476. dStatus.Add().SetSprintf ( "keyword[%d]", i );
  4477. dStatus.Add ( tMeta.m_dWordStats[i].m_sWord );
  4478. dStatus.Add().SetSprintf ( "docs[%d]", i );
  4479. dStatus.Add().SetSprintf ( "%d", tMeta.m_dWordStats[i].m_iDocs );
  4480. dStatus.Add().SetSprintf ( "hits[%d]", i );
  4481. dStatus.Add().SetSprintf ( "%d", tMeta.m_dWordStats[i].m_iHits );
  4482. }
  4483. }
  4484. void HandleCommandStatus ( int iSock, int iVer, InputBuffer_c & tReq )
  4485. {
  4486. if ( !CheckCommandVersion ( iVer, VER_COMMAND_STATUS, tReq ) )
  4487. return;
  4488. if ( !g_pStats )
  4489. {
  4490. tReq.SendErrorReply ( "performance counters disabled" );
  4491. return;
  4492. }
  4493. CSphVector<CSphString> dStatus;
  4494. BuildStatus ( dStatus );
  4495. int iRespLen = 8; // int rows, int cols
  4496. ARRAY_FOREACH ( i, dStatus )
  4497. iRespLen += 4+strlen(dStatus[i].cstr());
  4498. NetOutputBuffer_c tOut ( iSock );
  4499. tOut.SendWord ( SEARCHD_OK );
  4500. tOut.SendWord ( VER_COMMAND_STATUS );
  4501. tOut.SendInt ( iRespLen );
  4502. tOut.SendInt ( dStatus.GetLength()/2 ); // rows
  4503. tOut.SendInt ( 2 ); // cols
  4504. ARRAY_FOREACH ( i, dStatus )
  4505. tOut.SendString ( dStatus[i].cstr() );
  4506. tOut.Flush ();
  4507. assert ( tOut.GetError()==true || tOut.GetSentCount()==8+iRespLen );
  4508. }
  4509. /////////////////////////////////////////////////////////////////////////////
  4510. // GENERAL HANDLER
  4511. /////////////////////////////////////////////////////////////////////////////
  4512. void SafeClose ( int & iFD )
  4513. {
  4514. if ( iFD>=0 )
  4515. ::close ( iFD );
  4516. iFD = -1;
  4517. }
  4518. void HandleClientSphinx ( int iSock, const char * sClientIP, int iPipeFD )
  4519. {
  4520. bool bPersist = false;
  4521. int iTimeout = g_iReadTimeout;
  4522. NetInputBuffer_c tBuf ( iSock );
  4523. // send my version
  4524. DWORD uServer = htonl ( SPHINX_SEARCHD_PROTO );
  4525. if ( sphSockSend ( iSock, (char*)&uServer, sizeof(DWORD) )!=sizeof(DWORD) )
  4526. {
  4527. sphWarning ( "failed to send server version (client=%s)", sClientIP );
  4528. return;
  4529. }
  4530. // get client version and request
  4531. tBuf.ReadFrom ( 4 ); // FIXME! magic
  4532. tBuf.GetInt (); // client version is for now unused
  4533. do
  4534. {
  4535. g_pCrashLog_LastQuery = NULL;
  4536. tBuf.ReadFrom ( 8, iTimeout );
  4537. int iCommand = tBuf.GetWord ();
  4538. int iCommandVer = tBuf.GetWord ();
  4539. int iLength = tBuf.GetInt ();
  4540. if ( tBuf.GetError() )
  4541. {
  4542. // under high load, there can be pretty frequent accept() vs connect() timeouts
  4543. // lets avoid agent log flood
  4544. //
  4545. // sphWarning ( "failed to receive client version and request (client=%s, error=%s)", sClientIP, sphSockError() );
  4546. return;
  4547. }
  4548. if ( g_bCrashLog_Enabled )
  4549. memcpy ( g_dCrashLog_LastHello + 4, tBuf.GetBufferPtr(), sizeof(g_dCrashLog_LastHello) - 4 );
  4550. // check request
  4551. if ( iCommand<0 || iCommand>=SEARCHD_COMMAND_TOTAL
  4552. || iLength<=0 || iLength>g_iMaxPacketSize )
  4553. {
  4554. // unknown command, default response header
  4555. tBuf.SendErrorReply ( "unknown command (code=%d)", iCommand );
  4556. // if request length is insane, low level comm is broken, so we bail out
  4557. if ( iLength<=0 || iLength>g_iMaxPacketSize )
  4558. {
  4559. sphWarning ( "ill-formed client request (length=%d out of bounds)", iLength );
  4560. return;
  4561. }
  4562. }
  4563. // count commands
  4564. if ( g_pStats && iCommand>=0 && iCommand<SEARCHD_COMMAND_TOTAL )
  4565. {
  4566. g_tStatsMutex.Lock();
  4567. g_pStats->m_iCommandCount[iCommand]++;
  4568. g_tStatsMutex.Unlock();
  4569. }
  4570. // get request body
  4571. assert ( iLength>0 && iLength<=g_iMaxPacketSize );
  4572. if ( !tBuf.ReadFrom ( iLength ) )
  4573. {
  4574. sphWarning ( "failed to receive client request body (client=%s, exp=%d)", sClientIP, iLength );
  4575. return;
  4576. }
  4577. if ( g_bCrashLog_Enabled )
  4578. {
  4579. g_pCrashLog_LastQuery = tBuf.GetBufferPtr();
  4580. g_iCrashLog_LastQuerySize = iLength;
  4581. }
  4582. // handle known commands
  4583. assert ( iCommand>=0 && iCommand<SEARCHD_COMMAND_TOTAL );
  4584. switch ( iCommand )
  4585. {
  4586. case SEARCHD_COMMAND_SEARCH: HandleCommandSearch ( iSock, iCommandVer, tBuf ); break;
  4587. case SEARCHD_COMMAND_EXCERPT: HandleCommandExcerpt ( iSock, iCommandVer, tBuf ); break;
  4588. case SEARCHD_COMMAND_KEYWORDS: HandleCommandKeywords ( iSock, iCommandVer, tBuf ); break;
  4589. case SEARCHD_COMMAND_UPDATE: HandleCommandUpdate ( iSock, iCommandVer, tBuf, iPipeFD ); break;
  4590. case SEARCHD_COMMAND_PERSIST: bPersist = ( tBuf.GetInt()!=0 ); iTimeout = g_iClientTimeout; break;
  4591. case SEARCHD_COMMAND_STATUS: HandleCommandStatus ( iSock, iCommandVer, tBuf ); break;
  4592. case SEARCHD_COMMAND_QUERY: HandleCommandQuery ( iSock, iCommandVer, tBuf ); break;
  4593. default: assert ( 0 && "INTERNAL ERROR: unhandled command" ); break;
  4594. }
  4595. } while ( bPersist );
  4596. SafeClose ( iPipeFD );
  4597. }
  4598. //////////////////////////////////////////////////////////////////////////
  4599. // MYSQLD PRETENDER
  4600. //////////////////////////////////////////////////////////////////////////
  4601. /// our copy of enum_field_types
  4602. /// we can't rely on mysql_com.h because it might be unavailable
  4603. ///
  4604. /// MYSQL_TYPE_DECIMAL = 0
  4605. /// MYSQL_TYPE_TINY = 1
  4606. /// MYSQL_TYPE_SHORT = 2
  4607. /// MYSQL_TYPE_LONG = 3
  4608. /// MYSQL_TYPE_FLOAT = 4
  4609. /// MYSQL_TYPE_DOUBLE = 5
  4610. /// MYSQL_TYPE_NULL = 6
  4611. /// MYSQL_TYPE_TIMESTAMP = 7
  4612. /// MYSQL_TYPE_LONGLONG = 8
  4613. /// MYSQL_TYPE_INT24 = 9
  4614. /// MYSQL_TYPE_DATE = 10
  4615. /// MYSQL_TYPE_TIME = 11
  4616. /// MYSQL_TYPE_DATETIME = 12
  4617. /// MYSQL_TYPE_YEAR = 13
  4618. /// MYSQL_TYPE_NEWDATE = 14
  4619. /// MYSQL_TYPE_VARCHAR = 15
  4620. /// MYSQL_TYPE_BIT = 16
  4621. /// MYSQL_TYPE_NEWDECIMAL = 246
  4622. /// MYSQL_TYPE_ENUM = 247
  4623. /// MYSQL_TYPE_SET = 248
  4624. /// MYSQL_TYPE_TINY_BLOB = 249
  4625. /// MYSQL_TYPE_MEDIUM_BLOB = 250
  4626. /// MYSQL_TYPE_LONG_BLOB = 251
  4627. /// MYSQL_TYPE_BLOB = 252
  4628. /// MYSQL_TYPE_VAR_STRING = 253
  4629. /// MYSQL_TYPE_STRING = 254
  4630. /// MYSQL_TYPE_GEOMETRY = 255
  4631. enum MysqlColumnType_e
  4632. {
  4633. MYSQL_COL_DECIMAL = 0,
  4634. MYSQL_COL_STRING = 254
  4635. };
  4636. void SendMysqlFieldPacket ( NetOutputBuffer_c & tOut, BYTE uPacketID, const char * sCol, MysqlColumnType_e eType )
  4637. {
  4638. const char * sDB = "";
  4639. const char * sTable = "";
  4640. int iLen = 17 + tOut.GetMysqlPacklen(sDB) + 2*( tOut.GetMysqlPacklen(sTable) + tOut.GetMysqlPacklen(sCol) );
  4641. int iColLen = 0;
  4642. switch ( eType )
  4643. {
  4644. case MYSQL_COL_DECIMAL: iColLen = 20; break;
  4645. case MYSQL_COL_STRING: iColLen = 255; break;
  4646. }
  4647. tOut.SendLSBDword ( (uPacketID<<24) + iLen );
  4648. tOut.SendMysqlString ( "def" ); // catalog
  4649. tOut.SendMysqlString ( sDB ); // db
  4650. tOut.SendMysqlString ( sTable ); // table
  4651. tOut.SendMysqlString ( sTable ); // org_table
  4652. tOut.SendMysqlString ( sCol ); // name
  4653. tOut.SendMysqlString ( sCol ); // org_name
  4654. tOut.SendByte ( 12 ); // filler, must be 12 (following pseudo-string length)
  4655. tOut.SendByte ( 8 ); // charset_nr, 8 is latin1
  4656. tOut.SendByte ( 0 ); // charset_nr
  4657. tOut.SendLSBDword ( iColLen ); // length
  4658. tOut.SendByte ( BYTE(eType) ); // type (0=decimal)
  4659. tOut.SendWord ( 0 ); // flags
  4660. tOut.SendByte ( 0 ); // decimals
  4661. tOut.SendWord ( 0 ); // filler
  4662. }
  4663. void SendMysqlErrorPacket ( NetOutputBuffer_c & tOut, BYTE uPacketID, const char * sError )
  4664. {
  4665. if ( sError==NULL )
  4666. sError = "(null)";
  4667. int iErrorLen = strlen(sError)+1; // including the trailing zero
  4668. int iLen = 9 + iErrorLen;
  4669. int iError = 1064; // pretend to be mysql syntax error for now
  4670. tOut.SendLSBDword ( (uPacketID<<24) + iLen );
  4671. tOut.SendByte ( 0xff ); // field count, always 0xff for error packet
  4672. tOut.SendByte ( BYTE(iError&0xff) );
  4673. tOut.SendByte ( BYTE(iError>>8) );
  4674. tOut.SendBytes ( "#42000", 6 ); // sqlstate marker (1 byte), sqlstate (5 bytes)
  4675. tOut.SendBytes ( sError, iErrorLen );
  4676. }
  4677. void SendMysqlEofPacket ( NetOutputBuffer_c & tOut, BYTE uPacketID, int iWarns )
  4678. {
  4679. if ( iWarns<0 ) iWarns = 0;
  4680. if ( iWarns>65535 ) iWarns = 65535;
  4681. tOut.SendLSBDword ( (uPacketID<<24) + 5 );
  4682. tOut.SendByte ( 0xfe );
  4683. tOut.SendLSBDword ( iWarns ); // N warnings, 0 status
  4684. }
  4685. void HandleClientMySQL ( int iSock, const char * sClientIP, int iPipeFD )
  4686. {
  4687. // handshake
  4688. char sHandshake[] =
  4689. "\x00\x00\x00" // packet length
  4690. "\x00" // packet id
  4691. "\x0A" // protocol version; v.10
  4692. SPHINX_VERSION "\x00" // server version
  4693. "\x01\x00\x00\x00" // thread id
  4694. "\x01\x02\x03\x04\x05\x06\x07\x08" // scramble buffer (for auth)
  4695. "\x00" // filler
  4696. "\x08\x02" // server capabilities; CLIENT_PROTOCOL_41 | CLIENT_CONNECT_WITH_DB
  4697. "\x00" // server language
  4698. "\x02\x00" // server status
  4699. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" // filler
  4700. "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d" // scramble buffer2 (for auth, 4.1+)
  4701. ;
  4702. const int INTERACTIVE_TIMEOUT = 900;
  4703. NetInputBuffer_c tIn ( iSock );
  4704. NetOutputBuffer_c tOut ( iSock );
  4705. sHandshake[0] = sizeof(sHandshake)-5;
  4706. if ( sphSockSend ( iSock, sHandshake, sizeof(sHandshake)-1 )!=sizeof(sHandshake)-1 )
  4707. {
  4708. sphWarning ( "failed to send server version (client=%s)", sClientIP );
  4709. return;
  4710. }
  4711. bool bAuthed = false;
  4712. BYTE uPacketID = 1;
  4713. CSphQueryResultMeta tLastMeta;
  4714. tLastMeta.m_iQueryTime = 0;
  4715. tLastMeta.m_iCpuTime = 0;
  4716. tLastMeta.m_iMatches = 0;
  4717. tLastMeta.m_iTotalMatches = 0;
  4718. for ( ;; )
  4719. {
  4720. // send the packet formed on the previous cycle
  4721. if ( !tOut.Flush() )
  4722. break;
  4723. // get next packet
  4724. if ( !tIn.ReadFrom ( 4, INTERACTIVE_TIMEOUT ) )
  4725. break;
  4726. DWORD uPacketHeader = tIn.GetLSBDword ();
  4727. int iPacketLen = ( uPacketHeader & 0xffffffUL );
  4728. if ( !tIn.ReadFrom ( iPacketLen, INTERACTIVE_TIMEOUT ) )
  4729. break;
  4730. // handle it!
  4731. uPacketID = 1 + BYTE(uPacketHeader>>24); // client will expect this id
  4732. char sOK[] = "\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
  4733. sOK[3] = uPacketID;
  4734. // handle auth packet
  4735. if ( !bAuthed )
  4736. {
  4737. bAuthed = true;
  4738. tOut.SendBytes ( sOK, sizeof(sOK)-1 );
  4739. continue;
  4740. }
  4741. // handle query packet
  4742. tIn.GetByte (); // skip command
  4743. CSphString sQuery = tIn.GetRawString ( iPacketLen-1 );
  4744. // parse SQL query
  4745. CSphString sError;
  4746. SearchHandler_c tHandler ( 1 );
  4747. SqlStmt_e eStmt = ParseSqlQuery ( sQuery, tHandler.m_dQueries[0], sError );
  4748. // handle SQL query
  4749. if ( eStmt==STMT_PARSE_ERROR )
  4750. {
  4751. SendMysqlErrorPacket ( tOut, uPacketID, sError.cstr() );
  4752. } else if ( eStmt==STMT_SELECT )
  4753. {
  4754. CheckQuery ( tHandler.m_dQueries[0], sError );
  4755. if ( !sError.IsEmpty() )
  4756. {
  4757. SendMysqlErrorPacket ( tOut, uPacketID, sError.cstr() );
  4758. continue;
  4759. }
  4760. // actual searching
  4761. tHandler.RunQueries ();
  4762. AggrResult_t * pRes = &tHandler.m_dResults[0];
  4763. if ( !pRes->m_iSuccesses )
  4764. {
  4765. SendMysqlErrorPacket ( tOut, uPacketID, pRes->m_sError.cstr() );
  4766. continue;
  4767. }
  4768. // save meta for SHOW META
  4769. tLastMeta = *pRes;
  4770. tLastMeta.m_iMatches = pRes->m_dMatches.GetLength();
  4771. // result set header packet
  4772. tOut.SendLSBDword ( ((uPacketID++)<<24) + 2 );
  4773. tOut.SendByte ( BYTE ( 2+pRes->m_tSchema.GetAttrsCount() ) ); // field count (id+weight+attrs)
  4774. tOut.SendByte ( 0 ); // extra
  4775. // field packets
  4776. SendMysqlFieldPacket ( tOut, uPacketID++, "id", MYSQL_COL_DECIMAL );
  4777. SendMysqlFieldPacket ( tOut, uPacketID++, "weight", MYSQL_COL_DECIMAL );
  4778. for ( int i=0; i<pRes->m_tSchema.GetAttrsCount(); i++ )
  4779. {
  4780. const CSphColumnInfo & tCol = pRes->m_tSchema.GetAttr(i);
  4781. MysqlColumnType_e eType = ( tCol.m_eAttrType==SPH_ATTR_INTEGER || tCol.m_eAttrType==SPH_ATTR_TIMESTAMP || tCol.m_eAttrType==SPH_ATTR_BOOL || tCol.m_eAttrType==SPH_ATTR_BIGINT )
  4782. ? MYSQL_COL_DECIMAL
  4783. : MYSQL_COL_STRING;
  4784. SendMysqlFieldPacket ( tOut, uPacketID++, tCol.m_sName.cstr(), eType );
  4785. }
  4786. // eof packet
  4787. BYTE iWarns = ( !pRes->m_sWarning.IsEmpty() ) ? 1 : 0;
  4788. SendMysqlEofPacket ( tOut, uPacketID++, iWarns );
  4789. // rows
  4790. char sRowBuffer[4096];
  4791. const char * sRowMax = sRowBuffer + sizeof(sRowBuffer);
  4792. for ( int iMatch = pRes->m_iOffset; iMatch < pRes->m_iOffset + pRes->m_iCount; iMatch++ )
  4793. {
  4794. const CSphMatch & tMatch = pRes->m_dMatches [ iMatch ];
  4795. char * p = sRowBuffer;
  4796. int iLen;
  4797. iLen = snprintf ( p+1, sRowMax-p, DOCID_FMT, tMatch.m_iDocID ); p[0] = BYTE(iLen); p += 1+iLen;
  4798. iLen = snprintf ( p+1, sRowMax-p, "%u", tMatch.m_iWeight ); p[0] = BYTE(iLen); p += 1+iLen;
  4799. const CSphSchema & tSchema = pRes->m_tSchema;
  4800. for ( int i=0; i<tSchema.GetAttrsCount(); i++ )
  4801. {
  4802. CSphAttrLocator tLoc = tSchema.GetAttr(i).m_tLocator;
  4803. DWORD eAttrType = tSchema.GetAttr(i).m_eAttrType;
  4804. switch ( eAttrType )
  4805. {
  4806. case SPH_ATTR_INTEGER:
  4807. case SPH_ATTR_TIMESTAMP:
  4808. case SPH_ATTR_BOOL:
  4809. case SPH_ATTR_BIGINT:
  4810. if ( eAttrType==SPH_ATTR_BIGINT )
  4811. iLen = snprintf ( p+1, sRowMax-p, "%"PRIu64, tMatch.GetAttr(tLoc) );
  4812. else
  4813. iLen = snprintf ( p+1, sRowMax-p, "%u", (DWORD)tMatch.GetAttr(tLoc) );
  4814. p[0] = BYTE(iLen);
  4815. p += 1+iLen;
  4816. break;
  4817. case SPH_ATTR_FLOAT:
  4818. iLen = snprintf ( p+1, sRowMax-p, "%f", tMatch.GetAttrFloat(tLoc) );
  4819. p[0] = BYTE(iLen);
  4820. p += 1+iLen;
  4821. break;
  4822. case SPH_ATTR_INTEGER | SPH_ATTR_MULTI:
  4823. {
  4824. BYTE * pLen = (BYTE*) p;
  4825. p += 4; // marker + 3-byte len
  4826. const DWORD * pValues = tMatch.GetAttrMVA ( tLoc, pRes->m_pMva );
  4827. if ( pValues )
  4828. {
  4829. DWORD nValues = *pValues++;
  4830. while ( nValues )
  4831. {
  4832. p += snprintf ( p, sRowMax-p, "%u", *pValues++ );
  4833. if ( --nValues )
  4834. *p++ = ',';
  4835. }
  4836. }
  4837. iLen = (BYTE*)p - pLen - 4;
  4838. pLen[0] = 253; // 3-byte
  4839. pLen[1] = BYTE(iLen&0xff);
  4840. pLen[2] = BYTE((iLen>>8)&0xff);
  4841. pLen[3] = BYTE((iLen>>16)&0xff);
  4842. break;
  4843. }
  4844. case SPH_ATTR_STRING:
  4845. {
  4846. const BYTE * pStrings = pRes->m_dTag2Pools [ tMatch.m_iTag ].m_pStrings;
  4847. // get that string
  4848. const BYTE * pStr;
  4849. int iLen = 0;
  4850. DWORD uOffset = (DWORD) tMatch.GetAttr ( tLoc );
  4851. if ( uOffset )
  4852. iLen = sphUnpackStr ( pStrings+uOffset, &pStr );
  4853. // send length
  4854. BYTE * pLen = (BYTE*)p;
  4855. iLen = Min ( iLen, sRowMax-p-3 ); // clamp it, buffer size is limited
  4856. if ( iLen<251 )
  4857. {
  4858. pLen[0] = BYTE(iLen);
  4859. p++;
  4860. } else
  4861. {
  4862. assert ( iLen<=0xffff );
  4863. pLen[0] = 252;
  4864. pLen[1] = BYTE(iLen&0xff);
  4865. pLen[2] = BYTE(iLen>>8);
  4866. p += 3;
  4867. }
  4868. // send string data
  4869. if ( iLen )
  4870. memcpy ( p, pStr, iLen );
  4871. p += iLen;
  4872. break;
  4873. }
  4874. default:
  4875. p[0] = 1;
  4876. p[1] = '-';
  4877. p += 2; break;
  4878. }
  4879. }
  4880. tOut.SendLSBDword ( ((uPacketID++)<<24) + ( p-sRowBuffer ) );
  4881. tOut.SendBytes ( sRowBuffer, p-sRowBuffer );
  4882. }
  4883. // eof packet
  4884. SendMysqlEofPacket ( tOut, uPacketID++, iWarns );
  4885. } else if ( eStmt==STMT_SHOW_WARNINGS )
  4886. {
  4887. if ( tLastMeta.m_sWarning.IsEmpty() )
  4888. {
  4889. tOut.SendBytes ( sOK, sizeof(sOK)-1 );
  4890. continue;
  4891. }
  4892. // result set header packet
  4893. tOut.SendLSBDword ( ((uPacketID++)<<24) + 2 );
  4894. tOut.SendByte ( 3 ); // field count (level+code+message)
  4895. tOut.SendByte ( 0 ); // extra
  4896. // field packets
  4897. SendMysqlFieldPacket ( tOut, uPacketID++, "Level", MYSQL_COL_STRING );
  4898. SendMysqlFieldPacket ( tOut, uPacketID++, "Code", MYSQL_COL_DECIMAL );
  4899. SendMysqlFieldPacket ( tOut, uPacketID++, "Message", MYSQL_COL_STRING );
  4900. SendMysqlEofPacket ( tOut, uPacketID++, 0 );
  4901. // row
  4902. char sRowBuffer[4096];
  4903. const char * sRowMax = sRowBuffer + sizeof(sRowBuffer);
  4904. int iLen;
  4905. char * p = sRowBuffer;
  4906. iLen = snprintf ( p+1, sRowMax-p, "warning" ); p[0] = BYTE(iLen); p += 1+iLen;
  4907. iLen = snprintf ( p+1, sRowMax-p, "%d", 1000 ); p[0] = BYTE(iLen); p += 1+iLen; // FIXME! proper code?
  4908. iLen = snprintf ( p+1, sRowMax-p, "%s", tLastMeta.m_sWarning.cstr() ); p[0] = BYTE(iLen); p += 1+iLen;
  4909. tOut.SendLSBDword ( ((uPacketID++)<<24) + ( p-sRowBuffer ) );
  4910. tOut.SendBytes ( sRowBuffer, p-sRowBuffer );
  4911. // cleanup
  4912. SendMysqlEofPacket ( tOut, uPacketID++, 0 );
  4913. } else if ( eStmt==STMT_SHOW_STATUS || eStmt==STMT_SHOW_META )
  4914. {
  4915. CSphVector<CSphString> dStatus;
  4916. if ( eStmt==STMT_SHOW_STATUS )
  4917. BuildStatus ( dStatus );
  4918. else
  4919. BuildMeta ( dStatus, tLastMeta );
  4920. // result set header packet
  4921. tOut.SendLSBDword ( ((uPacketID++)<<24) + 2 );
  4922. tOut.SendByte ( 2 ); // field count (level+code+message)
  4923. tOut.SendByte ( 0 ); // extra
  4924. // field packets
  4925. SendMysqlFieldPacket ( tOut, uPacketID++, "Variable_name", MYSQL_COL_STRING );
  4926. SendMysqlFieldPacket ( tOut, uPacketID++, "Value", MYSQL_COL_STRING );
  4927. SendMysqlEofPacket ( tOut, uPacketID++, 0 );
  4928. // send rows
  4929. char sRowBuffer[4096];
  4930. const char * sRowMax = sRowBuffer + sizeof(sRowBuffer);
  4931. for ( int iRow=0; iRow<dStatus.GetLength(); iRow+=2 )
  4932. {
  4933. int iLen;
  4934. char * p = sRowBuffer;
  4935. iLen = strlen ( dStatus[iRow+0].cstr() ); strncpy ( p+1, dStatus[iRow+0].cstr(), sRowMax-p-1 ); p[0] = BYTE(iLen); p += 1+iLen;
  4936. iLen = strlen ( dStatus[iRow+1].cstr() ); strncpy ( p+1, dStatus[iRow+1].cstr(), sRowMax-p-1 ); p[0] = BYTE(iLen); p += 1+iLen;
  4937. tOut.SendLSBDword ( ((uPacketID++)<<24) + ( p-sRowBuffer ) );
  4938. tOut.SendBytes ( sRowBuffer, p-sRowBuffer );
  4939. }
  4940. // cleanup
  4941. SendMysqlEofPacket ( tOut, uPacketID++, 0 );
  4942. } else
  4943. {
  4944. sError.SetSprintf ( "internal error: unhandled statement type (value=%d)", eStmt );
  4945. SendMysqlErrorPacket ( tOut, uPacketID, sError.cstr() );
  4946. }
  4947. }
  4948. SafeClose ( iPipeFD );
  4949. }
  4950. //////////////////////////////////////////////////////////////////////////
  4951. // HANDLE-BY-LISTENER
  4952. //////////////////////////////////////////////////////////////////////////
  4953. void HandleClient ( ProtocolType_e eProto, int iSock, const char * sClientIP, int iPipeFD )
  4954. {
  4955. switch ( eProto )
  4956. {
  4957. case PROTO_SPHINX: HandleClientSphinx ( iSock, sClientIP, iPipeFD ); break;
  4958. case PROTO_MYSQL41: HandleClientMySQL ( iSock, sClientIP, iPipeFD ); break;
  4959. }
  4960. }
  4961. /////////////////////////////////////////////////////////////////////////////
  4962. // INDEX ROTATION
  4963. /////////////////////////////////////////////////////////////////////////////
  4964. bool TryRename ( const char * sIndex, const char * sPrefix, const char * sFromPostfix, const char * sToPostfix, bool bFatal )
  4965. {
  4966. char sFrom [ SPH_MAX_FILENAME_LEN ];
  4967. char sTo [ SPH_MAX_FILENAME_LEN ];
  4968. snprintf ( sFrom, sizeof(sFrom), "%s%s", sPrefix, sFromPostfix );
  4969. snprintf ( sTo, sizeof(sTo), "%s%s", sPrefix, sToPostfix );
  4970. #if USE_WINDOWS
  4971. ::unlink ( sTo );
  4972. #endif
  4973. if ( rename ( sFrom, sTo ) )
  4974. {
  4975. if ( bFatal )
  4976. {
  4977. sphFatal ( "rotating index '%s': rollback rename '%s' to '%s' failed: %s",
  4978. sIndex, sFrom, sTo, strerror(errno) );
  4979. } else
  4980. {
  4981. sphWarning ( "rotating index '%s': rename '%s' to '%s' failed: %s",
  4982. sIndex, sFrom, sTo, strerror(errno) );
  4983. }
  4984. return false;
  4985. }
  4986. return true;
  4987. }
  4988. bool HasFiles ( const ServedIndex_t & tIndex, const char ** dExts )
  4989. {
  4990. char sFile [ SPH_MAX_FILENAME_LEN ];
  4991. const char * sPath = tIndex.m_sIndexPath.cstr();
  4992. for ( int i=0; i<EXT_COUNT; i++ )
  4993. {
  4994. snprintf ( sFile, sizeof(sFile), "%s%s", sPath, dExts [i] );
  4995. if ( !sphIsReadable ( sFile ) )
  4996. return false;
  4997. }
  4998. return true;
  4999. }
  5000. /// returns true if any version of the index (old or new one) has been preread
  5001. bool RotateIndexGreedy ( ServedIndex_t & tIndex, const char * sIndex )
  5002. {
  5003. char sFile [ SPH_MAX_FILENAME_LEN ];
  5004. const char * sPath = tIndex.m_sIndexPath.cstr();
  5005. for ( int i=0; i<EXT_COUNT; i++ )
  5006. {
  5007. snprintf ( sFile, sizeof(sFile), "%s%s", sPath, g_dNewExts[i] );
  5008. if ( !sphIsReadable ( sFile ) )
  5009. {
  5010. if ( i>0 )
  5011. {
  5012. if ( tIndex.m_bOnlyNew )
  5013. sphWarning ( "rotating index '%s': '%s' unreadable: %s; NOT SERVING", sIndex, sFile, strerror(errno) );
  5014. else
  5015. sphWarning ( "rotating index '%s': '%s' unreadable: %s; using old index", sIndex, sFile, strerror(errno) );
  5016. }
  5017. return false;
  5018. }
  5019. }
  5020. if ( !tIndex.m_bOnlyNew )
  5021. {
  5022. // rename current to old
  5023. for ( int i=0; i<EXT_COUNT; i++ )
  5024. {
  5025. if ( TryRename ( sIndex, sPath, g_dCurExts[i], g_dOldExts[i], false ) )
  5026. continue;
  5027. // rollback
  5028. for ( int j=0; j<i; j++ )
  5029. TryRename ( sIndex, sPath, g_dOldExts[j], g_dCurExts[j], true );
  5030. sphWarning ( "rotating index '%s': rename to .old failed; using old index", sIndex );
  5031. return false;
  5032. }
  5033. }
  5034. // rename new to current
  5035. for ( int i=0; i<EXT_COUNT; i++ )
  5036. {
  5037. if ( TryRename ( sIndex, sPath, g_dNewExts[i], g_dCurExts[i], false ) )
  5038. continue;
  5039. // rollback new ones we already renamed
  5040. for ( int j=0; j<i; j++ )
  5041. TryRename ( sIndex, sPath, g_dCurExts[j], g_dNewExts[j], true );
  5042. // rollback old ones
  5043. for ( int j=0; j<EXT_COUNT; j++ )
  5044. TryRename ( sIndex, sPath, g_dOldExts[j], g_dCurExts[j], true );
  5045. return false;
  5046. }
  5047. bool bPreread = false;
  5048. // try to use new index
  5049. CSphString sWarning;
  5050. ISphTokenizer * pTokenizer = tIndex.m_pIndex->LeakTokenizer ();
  5051. CSphDict * pDictionary = tIndex.m_pIndex->LeakDictionary ();
  5052. const CSphSchema * pNewSchema = tIndex.m_pIndex->Prealloc ( tIndex.m_bMlock, sWarning );
  5053. if ( !pNewSchema || !tIndex.m_pIndex->Preread() )
  5054. {
  5055. if ( tIndex.m_bOnlyNew )
  5056. {
  5057. sphWarning ( "rotating index '%s': .new preload failed: %s; NOT SERVING", sIndex, tIndex.m_pIndex->GetLastError().cstr() );
  5058. return false;
  5059. }
  5060. else
  5061. {
  5062. sphWarning ( "rotating index '%s': .new preload failed: %s", sIndex, tIndex.m_pIndex->GetLastError().cstr() );
  5063. // try to recover
  5064. for ( int j=0; j<EXT_COUNT; j++ )
  5065. {
  5066. TryRename ( sIndex, sPath, g_dCurExts[j], g_dNewExts[j], true );
  5067. TryRename ( sIndex, sPath, g_dOldExts[j], g_dCurExts[j], true );
  5068. }
  5069. pNewSchema = tIndex.m_pIndex->Prealloc ( tIndex.m_bMlock, sWarning );
  5070. if ( !pNewSchema || !tIndex.m_pIndex->Preread() )
  5071. {
  5072. sphWarning ( "rotating index '%s': .new preload failed; ROLLBACK FAILED; INDEX UNUSABLE", sIndex );
  5073. tIndex.m_bEnabled = false;
  5074. }
  5075. else
  5076. {
  5077. tIndex.m_bEnabled = true;
  5078. bPreread = true;
  5079. sphWarning ( "rotating index '%s': .new preload failed; using old index", sIndex );
  5080. if ( !sWarning.IsEmpty() )
  5081. sphWarning ( "rotating index '%s': %s", sIndex, sWarning.cstr() );
  5082. }
  5083. if ( !tIndex.m_pIndex->GetTokenizer () )
  5084. tIndex.m_pIndex->SetTokenizer ( pTokenizer );
  5085. else
  5086. SafeDelete ( pTokenizer );
  5087. if ( !tIndex.m_pIndex->GetDictionary () )
  5088. tIndex.m_pIndex->SetDictionary ( pDictionary );
  5089. else
  5090. SafeDelete ( pDictionary );
  5091. }
  5092. return bPreread;
  5093. }
  5094. else
  5095. {
  5096. bPreread = true;
  5097. if ( !sWarning.IsEmpty() )
  5098. sphWarning ( "rotating index '%s': %s", sIndex, sWarning.cstr() );
  5099. }
  5100. if ( !tIndex.m_pIndex->GetTokenizer () )
  5101. tIndex.m_pIndex->SetTokenizer ( pTokenizer );
  5102. else
  5103. SafeDelete ( pTokenizer );
  5104. if ( !tIndex.m_pIndex->GetDictionary () )
  5105. tIndex.m_pIndex->SetDictionary ( pDictionary );
  5106. else
  5107. SafeDelete ( pDictionary );
  5108. // unlink .old
  5109. if ( g_bUnlinkOld && !tIndex.m_bOnlyNew )
  5110. for ( int i=0; i<EXT_COUNT; i++ )
  5111. {
  5112. snprintf ( sFile, sizeof(sFile), "%s%s", sPath, g_dOldExts[i] );
  5113. if ( ::unlink ( sFile ) )
  5114. sphWarning ( "rotating index '%s': unable to unlink '%s': %s", sIndex, sFile, strerror(errno) );
  5115. }
  5116. // uff. all done
  5117. tIndex.m_pSchema = pNewSchema;
  5118. tIndex.m_bEnabled = true;
  5119. tIndex.m_bOnlyNew = false;
  5120. sphInfo ( "rotating index '%s': success", sIndex );
  5121. return bPreread;
  5122. }
  5123. /////////////////////////////////////////////////////////////////////////////
  5124. // MAIN LOOP
  5125. /////////////////////////////////////////////////////////////////////////////
  5126. #if USE_WINDOWS
  5127. int CreatePipe ( bool, int ) { return -1; }
  5128. int PipeAndFork ( bool, int ) { return -1; }
  5129. #else
  5130. // open new pipe to be able to receive notifications from children
  5131. // adds read-end fd to g_dPipes; returns write-end fd for child
  5132. int CreatePipe ( bool bFatal, int iHandler )
  5133. {
  5134. assert ( g_bHeadDaemon );
  5135. int dPipe[2] = { -1, -1 };
  5136. for ( ;; )
  5137. {
  5138. if ( pipe(dPipe) )
  5139. {
  5140. if ( bFatal )
  5141. sphFatal ( "pipe() failed (error=%s)", strerror(errno) );
  5142. else
  5143. sphWarning ( "pipe() failed (error=%s)", strerror(errno) );
  5144. break;
  5145. }
  5146. if ( fcntl ( dPipe[0], F_SETFL, O_NONBLOCK ) )
  5147. {
  5148. sphWarning ( "fcntl(O_NONBLOCK) on pipe failed (error=%s)", strerror(errno) );
  5149. SafeClose ( dPipe[0] );
  5150. SafeClose ( dPipe[1] );
  5151. break;
  5152. }
  5153. PipeInfo_t tAdd;
  5154. tAdd.m_iFD = dPipe[0];
  5155. tAdd.m_iHandler = iHandler;
  5156. g_dPipes.Add ( tAdd );
  5157. break;
  5158. }
  5159. return dPipe[1];
  5160. }
  5161. /// create new worker child
  5162. /// creates a pipe to it, forks, and does some post-fork work
  5163. //
  5164. /// in child, returns write-end pipe fd (might be -1!) and sets g_bHeadDaemon to false
  5165. /// in parent, returns -1 and leaves g_bHeadDaemon unaffected
  5166. int PipeAndFork ( bool bFatal, int iHandler )
  5167. {
  5168. int iChildPipe = CreatePipe ( bFatal, iHandler );
  5169. switch ( fork() )
  5170. {
  5171. // fork() failed
  5172. case -1:
  5173. sphFatal ( "fork() failed (reason: %s)", strerror(errno) );
  5174. // child process, handle client
  5175. case 0:
  5176. g_bHeadDaemon = false;
  5177. sphSetProcessInfo ( false );
  5178. ARRAY_FOREACH ( i, g_dPipes )
  5179. SafeClose ( g_dPipes[i].m_iFD );
  5180. break;
  5181. // parent process, continue accept()ing
  5182. default:
  5183. g_iChildren++;
  5184. SafeClose ( iChildPipe );
  5185. break;
  5186. }
  5187. return iChildPipe;
  5188. }
  5189. #endif // !USE_WINDOWS
  5190. /// check and report if there were any leaks since last call
  5191. void CheckLeaks ()
  5192. {
  5193. #if SPH_DEBUG_LEAKS
  5194. static int iHeadAllocs = sphAllocsCount ();
  5195. static int iHeadCheckpoint = sphAllocsLastID ();
  5196. if ( iHeadAllocs!=sphAllocsCount() )
  5197. {
  5198. lseek ( g_iLogFile, 0, SEEK_END );
  5199. sphAllocsDump ( g_iLogFile, iHeadCheckpoint );
  5200. iHeadAllocs = sphAllocsCount ();
  5201. iHeadCheckpoint = sphAllocsLastID ();
  5202. }
  5203. #endif
  5204. }
  5205. bool CheckIndex ( const CSphIndex * pIndex, CSphString & sError )
  5206. {
  5207. const CSphIndexSettings & tSettings = pIndex->GetSettings ();
  5208. if ( ( tSettings.m_iMinPrefixLen>0 || tSettings.m_iMinInfixLen>0 ) && !pIndex->m_bEnableStar )
  5209. {
  5210. CSphDict * pDict = pIndex->GetDictionary ();
  5211. assert ( pDict );
  5212. if ( pDict->GetSettings ().HasMorphology () )
  5213. {
  5214. sError = "infixes and morphology are enabled, enable_star=0";
  5215. return false;
  5216. }
  5217. }
  5218. return true;
  5219. }
  5220. void SeamlessTryToForkPrereader ()
  5221. {
  5222. // next in line
  5223. const char * sPrereading = g_dRotating.Pop ();
  5224. if ( !sPrereading || !g_hIndexes(sPrereading) )
  5225. {
  5226. sphWarning ( "INTERNAL ERROR: preread attempt on unknown index '%s'", sPrereading ? sPrereading : "(NULL)" );
  5227. return;
  5228. }
  5229. const ServedIndex_t & tServed = g_hIndexes[sPrereading];
  5230. // alloc buffer index (once per run)
  5231. if ( !g_pPrereading )
  5232. g_pPrereading = sphCreateIndexPhrase ( NULL ); // FIXME! check if it's ok
  5233. g_pPrereading->m_bEnableStar = tServed.m_bStar;
  5234. g_pPrereading->m_bExpandKeywords = tServed.m_bExpand;
  5235. g_pPrereading->SetPreopen ( tServed.m_bPreopen || g_bPreopenIndexes );
  5236. g_pPrereading->SetWordlistPreload ( !tServed.m_bOnDiskDict && !g_bOnDiskDicts );
  5237. // rebase buffer index
  5238. char sNewPath [ SPH_MAX_FILENAME_LEN ];
  5239. snprintf ( sNewPath, sizeof(sNewPath), "%s.new", tServed.m_sIndexPath.cstr() );
  5240. g_pPrereading->SetBase ( sNewPath );
  5241. // prealloc enough RAM and lock new index
  5242. CSphString sWarn, sError;
  5243. if ( !g_pPrereading->Prealloc ( tServed.m_bMlock, sWarn ) )
  5244. {
  5245. sphWarning ( "rotating index '%s': prealloc: %s; using old index", sPrereading, g_pPrereading->GetLastError().cstr() );
  5246. return;
  5247. }
  5248. if ( !g_pPrereading->Lock() )
  5249. {
  5250. sphWarning ( "rotating index '%s': lock: %s; using old index", sPrereading, g_pPrereading->GetLastError().cstr() );
  5251. g_pPrereading->Dealloc ();
  5252. return;
  5253. }
  5254. if ( tServed.m_bOnlyNew && g_pCfg && g_pCfg->m_tConf.Exists ( "index" ) && g_pCfg->m_tConf["index"].Exists ( sPrereading ) )
  5255. if ( !sphFixupIndexSettings ( g_pPrereading, g_pCfg->m_tConf["index"][sPrereading], sError ) )
  5256. {
  5257. sphWarning ( "rotating index '%s': fixup: %s; using old index", sPrereading, sError.cstr() );
  5258. return;
  5259. }
  5260. if ( !CheckIndex ( g_pPrereading, sError ) )
  5261. {
  5262. sphWarning ( "rotating index '%s': check: %s; using old index", sPrereading, sError.cstr() );
  5263. return;
  5264. }
  5265. // fork async reader
  5266. g_sPrereading = sPrereading;
  5267. int iPipeFD = PipeAndFork ( true, SPH_PIPE_PREREAD );
  5268. // in parent, wait for prereader process to finish
  5269. if ( g_bHeadDaemon )
  5270. return;
  5271. // in child, do preread
  5272. bool bRes = g_pPrereading->Preread ();
  5273. if ( !bRes )
  5274. sphWarning ( "rotating index '%s': preread failed: %s; using old index", g_sPrereading, g_pPrereading->GetLastError().cstr() );
  5275. // report and exit
  5276. DWORD uTmp = SPH_PIPE_PREREAD;
  5277. ::write ( iPipeFD, &uTmp, sizeof(DWORD) );
  5278. uTmp = bRes;
  5279. ::write ( iPipeFD, &uTmp, sizeof(DWORD) );
  5280. ::close ( iPipeFD );
  5281. exit ( 0 );
  5282. }
  5283. void SeamlessForkPrereader ()
  5284. {
  5285. // sanity checks
  5286. if ( !g_bDoRotate )
  5287. {
  5288. sphWarning ( "INTERNAL ERROR: preread attempt not in rotate state" );
  5289. return;
  5290. }
  5291. if ( g_sPrereading )
  5292. {
  5293. sphWarning ( "INTERNAL ERROR: preread attempt before previous completion" );
  5294. return;
  5295. }
  5296. // try candidates one by one
  5297. while ( g_dRotating.GetLength() && !g_sPrereading )
  5298. SeamlessTryToForkPrereader ();
  5299. // if there's no more candidates, and nothing in the works, we're done
  5300. if ( !g_sPrereading && !g_dRotating.GetLength() )
  5301. {
  5302. g_bDoRotate = false;
  5303. sphInfo ( "rotating finished" );
  5304. }
  5305. }
  5306. /// simple wrapper to simplify reading from pipes
  5307. struct PipeReader_t
  5308. {
  5309. PipeReader_t ( int iFD )
  5310. : m_iFD ( iFD )
  5311. , m_bError ( false )
  5312. {
  5313. #if !USE_WINDOWS
  5314. if ( fcntl ( iFD, F_SETFL, 0 )<0 )
  5315. sphWarning ( "fcntl(0) on pipe failed (error=%s)", strerror(errno) );
  5316. #endif
  5317. }
  5318. ~PipeReader_t ()
  5319. {
  5320. SafeClose ( m_iFD );
  5321. }
  5322. int GetFD () const
  5323. {
  5324. return m_iFD;
  5325. }
  5326. bool IsError () const
  5327. {
  5328. return m_bError;
  5329. }
  5330. int GetInt ()
  5331. {
  5332. int iTmp;
  5333. if ( !GetBytes ( &iTmp, sizeof(iTmp) ) )
  5334. iTmp = 0;
  5335. return iTmp;
  5336. }
  5337. CSphString GetString ()
  5338. {
  5339. int iLen = GetInt ();
  5340. CSphString sRes;
  5341. sRes.Reserve ( iLen );
  5342. if ( !GetBytes ( const_cast<char*>(sRes.cstr()), iLen ) )
  5343. sRes = "";
  5344. return sRes;
  5345. }
  5346. protected:
  5347. bool GetBytes ( void * pBuf, int iCount )
  5348. {
  5349. if ( m_bError )
  5350. return false;
  5351. if ( m_iFD<0 )
  5352. {
  5353. m_bError = true;
  5354. sphWarning ( "invalid pipe fd" );
  5355. return false;
  5356. }
  5357. for ( ;; )
  5358. {
  5359. int iRes = ::read ( m_iFD, pBuf, iCount );
  5360. if ( iRes<0 && errno==EINTR )
  5361. continue;
  5362. if ( iRes!=iCount )
  5363. {
  5364. m_bError = true;
  5365. sphWarning ( "pipe read failed (exp=%d, res=%d, error=%s)",
  5366. iCount, iRes, iRes>0 ? "(none)" : strerror(errno) );
  5367. return false;
  5368. }
  5369. return true;
  5370. }
  5371. }
  5372. protected:
  5373. int m_iFD;
  5374. bool m_bError;
  5375. };
  5376. /// handle pipe notifications from attribute updating
  5377. void HandlePipeUpdate ( PipeReader_t & tPipe, bool bFailure )
  5378. {
  5379. if ( bFailure )
  5380. return; // silently ignore errors
  5381. ++g_iUpdateTag;
  5382. int iUpdIndexes = tPipe.GetInt ();
  5383. for ( int i=0; i<iUpdIndexes; i++ )
  5384. {
  5385. // index name and status must follow
  5386. CSphString sIndex = tPipe.GetString ();
  5387. DWORD uStatus = tPipe.GetInt ();
  5388. if ( tPipe.IsError() )
  5389. break;
  5390. ServedIndex_t * pServed = g_hIndexes(sIndex);
  5391. if ( pServed )
  5392. {
  5393. pServed->m_iUpdateTag = g_iUpdateTag;
  5394. pServed->m_pIndex->m_uAttrsStatus |= uStatus;
  5395. } else
  5396. sphWarning ( "INTERNAL ERROR: unknown index '%s' in HandlePipeUpdate()", sIndex.cstr() );
  5397. }
  5398. }
  5399. /// handle pipe notifications from prereading
  5400. void HandlePipePreread ( PipeReader_t & tPipe, bool bFailure )
  5401. {
  5402. if ( bFailure )
  5403. {
  5404. // clean up previous one and launch next one
  5405. g_sPrereading = NULL;
  5406. // in any case, buffer index should now be deallocated
  5407. g_pPrereading->Dealloc ();
  5408. g_pPrereading->Unlock ();
  5409. // work next one
  5410. SeamlessForkPrereader ();
  5411. return;
  5412. }
  5413. assert ( g_bDoRotate && g_bSeamlessRotate && g_sPrereading );
  5414. // whatever the outcome, we will be done with this one
  5415. const char * sPrereading = g_sPrereading;
  5416. g_sPrereading = NULL;
  5417. // notice that this will block!
  5418. int iRes = tPipe.GetInt();
  5419. if ( !tPipe.IsError() && iRes )
  5420. {
  5421. // if preread was succesful, exchange served index and prereader buffer index
  5422. ServedIndex_t & tServed = g_hIndexes[sPrereading];
  5423. CSphIndex * pOld = tServed.m_pIndex;
  5424. CSphIndex * pNew = g_pPrereading;
  5425. char sOld [ SPH_MAX_FILENAME_LEN ];
  5426. snprintf ( sOld, sizeof(sOld), "%s.old", tServed.m_sIndexPath.cstr() );
  5427. if ( !tServed.m_bOnlyNew && !pOld->Rename ( sOld ) )
  5428. {
  5429. // FIXME! rollback inside Rename() call potentially fail
  5430. sphWarning ( "rotating index '%s': cur to old rename failed: %s", sPrereading, pOld->GetLastError().cstr() );
  5431. } else
  5432. {
  5433. // FIXME! at this point there's no cur lock file; ie. potential race
  5434. if ( !pNew->Rename ( tServed.m_sIndexPath.cstr() ) )
  5435. {
  5436. sphWarning ( "rotating index '%s': new to cur rename failed: %s", sPrereading, pNew->GetLastError().cstr() );
  5437. if ( !tServed.m_bOnlyNew && !pOld->Rename ( tServed.m_sIndexPath.cstr() ) )
  5438. {
  5439. sphWarning ( "rotating index '%s': old to cur rename failed: %s; INDEX UNUSABLE", sPrereading, pOld->GetLastError().cstr() );
  5440. tServed.m_bEnabled = false;
  5441. }
  5442. } else
  5443. {
  5444. // all went fine; swap them
  5445. if ( !g_pPrereading->GetTokenizer () )
  5446. g_pPrereading->SetTokenizer ( tServed.m_pIndex->LeakTokenizer () );
  5447. if ( !g_pPrereading->GetDictionary () )
  5448. g_pPrereading->SetDictionary ( tServed.m_pIndex->LeakDictionary () );
  5449. Swap ( tServed.m_pIndex, g_pPrereading );
  5450. tServed.m_pSchema = tServed.m_pIndex->GetSchema ();
  5451. tServed.m_bEnabled = true;
  5452. // unlink .old
  5453. if ( g_bUnlinkOld && !tServed.m_bOnlyNew )
  5454. {
  5455. char sFile [ SPH_MAX_FILENAME_LEN ];
  5456. for ( int i=0; i<EXT_COUNT; i++ )
  5457. {
  5458. snprintf ( sFile, sizeof(sFile), "%s%s", sOld, g_dCurExts[i] );
  5459. if ( ::unlink ( sFile ) )
  5460. sphWarning ( "rotating index '%s': unable to unlink '%s': %s", sPrereading, sFile, strerror(errno) );
  5461. }
  5462. }
  5463. tServed.m_bOnlyNew = false;
  5464. sphInfo ( "rotating index '%s': success", sPrereading );
  5465. }
  5466. }
  5467. } else
  5468. {
  5469. if ( tPipe.IsError() )
  5470. sphWarning ( "rotating index '%s': pipe read failed" );
  5471. else
  5472. sphWarning ( "rotating index '%s': preread failure reported" );
  5473. }
  5474. // in any case, buffer index should now be deallocated
  5475. g_pPrereading->Dealloc ();
  5476. g_pPrereading->Unlock ();
  5477. // work next one
  5478. SeamlessForkPrereader ();
  5479. }
  5480. /// handle pipe notifications from attribute saving
  5481. void HandlePipeSave ( PipeReader_t & tPipe, bool bFailure )
  5482. {
  5483. // in any case, we're no more flushing
  5484. g_bFlushing = false;
  5485. // silently ignore errors
  5486. if ( bFailure )
  5487. return;
  5488. // handle response
  5489. int iSavedIndexes = tPipe.GetInt ();
  5490. for ( int i=0; i<iSavedIndexes; i++ )
  5491. {
  5492. // index name must follow
  5493. CSphString sIndex = tPipe.GetString ();
  5494. if ( tPipe.IsError() )
  5495. break;
  5496. ServedIndex_t * pServed = g_hIndexes(sIndex);
  5497. if ( pServed )
  5498. {
  5499. if ( pServed->m_iUpdateTag<=g_iFlushTag )
  5500. pServed->m_pIndex->m_uAttrsStatus = 0;
  5501. } else
  5502. {
  5503. sphWarning ( "INTERNAL ERROR: unknown index '%s' in HandlePipeSave()", sIndex.cstr() );
  5504. }
  5505. }
  5506. }
  5507. /// check if there are any notifications from the children and handle them
  5508. void CheckPipes ()
  5509. {
  5510. ARRAY_FOREACH ( i, g_dPipes )
  5511. {
  5512. // try to get status code
  5513. DWORD uStatus;
  5514. int iRes = ::read ( g_dPipes[i].m_iFD, &uStatus, sizeof(DWORD) );
  5515. // no data yet?
  5516. if ( iRes==-1 && errno==EAGAIN )
  5517. continue;
  5518. // either if there's eof, or error, or valid data - this pipe is over
  5519. PipeReader_t tPipe ( g_dPipes[i].m_iFD );
  5520. int iHandler = g_dPipes[i].m_iHandler;
  5521. g_dPipes.Remove ( i-- );
  5522. // check for eof/error
  5523. bool bFailure = false;
  5524. if ( iRes!=sizeof(DWORD) )
  5525. {
  5526. bFailure = true;
  5527. if ( iHandler<0 )
  5528. continue; // no handler; we're not expecting anything
  5529. if ( iRes!=0 || iHandler>=0 )
  5530. sphWarning ( "pipe status read failed (handler=%d)", iHandler );
  5531. }
  5532. // check for handler/status mismatch
  5533. if ( !bFailure && ( iHandler>=0 && (int)uStatus!=iHandler ) )
  5534. {
  5535. bFailure = true;
  5536. sphWarning ( "INTERNAL ERROR: pipe status mismatch (handler=%d, status=%d)", iHandler, uStatus );
  5537. }
  5538. // check for handler promotion (ie: we did not expect anything particular, but something happened anyway)
  5539. if ( !bFailure && iHandler<0 )
  5540. iHandler = (int)uStatus;
  5541. // run the proper handler
  5542. switch ( iHandler )
  5543. {
  5544. case SPH_PIPE_UPDATED_ATTRS: HandlePipeUpdate ( tPipe, bFailure ); break;
  5545. case SPH_PIPE_SAVED_ATTRS: HandlePipeSave ( tPipe, bFailure ); break;
  5546. case SPH_PIPE_PREREAD: HandlePipePreread ( tPipe, bFailure ); break;
  5547. default: if ( !bFailure ) sphWarning ( "INTERNAL ERROR: unknown pipe handler (handler=%d, status=%d)", iHandler, uStatus ); break;
  5548. }
  5549. }
  5550. }
  5551. void ConfigureIndex ( ServedIndex_t & tIdx, const CSphConfigSection & hIndex )
  5552. {
  5553. tIdx.m_bMlock = ( hIndex.GetInt ( "mlock", 0 )!=0 ) && !g_bOptConsole;
  5554. tIdx.m_bStar = ( hIndex.GetInt ( "enable_star", 0 )!=0 );
  5555. tIdx.m_bExpand = ( hIndex.GetInt ( "expand_keywords", 0 )!=0 );
  5556. tIdx.m_bPreopen = ( hIndex.GetInt ( "preopen", 0 )!=0 );
  5557. tIdx.m_bOnDiskDict = ( hIndex.GetInt ( "ondisk_dict", 0 )!=0 );
  5558. }
  5559. bool PrereadNewIndex ( ServedIndex_t & tIdx, const CSphConfigSection & hIndex, const char * szIndexName )
  5560. {
  5561. CSphString sWarning;
  5562. tIdx.m_pSchema = tIdx.m_pIndex->Prealloc ( tIdx.m_bMlock, sWarning );
  5563. if ( !tIdx.m_pSchema || !tIdx.m_pIndex->Preread() )
  5564. {
  5565. sphWarning ( "index '%s': preload: %s; NOT SERVING", szIndexName, tIdx.m_pIndex->GetLastError().cstr() );
  5566. return false;
  5567. }
  5568. if ( !sWarning.IsEmpty() )
  5569. sphWarning ( "index '%s': %s", szIndexName, sWarning.cstr() );
  5570. CSphString sError;
  5571. if ( !sphFixupIndexSettings ( tIdx.m_pIndex, hIndex, sError ) )
  5572. {
  5573. sphWarning ( "index '%s': %s - NOT SERVING", szIndexName, sError.cstr() );
  5574. return false;
  5575. }
  5576. // try to lock it
  5577. if ( !g_bOptConsole && !tIdx.m_pIndex->Lock() )
  5578. {
  5579. sphWarning ( "index '%s': lock: %s; NOT SERVING", szIndexName, tIdx.m_pIndex->GetLastError().cstr() );
  5580. return false;
  5581. }
  5582. return true;
  5583. }
  5584. bool ConfigureAgent ( Agent_t & tAgent, const CSphVariant * pAgent, const char * szIndexName, bool bBlackhole )
  5585. {
  5586. // extract host name or path
  5587. const char * p = pAgent->cstr();
  5588. while ( sphIsAlpha(*p) || *p=='.' || *p=='-' || *p=='/' ) p++;
  5589. if ( p==pAgent->cstr() )
  5590. {
  5591. sphWarning ( "index '%s': agent '%s': host name or path expected - SKIPPING AGENT",
  5592. szIndexName, pAgent->cstr() );
  5593. return false;
  5594. }
  5595. if ( *p++!=':' )
  5596. {
  5597. sphWarning ( "index '%s': agent '%s': colon expected near '%s' - SKIPPING AGENT",
  5598. szIndexName, pAgent->cstr(), p );
  5599. return false;
  5600. }
  5601. CSphString sSub = pAgent->SubString ( 0, p-1-pAgent->cstr() );
  5602. if ( sSub.cstr()[0] == '/' )
  5603. {
  5604. #if USE_WINDOWS
  5605. sphWarning ( "index '%s': agent '%s': UNIX sockets are not supported on Windows - SKIPPING AGENT",
  5606. szIndexName, pAgent->cstr() );
  5607. return false;
  5608. #else
  5609. if ( strlen ( sSub.cstr() ) + 1 > sizeof(((struct sockaddr_un *)0)->sun_path) )
  5610. {
  5611. sphWarning ( "index '%s': agent '%s': UNIX socket path is too long - SKIPPING AGENT",
  5612. szIndexName, pAgent->cstr() );
  5613. return false;
  5614. }
  5615. tAgent.m_iFamily = AF_UNIX;
  5616. tAgent.m_sPath = sSub;
  5617. p--;
  5618. #endif
  5619. }
  5620. else
  5621. {
  5622. tAgent.m_iFamily = AF_INET;
  5623. tAgent.m_sHost = sSub;
  5624. // extract port
  5625. if ( !isdigit(*p) )
  5626. {
  5627. sphWarning ( "index '%s': agent '%s': port number expected near '%s' - SKIPPING AGENT",
  5628. szIndexName, pAgent->cstr(), p );
  5629. return false;
  5630. }
  5631. tAgent.m_iPort = atoi(p);
  5632. if ( !IsPortInRange(tAgent.m_iPort) )
  5633. {
  5634. sphWarning ( "index '%s': agent '%s': invalid port number near '%s' - SKIPPING AGENT",
  5635. szIndexName, pAgent->cstr(), p );
  5636. return false;
  5637. }
  5638. while ( isdigit(*p) ) p++;
  5639. }
  5640. // extract index list
  5641. if ( *p++!=':' )
  5642. {
  5643. sphWarning ( "index '%s': agent '%s': colon expected near '%s' - SKIPPING AGENT",
  5644. szIndexName, pAgent->cstr(), p );
  5645. return false;
  5646. }
  5647. while ( isspace(*p) )
  5648. p++;
  5649. const char * sIndexList = p;
  5650. while ( sphIsAlpha(*p) || isspace(*p) || *p==',' )
  5651. p++;
  5652. if ( *p )
  5653. {
  5654. sphWarning ( "index '%s': agent '%s': index list expected near '%s' - SKIPPING AGENT",
  5655. szIndexName, pAgent->cstr(), p );
  5656. return false;
  5657. }
  5658. tAgent.m_sIndexes = sIndexList;
  5659. // lookup address (if needed)
  5660. if ( tAgent.m_iFamily == AF_INET )
  5661. {
  5662. tAgent.m_uAddr = sphGetAddress ( tAgent.m_sHost.cstr() );
  5663. if ( tAgent.m_uAddr == 0 )
  5664. {
  5665. sphWarning ( "index '%s': agent '%s': failed to lookup host name '%s' (error=%s) - SKIPPING AGENT",
  5666. szIndexName, pAgent->cstr(), tAgent.m_sHost.cstr(), sphSockError() );
  5667. return false;
  5668. }
  5669. }
  5670. tAgent.m_bBlackhole = bBlackhole;
  5671. return true;
  5672. }
  5673. ESphAddIndex AddIndex ( const char * szIndexName, const CSphConfigSection & hIndex )
  5674. {
  5675. if ( hIndex("type") && hIndex["type"]=="distributed" )
  5676. {
  5677. ///////////////////////////////
  5678. // configure distributed index
  5679. ///////////////////////////////
  5680. DistributedIndex_t tIdx;
  5681. // add local agents
  5682. for ( CSphVariant * pLocal = hIndex("local"); pLocal; pLocal = pLocal->m_pNext )
  5683. {
  5684. if ( !g_hIndexes ( pLocal->cstr() ) )
  5685. {
  5686. sphWarning ( "index '%s': no such local index '%s' - SKIPPING LOCAL INDEX",
  5687. szIndexName, pLocal->cstr() );
  5688. continue;
  5689. }
  5690. tIdx.m_dLocal.Add ( pLocal->cstr() );
  5691. }
  5692. // add remote agents
  5693. for ( CSphVariant * pAgent = hIndex("agent"); pAgent; pAgent = pAgent->m_pNext )
  5694. {
  5695. Agent_t tAgent;
  5696. if ( ConfigureAgent ( tAgent, pAgent, szIndexName, false ) )
  5697. tIdx.m_dAgents.Add ( tAgent );
  5698. }
  5699. for ( CSphVariant * pAgent = hIndex("agent_blackhole"); pAgent; pAgent = pAgent->m_pNext )
  5700. {
  5701. Agent_t tAgent;
  5702. if ( ConfigureAgent ( tAgent, pAgent, szIndexName, true ) )
  5703. tIdx.m_dAgents.Add ( tAgent );
  5704. }
  5705. // configure options
  5706. if ( hIndex("agent_connect_timeout") )
  5707. {
  5708. if ( hIndex["agent_connect_timeout"].intval()<=0 )
  5709. sphWarning ( "index '%s': connect_timeout must be positive, ignored", szIndexName );
  5710. else
  5711. tIdx.m_iAgentConnectTimeout = hIndex["agent_connect_timeout"].intval();
  5712. }
  5713. if ( hIndex("agent_query_timeout") )
  5714. {
  5715. if ( hIndex["agent_query_timeout"].intval()<=0 )
  5716. sphWarning ( "index '%s': query_timeout must be positive, ignored", szIndexName );
  5717. else
  5718. tIdx.m_iAgentQueryTimeout = hIndex["agent_query_timeout"].intval();
  5719. }
  5720. // finally, check and add distributed index to global table
  5721. if ( tIdx.m_dAgents.GetLength()==0 && tIdx.m_dLocal.GetLength()==0 )
  5722. {
  5723. sphWarning ( "index '%s': no valid local/remote indexes in distributed index - NOT SERVING",
  5724. szIndexName );
  5725. return ADD_ERROR;
  5726. }
  5727. else
  5728. {
  5729. if ( !g_hDistIndexes.Add ( tIdx, szIndexName ) )
  5730. {
  5731. sphWarning ( "index '%s': duplicate name in hash?! INTERNAL ERROR - NOT SERVING", szIndexName );
  5732. return ADD_ERROR;
  5733. }
  5734. }
  5735. return ADD_DISTR;
  5736. }
  5737. else
  5738. {
  5739. /////////////////////////
  5740. // configure local index
  5741. /////////////////////////
  5742. ServedIndex_t tIdx;
  5743. // check path
  5744. if ( !hIndex.Exists ( "path" ) )
  5745. {
  5746. sphWarning ( "index '%s': key 'path' not found' - NOT SERVING", szIndexName );
  5747. return ADD_ERROR;
  5748. }
  5749. // check name
  5750. if ( g_hIndexes.Exists ( szIndexName ) )
  5751. {
  5752. sphWarning ( "index '%s': duplicate name in hash?! INTERNAL ERROR - NOT SERVING", szIndexName );
  5753. return ADD_ERROR;
  5754. }
  5755. // configure memlocking, star
  5756. ConfigureIndex ( tIdx, hIndex );
  5757. // try to create index
  5758. CSphString sWarning;
  5759. tIdx.m_pIndex = sphCreateIndexPhrase ( hIndex["path"].cstr() );
  5760. tIdx.m_pIndex->m_bEnableStar = tIdx.m_bStar;
  5761. tIdx.m_pIndex->m_bExpandKeywords = tIdx.m_bExpand;
  5762. tIdx.m_pIndex->SetPreopen ( tIdx.m_bPreopen || g_bPreopenIndexes );
  5763. tIdx.m_pIndex->SetWordlistPreload ( !tIdx.m_bOnDiskDict && !g_bOnDiskDicts );
  5764. tIdx.m_bEnabled = false;
  5765. // done
  5766. tIdx.m_sIndexPath = hIndex["path"];
  5767. if ( !g_hIndexes.Add ( tIdx, szIndexName ) )
  5768. {
  5769. sphWarning ( "INTERNAL ERROR: index '%s': hash add failed - NOT SERVING", szIndexName );
  5770. return ADD_ERROR;
  5771. }
  5772. tIdx.Reset (); // so that the dtor wouln't delete everything
  5773. return ADD_LOCAL;
  5774. }
  5775. }
  5776. bool CheckConfigChanges ()
  5777. {
  5778. struct stat tStat;
  5779. memset ( &tStat, 0, sizeof ( tStat ) );
  5780. if ( stat ( g_sConfigFile.cstr (), &tStat ) < 0 )
  5781. memset ( &tStat, 0, sizeof ( tStat ) );
  5782. DWORD uCRC32 = 0;
  5783. sphCalcFileCRC32 ( g_sConfigFile.cstr (), uCRC32 );
  5784. if ( g_uCfgCRC32 == uCRC32 && tStat.st_mtime == g_tCfgStat.st_mtime && tStat.st_ctime == g_tCfgStat.st_ctime && tStat.st_size == g_tCfgStat.st_size )
  5785. return false;
  5786. g_uCfgCRC32 = uCRC32;
  5787. g_tCfgStat = tStat;
  5788. return true;
  5789. }
  5790. void ReloadIndexSettings ( CSphConfigParser * pCP )
  5791. {
  5792. assert ( pCP );
  5793. if ( !pCP->Parse ( g_sConfigFile.cstr () ) )
  5794. {
  5795. sphWarning ( "failed to parse config file '%s'; using previous settings", g_sConfigFile.cstr () );
  5796. return;
  5797. }
  5798. g_bDoDelete = false;
  5799. g_hIndexes.IterateStart ();
  5800. while ( g_hIndexes.IterateNext () )
  5801. g_hIndexes.IterateGet ().m_bToDelete = true;
  5802. g_hDistIndexes.IterateStart ();
  5803. while ( g_hDistIndexes.IterateNext () )
  5804. g_hDistIndexes.IterateGet ().m_bToDelete = true;
  5805. int nTotalIndexes = g_hIndexes.GetLength () + g_hDistIndexes.GetLength ();
  5806. int nChecked = 0;
  5807. const CSphConfig & hConf = pCP->m_tConf;
  5808. hConf["index"].IterateStart ();
  5809. while ( hConf["index"].IterateNext() )
  5810. {
  5811. const CSphConfigSection & hIndex = hConf["index"].IterateGet();
  5812. const char * sIndexName = hConf["index"].IterateGetKey().cstr();
  5813. if ( g_hIndexes.Exists ( sIndexName ) )
  5814. {
  5815. ServedIndex_t & tIndex = g_hIndexes[sIndexName];
  5816. ConfigureIndex ( tIndex, hIndex );
  5817. tIndex.m_bToDelete = false;
  5818. nChecked++;
  5819. }
  5820. else if ( g_hDistIndexes.Exists ( sIndexName ) )
  5821. {
  5822. DistributedIndex_t & tIndex = g_hDistIndexes[sIndexName];
  5823. tIndex.m_bToDelete = false;
  5824. nChecked++;
  5825. }
  5826. else if ( AddIndex ( sIndexName, hIndex ) == ADD_LOCAL )
  5827. {
  5828. ServedIndex_t & tIndex = g_hIndexes[sIndexName];
  5829. tIndex.m_bOnlyNew = true;
  5830. }
  5831. }
  5832. if ( nChecked < nTotalIndexes )
  5833. g_bDoDelete = true;
  5834. }
  5835. struct IndexToDelete_t
  5836. {
  5837. const CSphString * m_pName;
  5838. ServedIndex_t * m_pIndex;
  5839. };
  5840. void CheckDelete ()
  5841. {
  5842. if ( !g_bDoDelete )
  5843. return;
  5844. if ( g_iChildren )
  5845. return;
  5846. CSphVector<IndexToDelete_t> dToDelete;
  5847. CSphVector<const CSphString *> dDistToDelete;
  5848. dToDelete.Reserve ( 8 );
  5849. dDistToDelete.Reserve ( 8 );
  5850. g_hIndexes.IterateStart ();
  5851. while ( g_hIndexes.IterateNext () )
  5852. {
  5853. ServedIndex_t & tIndex = g_hIndexes.IterateGet ();
  5854. if ( tIndex.m_bToDelete )
  5855. {
  5856. IndexToDelete_t tToDelete;
  5857. tToDelete.m_pName = &g_hIndexes.IterateGetKey ();
  5858. tToDelete.m_pIndex = &tIndex;
  5859. dToDelete.Add ( tToDelete );
  5860. }
  5861. }
  5862. g_hDistIndexes.IterateStart ();
  5863. while ( g_hDistIndexes.IterateNext () )
  5864. {
  5865. DistributedIndex_t & tIndex = g_hDistIndexes.IterateGet ();
  5866. if ( tIndex.m_bToDelete )
  5867. dDistToDelete.Add ( &g_hDistIndexes.IterateGetKey () );
  5868. }
  5869. ARRAY_FOREACH ( i, dToDelete )
  5870. {
  5871. dToDelete [i].m_pIndex->m_pIndex->Unlock();
  5872. g_hIndexes.Delete ( *(dToDelete [i].m_pName) );
  5873. }
  5874. ARRAY_FOREACH ( i, dDistToDelete )
  5875. g_hDistIndexes.Delete ( *dDistToDelete [i] );
  5876. g_bDoDelete = false;
  5877. }
  5878. void CheckRotate ()
  5879. {
  5880. // do we need to rotate now?
  5881. if ( !g_bDoRotate )
  5882. return;
  5883. /////////////////////
  5884. // RAM-greedy rotate
  5885. /////////////////////
  5886. if ( !g_bSeamlessRotate )
  5887. {
  5888. // wait until there's no running queries
  5889. if ( g_iChildren )
  5890. return;
  5891. CSphConfigParser * pCP = NULL;
  5892. if ( CheckConfigChanges () )
  5893. {
  5894. pCP = new CSphConfigParser;
  5895. ReloadIndexSettings ( pCP );
  5896. }
  5897. g_hIndexes.IterateStart();
  5898. while ( g_hIndexes.IterateNext() )
  5899. {
  5900. ServedIndex_t & tIndex = g_hIndexes.IterateGet();
  5901. const char * sIndex = g_hIndexes.IterateGetKey().cstr();
  5902. assert ( tIndex.m_pIndex );
  5903. bool bWasAdded = tIndex.m_bOnlyNew;
  5904. RotateIndexGreedy ( tIndex, sIndex );
  5905. if ( bWasAdded && tIndex.m_bEnabled )
  5906. {
  5907. const CSphConfigType & hConf = pCP->m_tConf ["index"];
  5908. if ( hConf.Exists ( sIndex ) )
  5909. {
  5910. CSphString sError;
  5911. if ( !sphFixupIndexSettings ( tIndex.m_pIndex, hConf [sIndex], sError ) )
  5912. {
  5913. sphWarning ( "index '%s': %s - NOT SERVING", sIndex, sError.cstr() );
  5914. tIndex.m_bEnabled = false;
  5915. }
  5916. if ( tIndex.m_bEnabled && !CheckIndex ( tIndex.m_pIndex, sError ) )
  5917. {
  5918. sphWarning ( "index '%s': %s - NOT SERVING", sIndex, sError.cstr() );
  5919. tIndex.m_bEnabled = false;
  5920. }
  5921. }
  5922. }
  5923. }
  5924. SafeDelete ( pCP );
  5925. g_bDoRotate = false;
  5926. sphInfo ( "rotating finished" );
  5927. return;
  5928. }
  5929. ///////////////////
  5930. // seamless rotate
  5931. ///////////////////
  5932. assert ( g_bDoRotate && g_bSeamlessRotate );
  5933. if ( g_dRotating.GetLength() || g_sPrereading )
  5934. return; // rotate in progress already; will be handled in CheckPipes()
  5935. SafeDelete ( g_pCfg );
  5936. if ( CheckConfigChanges () )
  5937. {
  5938. g_pCfg = new CSphConfigParser;
  5939. ReloadIndexSettings ( g_pCfg );
  5940. }
  5941. // check what indexes need to be rotated
  5942. g_hIndexes.IterateStart();
  5943. while ( g_hIndexes.IterateNext() )
  5944. {
  5945. const ServedIndex_t & tIndex = g_hIndexes.IterateGet();
  5946. const char * sIndex = g_hIndexes.IterateGetKey().cstr();
  5947. assert ( tIndex.m_pIndex );
  5948. CSphString sNewPath;
  5949. sNewPath.SetSprintf ( "%s.new", tIndex.m_sIndexPath.cstr() );
  5950. // check if there's a .new index incoming
  5951. // FIXME? move this code to index, and also check for exists-but-not-readable
  5952. CSphString sTmp;
  5953. sTmp.SetSprintf ( "%s.sph", sNewPath.cstr() );
  5954. if ( !sphIsReadable ( sTmp.cstr() ) )
  5955. continue;
  5956. g_dRotating.Add ( sIndex );
  5957. }
  5958. SeamlessForkPrereader ();
  5959. }
  5960. void CheckReopen ()
  5961. {
  5962. if ( !g_bGotSigusr1 )
  5963. return;
  5964. // reopen searchd log
  5965. if ( g_iLogFile>=0 && !g_bLogTty )
  5966. {
  5967. int iFD = ::open ( g_sLogFile.cstr(), O_CREAT | O_RDWR | O_APPEND, S_IREAD | S_IWRITE );
  5968. if ( iFD<0 )
  5969. {
  5970. sphWarning ( "failed to reopen log file '%s': %s", g_sLogFile.cstr(), strerror(errno) );
  5971. } else
  5972. {
  5973. ::close ( g_iLogFile );
  5974. g_iLogFile = iFD;
  5975. g_bLogTty = ( isatty(g_iLogFile)!=0 );
  5976. sphInfo ( "log reopened" );
  5977. }
  5978. }
  5979. // reopen query log
  5980. if ( g_iQueryLogFile!=g_iLogFile && g_iQueryLogFile>=0 && !isatty(g_iQueryLogFile) )
  5981. {
  5982. int iFD = ::open ( g_sQueryLogFile.cstr(), O_CREAT | O_RDWR | O_APPEND, S_IREAD | S_IWRITE );
  5983. if ( iFD<0 )
  5984. {
  5985. sphWarning ( "failed to reopen query log file '%s': %s", g_sQueryLogFile.cstr(), strerror(errno) );
  5986. } else
  5987. {
  5988. ::close ( g_iQueryLogFile );
  5989. g_iQueryLogFile = iFD;
  5990. sphInfo ( "query log reopened" );
  5991. }
  5992. }
  5993. g_bGotSigusr1 = false;
  5994. }
  5995. void CheckFlush ()
  5996. {
  5997. if ( g_iAttrFlushPeriod<=0 || g_bFlushing )
  5998. return;
  5999. static int64_t tmLastCheck = -1000;
  6000. int64_t tmNow = sphMicroTimer();
  6001. if ( tmLastCheck + int64_t(g_iAttrFlushPeriod)*I64C(1000000) >= tmNow )
  6002. return;
  6003. tmLastCheck = tmNow;
  6004. // check if there are dirty indexes
  6005. bool bDirty = false;
  6006. g_hIndexes.IterateStart ();
  6007. while ( g_hIndexes.IterateNext () )
  6008. {
  6009. const ServedIndex_t & tServed = g_hIndexes.IterateGet ();
  6010. if ( tServed.m_bEnabled && tServed.m_iUpdateTag>g_iFlushTag )
  6011. {
  6012. bDirty = true;
  6013. break;
  6014. }
  6015. }
  6016. if ( !bDirty )
  6017. return;
  6018. // launch the flush!
  6019. g_bFlushing = true;
  6020. int iPipeFD = PipeAndFork ( false, SPH_PIPE_SAVED_ATTRS ); // FIXME! gracefully handle fork() failures, Windows, etc
  6021. if ( g_bHeadDaemon )
  6022. {
  6023. g_iFlushTag = g_iUpdateTag;
  6024. return;
  6025. }
  6026. // child process, do the work
  6027. CSphVector<CSphString> dSaved;
  6028. g_hIndexes.IterateStart ();
  6029. while ( g_hIndexes.IterateNext () )
  6030. {
  6031. const ServedIndex_t & tServed = g_hIndexes.IterateGet ();
  6032. if ( tServed.m_bEnabled && tServed.m_iUpdateTag>g_iFlushTag )
  6033. if ( tServed.m_pIndex->SaveAttributes () ) // FIXME? report errors somehow?
  6034. dSaved.Add ( g_hIndexes.IterateGetKey() );
  6035. }
  6036. // report and exit
  6037. DWORD uTmp = SPH_PIPE_SAVED_ATTRS;
  6038. ::write ( iPipeFD, &uTmp, sizeof(DWORD) );
  6039. uTmp = dSaved.GetLength();
  6040. ::write ( iPipeFD, &uTmp, sizeof(DWORD) );
  6041. ARRAY_FOREACH ( i, dSaved )
  6042. {
  6043. uTmp = strlen ( dSaved[i].cstr() );
  6044. ::write ( iPipeFD, &uTmp, sizeof(DWORD) );
  6045. ::write ( iPipeFD, dSaved[i].cstr(), uTmp );
  6046. }
  6047. ::close ( iPipeFD );
  6048. exit ( 0 );
  6049. }
  6050. #if !USE_WINDOWS
  6051. #define WINAPI
  6052. #else
  6053. SERVICE_STATUS g_ss;
  6054. SERVICE_STATUS_HANDLE g_ssHandle;
  6055. void MySetServiceStatus ( DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint )
  6056. {
  6057. static DWORD dwCheckPoint = 1;
  6058. if ( dwCurrentState == SERVICE_START_PENDING )
  6059. g_ss.dwControlsAccepted = 0;
  6060. else
  6061. g_ss.dwControlsAccepted = SERVICE_ACCEPT_STOP;
  6062. g_ss.dwCurrentState = dwCurrentState;
  6063. g_ss.dwWin32ExitCode = dwWin32ExitCode;
  6064. g_ss.dwWaitHint = dwWaitHint;
  6065. if ( dwCurrentState==SERVICE_RUNNING || dwCurrentState==SERVICE_STOPPED )
  6066. g_ss.dwCheckPoint = 0;
  6067. else
  6068. g_ss.dwCheckPoint = dwCheckPoint++;
  6069. SetServiceStatus ( g_ssHandle, &g_ss );
  6070. }
  6071. void WINAPI ServiceControl ( DWORD dwControlCode )
  6072. {
  6073. switch ( dwControlCode )
  6074. {
  6075. case SERVICE_CONTROL_STOP:
  6076. MySetServiceStatus ( SERVICE_STOP_PENDING, NO_ERROR, 0 );
  6077. g_bServiceStop = true;
  6078. break;
  6079. default:
  6080. MySetServiceStatus ( g_ss.dwCurrentState, NO_ERROR, 0 );
  6081. break;
  6082. }
  6083. }
  6084. // warning! static buffer, non-reentrable
  6085. const char * WinErrorInfo ()
  6086. {
  6087. static char sBuf[1024];
  6088. DWORD uErr = ::GetLastError ();
  6089. sprintf ( sBuf, "code=%d, error=", uErr );
  6090. int iLen = strlen(sBuf);
  6091. if ( !FormatMessage ( FORMAT_MESSAGE_FROM_SYSTEM, NULL, uErr, 0, sBuf+iLen, sizeof(sBuf)-iLen, NULL ) ) // FIXME? force US-english langid?
  6092. strcpy ( sBuf+iLen, "(no message)" );
  6093. return sBuf;
  6094. }
  6095. SC_HANDLE ServiceOpenManager ()
  6096. {
  6097. SC_HANDLE hSCM = OpenSCManager (
  6098. NULL, // local computer
  6099. NULL, // ServicesActive database
  6100. SC_MANAGER_ALL_ACCESS );// full access rights
  6101. if ( hSCM==NULL )
  6102. sphFatal ( "OpenSCManager() failed: %s", WinErrorInfo() );
  6103. return hSCM;
  6104. }
  6105. void strappend ( char * sBuf, const int iBufLimit, char * sAppend )
  6106. {
  6107. int iLen = strlen(sBuf);
  6108. int iAppend = strlen(sAppend);
  6109. int iToCopy = Min ( iBufLimit-iLen-1, iAppend );
  6110. memcpy ( sBuf+iLen, sAppend, iToCopy );
  6111. sBuf[iLen+iToCopy] = '\0';
  6112. }
  6113. void ServiceInstall ( int argc, char ** argv )
  6114. {
  6115. if ( g_bService )
  6116. return;
  6117. sphInfo ( "Installing service..." );
  6118. char szPath[MAX_PATH];
  6119. if( !GetModuleFileName ( NULL, szPath, MAX_PATH ) )
  6120. sphFatal ( "GetModuleFileName() failed: %s", WinErrorInfo() );
  6121. strappend ( szPath, sizeof(szPath), " --ntservice" );
  6122. for ( int i=1; i<argc; i++ )
  6123. if ( strcmp ( argv[i], "--install" ) )
  6124. {
  6125. strappend ( szPath, sizeof(szPath), " " );
  6126. strappend ( szPath, sizeof(szPath), argv[i] );
  6127. }
  6128. SC_HANDLE hSCM = ServiceOpenManager ();
  6129. SC_HANDLE hService = CreateService (
  6130. hSCM, // SCM database
  6131. g_sServiceName, // name of service
  6132. g_sServiceName, // service name to display
  6133. SERVICE_ALL_ACCESS, // desired access
  6134. SERVICE_WIN32_OWN_PROCESS, // service type
  6135. SERVICE_AUTO_START, // start type
  6136. SERVICE_ERROR_NORMAL, // error control type
  6137. szPath, // path to service's binary
  6138. NULL, // no load ordering group
  6139. NULL, // no tag identifier
  6140. NULL, // no dependencies
  6141. NULL, // LocalSystem account
  6142. NULL ); // no password
  6143. if ( !hService )
  6144. {
  6145. CloseServiceHandle ( hSCM );
  6146. sphFatal ( "CreateService() failed: %s", WinErrorInfo() );
  6147. } else
  6148. {
  6149. sphInfo ( "Service '%s' installed succesfully.", g_sServiceName );
  6150. }
  6151. CSphString sDesc;
  6152. sDesc.SetSprintf ( "%s-%s", g_sServiceName, SPHINX_VERSION );
  6153. SERVICE_DESCRIPTION tDesc;
  6154. tDesc.lpDescription = (LPSTR) sDesc.cstr();
  6155. if ( !ChangeServiceConfig2 ( hService, SERVICE_CONFIG_DESCRIPTION, &tDesc ) )
  6156. sphWarning ( "failed to set service description" );
  6157. CloseServiceHandle ( hService );
  6158. CloseServiceHandle ( hSCM );
  6159. }
  6160. void ServiceDelete ()
  6161. {
  6162. if ( g_bService )
  6163. return;
  6164. sphInfo ( "Deleting service..." );
  6165. // open manager
  6166. SC_HANDLE hSCM = ServiceOpenManager ();
  6167. // open service
  6168. SC_HANDLE hService = OpenService ( hSCM, g_sServiceName, DELETE );
  6169. if ( !hService )
  6170. {
  6171. CloseServiceHandle ( hSCM );
  6172. sphFatal ( "OpenService() failed: %s", WinErrorInfo() );
  6173. }
  6174. // do delete
  6175. bool bRes = !!DeleteService(hService);
  6176. CloseServiceHandle ( hService );
  6177. CloseServiceHandle ( hSCM );
  6178. if ( !bRes )
  6179. sphFatal ( "DeleteService() failed: %s", WinErrorInfo() );
  6180. else
  6181. sphInfo ( "Service '%s' deleted succesfully.", g_sServiceName );
  6182. }
  6183. #endif // USE_WINDOWS
  6184. void ShowHelp ()
  6185. {
  6186. fprintf ( stdout,
  6187. "Usage: searchd [OPTIONS]\n"
  6188. "\n"
  6189. "Options are:\n"
  6190. "-h, --help\t\tdisplay this help message\n"
  6191. "-c, -config <file>\tread configuration from specified file\n"
  6192. "\t\t\t(default is sphinx.conf)\n"
  6193. "--stop\t\t\tsend SIGTERM to currently running searchd\n"
  6194. "--status\t\tget ant print status variables\n"
  6195. "\t\t\t(PID is taken from pid_file specified in config file)\n"
  6196. "--iostats\t\tlog per-query io stats\n"
  6197. #ifdef HAVE_CLOCK_GETTIME
  6198. "--cpustats\t\tlog per-query cpu stats\n"
  6199. #endif
  6200. #if USE_WINDOWS
  6201. "--install\t\tinstall as Windows service\n"
  6202. "--delete\t\tdelete Windows service\n"
  6203. "--servicename <name>\tuse given service name (default is 'searchd')\n"
  6204. #endif
  6205. "\n"
  6206. "Debugging options are:\n"
  6207. "--console\t\trun in console mode (do not fork, do not log to files)\n"
  6208. "-p, --port <port>\tlisten on given port (overrides config setting)\n"
  6209. "-l, --listen <spec>\tlisten on given address, port or path (overrides\n"
  6210. "\t\t\tconfig settings)\n"
  6211. "-i, --index <index>\tonly serve one given index\n"
  6212. #if !USE_WINDOWS
  6213. "--nodetach\t\tdo not detach into background\n"
  6214. #endif
  6215. "\n"
  6216. "Examples:\n"
  6217. "searchd --config /usr/local/sphinx/etc/sphinx.conf\n"
  6218. #if USE_WINDOWS
  6219. "searchd --install --config c:\\sphinx\\sphinx.conf\n"
  6220. #endif
  6221. );
  6222. }
  6223. #if USE_WINDOWS
  6224. BOOL WINAPI CtrlHandler ( DWORD )
  6225. {
  6226. if ( !g_bService )
  6227. g_bGotSigterm = true;
  6228. return TRUE;
  6229. }
  6230. #endif
  6231. /// check for incoming signals, and react on them
  6232. void CheckSignals ()
  6233. {
  6234. #if USE_WINDOWS
  6235. if ( g_bService && g_bServiceStop )
  6236. {
  6237. Shutdown ();
  6238. MySetServiceStatus ( SERVICE_STOPPED, NO_ERROR, 0 );
  6239. exit ( 0 );
  6240. }
  6241. #endif
  6242. if ( g_bGotSighup )
  6243. {
  6244. sphInfo ( "rotating indices (seamless=%d)", (int)g_bSeamlessRotate ); // this might hang if performed from SIGHUP
  6245. g_bGotSighup = false;
  6246. }
  6247. if ( g_bGotSigterm )
  6248. {
  6249. assert ( g_bHeadDaemon );
  6250. sphInfo ( "caught SIGTERM, shutting down" );
  6251. Shutdown ();
  6252. exit ( 0 );
  6253. }
  6254. #if !USE_WINDOWS
  6255. if ( g_bGotSigchld )
  6256. {
  6257. while ( waitpid ( -1, NULL, WNOHANG ) > 0 )
  6258. g_iChildren--;
  6259. g_bGotSigchld = false;
  6260. }
  6261. #endif
  6262. #if USE_WINDOWS
  6263. BYTE dPipeInBuf [ WIN32_PIPE_BUFSIZE ];
  6264. DWORD nBytesRead = 0;
  6265. BOOL bSuccess = ReadFile ( g_hPipe, dPipeInBuf, WIN32_PIPE_BUFSIZE, &nBytesRead, NULL );
  6266. if ( nBytesRead > 0 && bSuccess )
  6267. {
  6268. for ( DWORD i = 0; i < nBytesRead; i++ )
  6269. {
  6270. switch ( dPipeInBuf [i] )
  6271. {
  6272. case 0:
  6273. g_bDoRotate = true;
  6274. g_bGotSighup = true;
  6275. break;
  6276. case 1:
  6277. g_bGotSigterm = true;
  6278. if ( g_bService )
  6279. g_bServiceStop = true;
  6280. break;
  6281. }
  6282. }
  6283. DisconnectNamedPipe ( g_hPipe );
  6284. ConnectNamedPipe ( g_hPipe, NULL );
  6285. }
  6286. #endif
  6287. }
  6288. void QueryStatus ( CSphVariant * v )
  6289. {
  6290. char sBuf [ SPH_ADDRESS_SIZE ];
  6291. for ( ; v; v = v->m_pNext )
  6292. {
  6293. ListenerDesc_t tDesc = ParseListener ( v->cstr() );
  6294. if ( tDesc.m_eProto!=PROTO_SPHINX )
  6295. continue;
  6296. int iSock = -1;
  6297. #if !USE_WINDOWS
  6298. if ( !tDesc.m_sUnix.IsEmpty() )
  6299. {
  6300. // UNIX connection
  6301. struct sockaddr_un uaddr;
  6302. size_t len = strlen ( tDesc.m_sUnix.cstr() );
  6303. if ( len+1 > sizeof(uaddr.sun_path ) )
  6304. sphFatal ( "UNIX socket path is too long (len=%d)", len );
  6305. memset ( &uaddr, 0, sizeof(uaddr) );
  6306. uaddr.sun_family = AF_UNIX;
  6307. memcpy ( uaddr.sun_path, tDesc.m_sUnix.cstr(), len+1 );
  6308. int iSock = socket ( AF_UNIX, SOCK_STREAM, 0 );
  6309. if ( iSock<0 )
  6310. sphFatal ( "failed to create UNIX socket: %s", sphSockError() );
  6311. if ( connect ( iSock, (struct sockaddr*)&uaddr, sizeof(uaddr) )<0 )
  6312. {
  6313. sphWarning ( "failed to connect to unix://%s: %s\n", tDesc.m_sUnix.cstr(), sphSockError() );
  6314. continue;
  6315. }
  6316. } else
  6317. #endif
  6318. {
  6319. // TCP connection
  6320. struct sockaddr_in sin;
  6321. memset ( &sin, 0, sizeof(sin) );
  6322. sin.sin_family = AF_INET;
  6323. sin.sin_addr.s_addr = ( tDesc.m_uIP==htonl(INADDR_ANY) )
  6324. ? htonl(INADDR_LOOPBACK)
  6325. : tDesc.m_uIP;
  6326. sin.sin_port = htons ( (short)tDesc.m_iPort );
  6327. iSock = socket ( AF_INET, SOCK_STREAM, 0 );
  6328. if ( iSock<0 )
  6329. sphFatal ( "failed to create TCP socket: %s", sphSockError() );
  6330. if ( connect ( iSock, (struct sockaddr*)&sin, sizeof(sin) )<0 )
  6331. {
  6332. sphWarning ( "failed to connect to %s:%d: %s\n", sphFormatIP ( sBuf, sizeof(sBuf), tDesc.m_uIP ), tDesc.m_iPort, sphSockError() );
  6333. continue;
  6334. }
  6335. }
  6336. // send request
  6337. NetOutputBuffer_c tOut ( iSock );
  6338. tOut.SendDword ( SPHINX_SEARCHD_PROTO );
  6339. tOut.SendWord ( SEARCHD_COMMAND_STATUS );
  6340. tOut.SendWord ( VER_COMMAND_STATUS );
  6341. tOut.SendInt ( 4 ); // request body length
  6342. tOut.SendInt ( 1 ); // dummy body
  6343. tOut.Flush ();
  6344. // get reply
  6345. NetInputBuffer_c tIn ( iSock );
  6346. if ( !tIn.ReadFrom ( 12, 5 ) ) // magic_header_size=12, magic_timeout=5
  6347. sphFatal ( "handshake failure (no response)" );
  6348. DWORD uVer = tIn.GetDword();
  6349. if ( uVer!=SPHINX_SEARCHD_PROTO && uVer!=0x01000000UL ) // workaround for all the revisions that sent it in host order...
  6350. sphFatal ( "handshake failure (unexpected protocol version=%d)", uVer );
  6351. if ( tIn.GetWord()!=SEARCHD_OK )
  6352. sphFatal ( "status command failed" );
  6353. if ( tIn.GetWord()!=VER_COMMAND_STATUS )
  6354. sphFatal ( "status command version mismatch" );
  6355. if ( !tIn.ReadFrom ( tIn.GetDword(), 5 ) ) // magic_timeout=5
  6356. sphFatal ( "failed to read status reply" );
  6357. fprintf ( stdout, "\nsearchd status\n--------------\n" );
  6358. int iRows = tIn.GetDword();
  6359. int iCols = tIn.GetDword();
  6360. for ( int i=0; i<iRows && !tIn.GetError(); i++ )
  6361. {
  6362. for ( int j=0; j<iCols && !tIn.GetError(); j++ )
  6363. {
  6364. fprintf ( stdout, "%s", tIn.GetString().cstr() );
  6365. fprintf ( stdout, ( j==0 ) ? ": " : " " );
  6366. }
  6367. fprintf ( stdout, "\n" );
  6368. }
  6369. // all done
  6370. sphSockClose ( iSock );
  6371. return;
  6372. }
  6373. }
  6374. int WINAPI ServiceMain ( int argc, char **argv )
  6375. {
  6376. g_bLogTty = isatty ( g_iLogFile )!=0;
  6377. #if USE_WINDOWS
  6378. CSphVector<char *> dArgs;
  6379. if ( g_bService )
  6380. {
  6381. g_ssHandle = RegisterServiceCtrlHandler ( g_sServiceName, ServiceControl );
  6382. if ( !g_ssHandle )
  6383. sphFatal ( "failed to start service: RegisterServiceCtrlHandler() failed: %s", WinErrorInfo() );
  6384. g_ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  6385. MySetServiceStatus ( SERVICE_START_PENDING, NO_ERROR, 4000 );
  6386. if ( argc<=1 )
  6387. {
  6388. dArgs.Resize ( g_dArgs.GetLength() );
  6389. ARRAY_FOREACH ( i, g_dArgs )
  6390. dArgs[i] = (char*) g_dArgs[i].cstr();
  6391. argc = g_dArgs.GetLength();
  6392. argv = &dArgs[0];
  6393. }
  6394. }
  6395. char szPipeName [64];
  6396. sprintf ( szPipeName, "\\\\.\\pipe\\searchd_%d", getpid() );
  6397. g_hPipe = CreateNamedPipe ( szPipeName, PIPE_ACCESS_INBOUND, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES, 0, WIN32_PIPE_BUFSIZE, NMPWAIT_NOWAIT, NULL );
  6398. ConnectNamedPipe ( g_hPipe, NULL );
  6399. #endif
  6400. if ( !g_bService )
  6401. fprintf ( stdout, SPHINX_BANNER );
  6402. //////////////////////
  6403. // parse command line
  6404. //////////////////////
  6405. CSphConfig conf;
  6406. bool bOptStop = false;
  6407. bool bOptStatus = false;
  6408. bool bOptPIDFile = false;
  6409. const char * sOptIndex = NULL;
  6410. int iOptPort = 0;
  6411. bool bOptPort = false;
  6412. CSphString sOptListen;
  6413. bool bOptListen = false;
  6414. #define OPT(_a1,_a2) else if ( !strcmp(argv[i],_a1) || !strcmp(argv[i],_a2) )
  6415. #define OPT1(_a1) else if ( !strcmp(argv[i],_a1) )
  6416. int i;
  6417. for ( i=1; i<argc; i++ )
  6418. {
  6419. // handle non-options
  6420. if ( argv[i][0]!='-' ) break;
  6421. // handle no-arg options
  6422. OPT ( "-h", "--help" ) { ShowHelp(); return 0; }
  6423. OPT ( "-?", "--?" ) { ShowHelp(); return 0; }
  6424. OPT1 ( "--console" ) { g_bOptConsole = true; g_bOptNoDetach = true; }
  6425. OPT1 ( "--stop" ) bOptStop = true;
  6426. OPT1 ( "--status" ) bOptStatus = true;
  6427. OPT1 ( "--pidfile" ) bOptPIDFile = true;
  6428. OPT1 ( "--iostats" ) g_bIOStats = true;
  6429. #if !USE_WINDOWS
  6430. OPT1 ( "--cpustats" ) g_bCpuStats = true;
  6431. #endif
  6432. #if USE_WINDOWS
  6433. OPT1 ( "--install" ) { if ( !g_bService ) { ServiceInstall ( argc, argv ); return 0; } }
  6434. OPT1 ( "--delete" ) { if ( !g_bService ) { ServiceDelete (); return 0; } }
  6435. OPT1 ( "--ntservice" ) ; // it's valid but handled elsewhere
  6436. #else
  6437. OPT1 ( "--nodetach" ) g_bOptNoDetach = true;
  6438. #endif
  6439. // handle 1-arg options
  6440. else if ( (i+1)>=argc ) break;
  6441. OPT ( "-c", "--config" ) g_sConfigFile = argv[++i];
  6442. OPT ( "-p", "--port" ) { bOptPort = true; iOptPort = atoi ( argv[++i] ); }
  6443. OPT ( "-l", "--listen" ) { bOptListen = true; sOptListen = argv[++i]; }
  6444. OPT ( "-i", "--index" ) sOptIndex = argv[++i];
  6445. #if USE_WINDOWS
  6446. OPT1 ( "--servicename" ) ++i; // it's valid but handled elsewhere
  6447. #endif
  6448. // handle unknown options
  6449. else break;
  6450. }
  6451. if ( i!=argc )
  6452. sphFatal ( "malformed or unknown option near '%s'; use '-h' or '--help' to see available options.", argv[i] );
  6453. #if USE_WINDOWS
  6454. if ( !g_bService )
  6455. {
  6456. sphWarning ( "forcing --console mode on Windows" );
  6457. g_bOptConsole = g_bOptNoDetach = true;
  6458. }
  6459. // init WSA on Windows
  6460. // we need to do it this early because otherwise gethostbyname() from config parser could fail
  6461. WSADATA tWSAData;
  6462. int iStartupErr = WSAStartup ( WINSOCK_VERSION, &tWSAData );
  6463. if ( iStartupErr )
  6464. sphFatal ( "failed to initialize WinSock2: %s", sphSockError(iStartupErr) );
  6465. #endif
  6466. if ( !bOptPIDFile )
  6467. bOptPIDFile = !g_bOptConsole;
  6468. // check port and listen arguments early
  6469. if ( !g_bOptConsole && ( bOptPort || bOptListen ) )
  6470. {
  6471. sphWarning ( "--listen and --port are only allowed in --console debug mode; switch ignored" );
  6472. bOptPort = bOptListen = false;
  6473. }
  6474. if ( bOptPort )
  6475. {
  6476. if ( bOptListen )
  6477. sphFatal ( "please specify either --port or --listen, not both" );
  6478. CheckPort ( iOptPort );
  6479. }
  6480. /////////////////////
  6481. // parse config file
  6482. /////////////////////
  6483. // fallback to defaults if there was no explicit config specified
  6484. while ( !g_sConfigFile.cstr() )
  6485. {
  6486. #ifdef SYSCONFDIR
  6487. g_sConfigFile = SYSCONFDIR "/sphinx.conf";
  6488. if ( sphIsReadable ( g_sConfigFile.cstr () ) )
  6489. break;
  6490. #endif
  6491. g_sConfigFile = "./sphinx.conf";
  6492. if ( sphIsReadable ( g_sConfigFile.cstr () ) )
  6493. break;
  6494. g_sConfigFile = NULL;
  6495. break;
  6496. }
  6497. if ( !g_sConfigFile.cstr () )
  6498. sphFatal ( "no readable config file (looked in "
  6499. #ifdef SYSCONFDIR
  6500. SYSCONFDIR "/sphinx.conf, "
  6501. #endif
  6502. "./sphinx.conf)." );
  6503. sphInfo ( "using config file '%s'...", g_sConfigFile.cstr () );
  6504. CheckConfigChanges ();
  6505. // do parse
  6506. CSphConfigParser cp;
  6507. if ( !cp.Parse ( g_sConfigFile.cstr () ) )
  6508. sphFatal ( "failed to parse config file '%s'", g_sConfigFile.cstr () );
  6509. const CSphConfig & hConf = cp.m_tConf;
  6510. if ( !hConf.Exists ( "searchd" ) || !hConf["searchd"].Exists ( "searchd" ) )
  6511. sphFatal ( "'searchd' config section not found in '%s'", g_sConfigFile.cstr () );
  6512. const CSphConfigSection & hSearchd = hConf["searchd"]["searchd"];
  6513. ////////////////////////
  6514. // stop running searchd
  6515. ////////////////////////
  6516. if ( bOptStop )
  6517. {
  6518. if ( !hSearchd("pid_file") )
  6519. sphFatal ( "stop: option 'pid_file' not found in '%s' section 'searchd'", g_sConfigFile.cstr () );
  6520. const char * sPid = hSearchd["pid_file"].cstr(); // shortcut
  6521. FILE * fp = fopen ( sPid, "r" );
  6522. if ( !fp )
  6523. sphFatal ( "stop: pid file '%s' does not exist or is not readable", sPid );
  6524. char sBuf[16];
  6525. int iLen = (int) fread ( sBuf, 1, sizeof(sBuf)-1, fp );
  6526. sBuf[iLen] = '\0';
  6527. fclose ( fp );
  6528. int iPid = atoi(sBuf);
  6529. if ( iPid<=0 )
  6530. sphFatal ( "stop: failed to read valid pid from '%s'", sPid );
  6531. #if USE_WINDOWS
  6532. bool bTerminatedOk = false;
  6533. char szPipeName [64];
  6534. sprintf ( szPipeName, "\\\\.\\pipe\\searchd_%d", iPid );
  6535. HANDLE hPipe = INVALID_HANDLE_VALUE;
  6536. while ( hPipe == INVALID_HANDLE_VALUE )
  6537. {
  6538. hPipe = CreateFile ( szPipeName, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL );
  6539. if ( hPipe == INVALID_HANDLE_VALUE )
  6540. {
  6541. if ( GetLastError () != ERROR_PIPE_BUSY )
  6542. {
  6543. fprintf ( stdout, "WARNING: could not open pipe (GetLastError()=%d)\n", GetLastError () );
  6544. break;
  6545. }
  6546. if ( !WaitNamedPipe ( szPipeName, 1000 ) )
  6547. {
  6548. fprintf ( stdout, "WARNING: could not open pipe (GetLastError()=%d)\n", GetLastError () );
  6549. break;
  6550. }
  6551. }
  6552. }
  6553. if ( hPipe != INVALID_HANDLE_VALUE )
  6554. {
  6555. DWORD uWritten = 0;
  6556. BYTE uWrite = 1;
  6557. BOOL bResult = WriteFile ( hPipe, &uWrite, 1, &uWritten, NULL );
  6558. if ( !bResult )
  6559. fprintf ( stdout, "WARNING: failed to send SIGHTERM to searchd (pid=%d, GetLastError()=%d)\n", iPid, GetLastError () );
  6560. bTerminatedOk = !!bResult;
  6561. CloseHandle ( hPipe );
  6562. }
  6563. if ( bTerminatedOk )
  6564. {
  6565. sphInfo ( "stop: succesfully terminated pid %d", iPid );
  6566. exit ( 0 );
  6567. }
  6568. else
  6569. sphFatal ( "stop: error terminating pid %d", iPid );
  6570. #else
  6571. if ( kill ( iPid, SIGTERM ) )
  6572. sphFatal ( "stop: kill() on pid %d failed: %s", iPid, strerror(errno) );
  6573. else
  6574. {
  6575. sphInfo ( "stop: succesfully sent SIGTERM to pid %d", iPid );
  6576. exit ( 0 );
  6577. }
  6578. #endif
  6579. }
  6580. ////////////////////////////////
  6581. // query running searchd status
  6582. ////////////////////////////////
  6583. if ( bOptStatus )
  6584. {
  6585. QueryStatus ( hSearchd("listen") );
  6586. exit ( 0 );
  6587. }
  6588. /////////////////////
  6589. // configure searchd
  6590. /////////////////////
  6591. if ( !hConf.Exists ( "index" ) )
  6592. sphFatal ( "no indexes found in '%s'", g_sConfigFile.cstr () );
  6593. #define CONF_CHECK(_hash,_key,_msg,_add) \
  6594. if (!( _hash.Exists ( _key ) )) \
  6595. sphFatal ( "mandatory option '%s' not found " _msg, _key, _add );
  6596. if ( bOptPIDFile )
  6597. CONF_CHECK ( hSearchd, "pid_file", "in 'searchd' section", "" );
  6598. if ( hSearchd.Exists ( "read_timeout" ) && hSearchd["read_timeout"].intval()>=0 )
  6599. g_iReadTimeout = hSearchd["read_timeout"].intval();
  6600. if ( hSearchd.Exists ( "client_timeout" ) && hSearchd["client_timeout"].intval()>=0 )
  6601. g_iClientTimeout = hSearchd["client_timeout"].intval();
  6602. if ( hSearchd.Exists ( "max_children" ) && hSearchd["max_children"].intval()>=0 )
  6603. g_iMaxChildren = hSearchd["max_children"].intval();
  6604. g_bPreopenIndexes = hSearchd.GetInt ( "preopen_indexes", (int)g_bPreopenIndexes ) != 0;
  6605. g_bOnDiskDicts = hSearchd.GetInt ( "ondisk_dict_default", (int)g_bOnDiskDicts ) != 0;
  6606. g_bUnlinkOld = hSearchd.GetInt ( "unlink_old", (int)g_bUnlinkOld ) != 0;
  6607. if ( hSearchd("max_matches") )
  6608. {
  6609. int iMax = hSearchd["max_matches"].intval();
  6610. if ( iMax<0 || iMax>10000000 )
  6611. {
  6612. sphWarning ( "max_matches=%d out of bounds; using default 1000", iMax );
  6613. } else
  6614. {
  6615. g_iMaxMatches = iMax;
  6616. }
  6617. }
  6618. if ( hSearchd("seamless_rotate") )
  6619. g_bSeamlessRotate = ( hSearchd["seamless_rotate"].intval()!=0 );
  6620. if ( !g_bSeamlessRotate && g_bPreopenIndexes )
  6621. sphWarning ( "preopen_indexes=1 has no effect with seamless_rotate=0" );
  6622. #if USE_WINDOWS
  6623. if ( g_bSeamlessRotate )
  6624. {
  6625. sphWarning ( "seamless_rotate is not yet supported in windows; forcing seamless_rotate=0" );
  6626. g_bSeamlessRotate = false;
  6627. }
  6628. #endif
  6629. g_iAttrFlushPeriod = hSearchd.GetInt ( "attr_flush_period", g_iAttrFlushPeriod );
  6630. g_iMaxPacketSize = hSearchd.GetSize ( "max_packet_size", g_iMaxPacketSize );
  6631. g_iMaxFilters = hSearchd.GetInt ( "max_filters", g_iMaxFilters );
  6632. g_iMaxFilterValues = hSearchd.GetInt ( "max_filter_values", g_iMaxFilterValues );
  6633. if ( g_iMaxPacketSize<128*1024 || g_iMaxPacketSize>128*1024*1024 )
  6634. sphFatal ( "max_packet_size out of bounds (128K..128M)" );
  6635. if ( g_iMaxFilters<1 || g_iMaxFilters>10240 )
  6636. sphFatal ( "max_filters out of bounds (1..10240)" );
  6637. if ( g_iMaxFilterValues<1 || g_iMaxFilterValues>1048576 )
  6638. sphFatal ( "max_filter_values out of bounds (1..1048576)" );
  6639. // create and lock pid
  6640. if ( bOptPIDFile )
  6641. {
  6642. g_sPidFile = hSearchd["pid_file"].cstr();
  6643. g_iPidFD = ::open ( g_sPidFile, O_CREAT | O_WRONLY, S_IREAD | S_IWRITE );
  6644. if ( g_iPidFD<0 )
  6645. sphFatal ( "failed to create pid file '%s': %s", g_sPidFile, strerror(errno) );
  6646. if ( !sphLockEx ( g_iPidFD, false ) )
  6647. sphFatal ( "failed to lock pid file '%s': %s (searchd already running?)", g_sPidFile, strerror(errno) );
  6648. }
  6649. if ( hSearchd("crash_log_path") )
  6650. {
  6651. g_sCrashLog_Path = hSearchd["crash_log_path"].cstr();
  6652. g_bCrashLog_Enabled = true;
  6653. char sPath[1024];
  6654. snprintf ( sPath, sizeof(sPath), "%s.test", g_sCrashLog_Path );
  6655. int iFd = open ( sPath, O_CREAT | O_WRONLY, 0644 );
  6656. if ( iFd == -1 )
  6657. sphWarning ( "unable to create files in crash_log_path: %s", strerror(errno) );
  6658. else
  6659. {
  6660. close ( iFd );
  6661. unlink ( sPath );
  6662. }
  6663. }
  6664. /////////////////////////
  6665. // perf counters startup
  6666. /////////////////////////
  6667. CSphString sError, sWarning;
  6668. if ( !g_tStatsBuffer.Alloc ( sizeof(SearchdStats_t), sError, sWarning ) )
  6669. {
  6670. sphWarning ( "performance counters disabled (alloc error: %s)", sError.cstr() );
  6671. g_pStats = NULL;
  6672. } else
  6673. {
  6674. g_pStats = (SearchdStats_t*) g_tStatsBuffer.GetWritePtr(); // FIXME? should be ok even on strange platforms but..
  6675. memset ( g_pStats, 0, sizeof(SearchdStats_t) ); // reset
  6676. g_pStats->m_uStarted = (DWORD)time(NULL);
  6677. }
  6678. ////////////////////
  6679. // network startup
  6680. ////////////////////
  6681. Listener_t tListener;
  6682. tListener.m_eProto = PROTO_SPHINX;
  6683. // command line arguments override config (but only in --console)
  6684. if ( bOptListen )
  6685. {
  6686. AddListener ( sOptListen );
  6687. } else if ( bOptPort )
  6688. {
  6689. tListener.m_iSock = sphCreateInetSocket ( htonl(INADDR_ANY), iOptPort );
  6690. g_dListeners.Add ( tListener );
  6691. } else
  6692. {
  6693. // listen directives in configuration file
  6694. for ( CSphVariant * v = hSearchd("listen"); v; v = v->m_pNext )
  6695. AddListener ( *v );
  6696. // handle deprecated directives
  6697. if ( hSearchd("port") )
  6698. {
  6699. DWORD uAddr = hSearchd.Exists("address") ?
  6700. sphGetAddress ( hSearchd["address"].cstr(), GETADDR_STRICT ) : htonl(INADDR_ANY);
  6701. int iPort = hSearchd["port"].intval();
  6702. CheckPort(iPort);
  6703. tListener.m_iSock = sphCreateInetSocket ( uAddr, iPort );
  6704. g_dListeners.Add ( tListener);
  6705. }
  6706. // still nothing? listen on INADDR_ANY, default port
  6707. if ( !g_dListeners.GetLength() )
  6708. {
  6709. tListener.m_iSock = sphCreateInetSocket ( htonl(INADDR_ANY), SEARCHD_DEFAULT_PORT );
  6710. g_dListeners.Add ( tListener );
  6711. }
  6712. }
  6713. #if !USE_WINDOWS
  6714. // reserve an fd for clients
  6715. int iDevNull = open ( "/dev/null", O_RDWR );
  6716. int iClientFD = dup(iDevNull);
  6717. #endif
  6718. //////////////////////
  6719. // build indexes hash
  6720. //////////////////////
  6721. // configure and preload
  6722. int iValidIndexes = 0;
  6723. hConf["index"].IterateStart ();
  6724. while ( hConf["index"].IterateNext() )
  6725. {
  6726. const CSphConfigSection & hIndex = hConf["index"].IterateGet();
  6727. const char * sIndexName = hConf["index"].IterateGetKey().cstr();
  6728. if ( g_bOptConsole && sOptIndex && strcasecmp ( sIndexName, sOptIndex )!=0 )
  6729. continue;
  6730. AddIndex ( sIndexName, hIndex );
  6731. if ( g_hIndexes.Exists ( sIndexName ) )
  6732. {
  6733. ServedIndex_t & tIndex = g_hIndexes [sIndexName];
  6734. if ( HasFiles ( tIndex, g_dNewExts ) )
  6735. {
  6736. tIndex.m_bOnlyNew = !HasFiles ( tIndex, g_dCurExts );
  6737. if ( RotateIndexGreedy ( tIndex, sIndexName ) )
  6738. {
  6739. CSphString sError;
  6740. if ( !sphFixupIndexSettings ( tIndex.m_pIndex, hIndex, sError ) )
  6741. {
  6742. sphWarning ( "index '%s': %s - NOT SERVING", sIndexName, sError.cstr() );
  6743. tIndex.m_bEnabled = false;
  6744. }
  6745. }
  6746. else
  6747. {
  6748. if ( PrereadNewIndex ( tIndex, hIndex, sIndexName ) )
  6749. tIndex.m_bEnabled = true;
  6750. }
  6751. }
  6752. else
  6753. {
  6754. tIndex.m_bOnlyNew = false;
  6755. if ( PrereadNewIndex ( tIndex, hIndex, sIndexName ) )
  6756. tIndex.m_bEnabled = true;
  6757. }
  6758. CSphString sError;
  6759. if ( tIndex.m_bEnabled && !CheckIndex ( tIndex.m_pIndex, sError ) )
  6760. {
  6761. sphWarning ( "index '%s': %s - NOT SERVING", sIndexName, sError.cstr() );
  6762. tIndex.m_bEnabled = false;
  6763. }
  6764. if ( !tIndex.m_bEnabled )
  6765. continue;
  6766. }
  6767. iValidIndexes++;
  6768. }
  6769. if ( !iValidIndexes )
  6770. sphFatal ( "no valid indexes to serve" );
  6771. ///////////
  6772. // startup
  6773. ///////////
  6774. // handle my signals
  6775. SetSignalHandlers ();
  6776. // setup mva updates arena
  6777. sphArenaInit ( hSearchd.GetSize ( "mva_updates_pool", 1048576 ) );
  6778. // create logs
  6779. if ( !g_bOptConsole )
  6780. {
  6781. // create log
  6782. const char * sLog = "searchd.log";
  6783. if ( hSearchd.Exists ( "log" ) )
  6784. sLog = hSearchd["log"].cstr();
  6785. umask ( 066 );
  6786. g_iLogFile = open ( sLog, O_CREAT | O_RDWR | O_APPEND, S_IREAD | S_IWRITE );
  6787. if ( g_iLogFile<0 )
  6788. {
  6789. g_iLogFile = STDOUT_FILENO;
  6790. sphFatal ( "failed to open log file '%s': %s", sLog, strerror(errno) );
  6791. }
  6792. g_bLogTty = isatty ( g_iLogFile )!=0;
  6793. g_sLogFile = sLog;
  6794. // create query log if required
  6795. if ( hSearchd.Exists ( "query_log" ) )
  6796. {
  6797. g_iQueryLogFile = open ( hSearchd["query_log"].cstr(), O_CREAT | O_RDWR | O_APPEND, S_IREAD | S_IWRITE );
  6798. if ( g_iQueryLogFile<0 )
  6799. sphFatal ( "failed to open query log file '%s': %s", hSearchd["query_log"].cstr(), strerror(errno) );
  6800. g_sQueryLogFile = hSearchd["query_log"].cstr();
  6801. }
  6802. }
  6803. // almost ready, time to start listening
  6804. int iBacklog = hSearchd.GetInt ( "listen_backlog", SEARCHD_BACKLOG );
  6805. ARRAY_FOREACH ( i, g_dListeners )
  6806. if ( listen ( g_dListeners[i].m_iSock, iBacklog )==-1 )
  6807. sphFatal ( "listen() failed: %s", sphSockError() );
  6808. // prepare to detach
  6809. if ( !g_bOptNoDetach )
  6810. {
  6811. #if !USE_WINDOWS
  6812. close ( STDIN_FILENO );
  6813. close ( STDOUT_FILENO );
  6814. close ( STDERR_FILENO );
  6815. dup2 ( iDevNull, STDIN_FILENO );
  6816. dup2 ( iDevNull, STDOUT_FILENO );
  6817. dup2 ( iDevNull, STDERR_FILENO );
  6818. #endif
  6819. g_bLogStdout = false;
  6820. // explicitly unlock everything in parent immediately before fork
  6821. //
  6822. // there's a race in case another instance is started before
  6823. // child re-acquires all locks; but let's hope that's rare
  6824. g_hIndexes.IterateStart ();
  6825. while ( g_hIndexes.IterateNext () )
  6826. {
  6827. ServedIndex_t & tServed = g_hIndexes.IterateGet ();
  6828. if ( tServed.m_bEnabled )
  6829. tServed.m_pIndex->Unlock();
  6830. }
  6831. }
  6832. if ( bOptPIDFile )
  6833. sphLockUn ( g_iPidFD );
  6834. #if !USE_WINDOWS
  6835. if ( !g_bOptNoDetach )
  6836. {
  6837. switch ( fork() )
  6838. {
  6839. case -1:
  6840. // error
  6841. Shutdown ();
  6842. sphFatal ( "fork() failed (reason: %s)", strerror ( errno ) );
  6843. exit ( 1 );
  6844. case 0:
  6845. // daemonized child
  6846. break;
  6847. default:
  6848. // tty-controlled parent
  6849. sphSetProcessInfo ( false );
  6850. exit ( 0 );
  6851. }
  6852. }
  6853. #endif
  6854. if ( bOptPIDFile )
  6855. {
  6856. #if !USE_WINDOWS
  6857. // re-lock pid
  6858. // FIXME! there's a potential race here
  6859. if ( !sphLockEx ( g_iPidFD, true ) )
  6860. sphFatal ( "failed to re-lock pid file '%s': %s", g_sPidFile, strerror(errno) );
  6861. #endif
  6862. char sPid[16];
  6863. snprintf ( sPid, sizeof(sPid), "%d\n", getpid() );
  6864. int iPidLen = strlen(sPid);
  6865. if ( ::write ( g_iPidFD, sPid, iPidLen )!=iPidLen )
  6866. sphFatal ( "failed to write to pid file '%s': %s", g_sPidFile, strerror(errno) );
  6867. ftruncate ( g_iPidFD, iPidLen );
  6868. }
  6869. #if USE_WINDOWS
  6870. SetConsoleCtrlHandler ( CtrlHandler, TRUE );
  6871. #endif
  6872. if ( !g_bOptNoDetach )
  6873. {
  6874. // re-lock indexes
  6875. g_hIndexes.IterateStart ();
  6876. while ( g_hIndexes.IterateNext () )
  6877. {
  6878. ServedIndex_t & tServed = g_hIndexes.IterateGet ();
  6879. if ( !tServed.m_bEnabled )
  6880. continue;
  6881. // obtain exclusive lock
  6882. if ( !tServed.m_pIndex->Lock() )
  6883. {
  6884. sphWarning ( "index '%s': lock: %s; INDEX UNUSABLE", g_hIndexes.IterateGetKey().cstr(),
  6885. tServed.m_pIndex->GetLastError().cstr() );
  6886. tServed.m_bEnabled = false;
  6887. continue;
  6888. }
  6889. // try to mlock again because mlock does not survive over fork
  6890. if ( !tServed.m_pIndex->Mlock() )
  6891. {
  6892. sphWarning ( "index '%s': %s", g_hIndexes.IterateGetKey().cstr(),
  6893. tServed.m_pIndex->GetLastError().cstr() );
  6894. }
  6895. }
  6896. }
  6897. // if we're running in console mode, dump queries to tty as well
  6898. if ( g_bOptConsole )
  6899. g_iQueryLogFile = g_iLogFile;
  6900. /////////////////
  6901. // serve clients
  6902. /////////////////
  6903. g_bHeadDaemon = true;
  6904. sphInfo ( "accepting connections" );
  6905. #if USE_WINDOWS
  6906. if ( g_bService )
  6907. MySetServiceStatus ( SERVICE_RUNNING, NO_ERROR, 0 );
  6908. #endif
  6909. sphSetInternalErrorCallback ( LogInternalError );
  6910. sphSetReadBuffers ( hSearchd.GetSize ( "read_buffer", 0 ), hSearchd.GetSize ( "read_unhinted", 0 ) );
  6911. fd_set fdsAccept;
  6912. FD_ZERO ( &fdsAccept );
  6913. int iNfds = 0;
  6914. ARRAY_FOREACH ( i, g_dListeners )
  6915. iNfds = Max ( iNfds, g_dListeners[i].m_iSock );
  6916. iNfds++;
  6917. for ( ;; )
  6918. {
  6919. CheckSignals ();
  6920. CheckLeaks ();
  6921. CheckPipes ();
  6922. CheckDelete ();
  6923. CheckRotate ();
  6924. CheckReopen ();
  6925. CheckFlush ();
  6926. sphLog ( LOG_INFO, NULL, NULL ); // flush dupes
  6927. ARRAY_FOREACH ( i, g_dListeners )
  6928. sphFDSet ( g_dListeners[i].m_iSock, &fdsAccept );
  6929. struct timeval tvTimeout;
  6930. tvTimeout.tv_sec = USE_WINDOWS ? 0 : 1;
  6931. tvTimeout.tv_usec = USE_WINDOWS ? 50000 : 0;
  6932. int iRes = select ( iNfds, &fdsAccept, NULL, NULL, &tvTimeout );
  6933. if ( iRes == 0 )
  6934. continue;
  6935. if ( iRes == -1 )
  6936. {
  6937. int iErrno = sphSockGetErrno();
  6938. if ( iErrno == EINTR || iErrno == EAGAIN || iErrno == EWOULDBLOCK )
  6939. continue;
  6940. static int iLastErrno = -1;
  6941. if ( iLastErrno != iErrno )
  6942. sphWarning ( "select() failed: %s", sphSockError(iErrno) );
  6943. iLastErrno = iErrno;
  6944. continue;
  6945. }
  6946. ARRAY_FOREACH ( i, g_dListeners )
  6947. {
  6948. if ( !FD_ISSET ( g_dListeners[i].m_iSock, &fdsAccept ) )
  6949. continue;
  6950. struct sockaddr_storage saStorage;
  6951. socklen_t uLength = sizeof(saStorage);
  6952. int iClientSock = accept ( g_dListeners[i].m_iSock, (struct sockaddr *)&saStorage, &uLength );
  6953. if ( iClientSock == -1 )
  6954. {
  6955. const int iErrno = sphSockGetErrno();
  6956. if ( iErrno==EINTR || iErrno==ECONNABORTED || iErrno==EAGAIN || iErrno==EWOULDBLOCK )
  6957. continue;
  6958. sphFatal ( "accept() failed: %s", sphSockError(iErrno) );
  6959. }
  6960. if ( g_pStats )
  6961. g_pStats->m_iConnections++;
  6962. if ( ( g_iMaxChildren && g_iChildren>=g_iMaxChildren )
  6963. || ( g_bDoRotate && !g_bSeamlessRotate ) )
  6964. {
  6965. const char * sMessage = "server maxed out, retry in a second";
  6966. int iRespLen = 4 + strlen(sMessage);
  6967. NetOutputBuffer_c tOut ( iClientSock );
  6968. tOut.SendInt ( SPHINX_SEARCHD_PROTO );
  6969. tOut.SendWord ( SEARCHD_RETRY );
  6970. tOut.SendWord ( 0 ); // version doesn't matter
  6971. tOut.SendInt ( iRespLen );
  6972. tOut.SendString ( sMessage );
  6973. tOut.Flush ();
  6974. sphWarning ( "maxed out, dismissing client" );
  6975. sphSockClose ( iClientSock );
  6976. if ( g_pStats )
  6977. g_pStats->m_iMaxedOut++;
  6978. break;
  6979. }
  6980. char sClientName[SPH_ADDRESS_SIZE];
  6981. switch ( saStorage.ss_family )
  6982. {
  6983. case AF_INET:
  6984. sphFormatIP ( sClientName, sizeof(sClientName), ((struct sockaddr_in *)&saStorage)->sin_addr.s_addr );
  6985. break;
  6986. case AF_UNIX:
  6987. strncpy ( sClientName, "(local)", sizeof(sClientName) );
  6988. break;
  6989. default:
  6990. sClientName[0] = '\0';
  6991. break;
  6992. }
  6993. // handle the client
  6994. if ( g_bOptConsole || g_bService )
  6995. {
  6996. #if !USE_WINDOWS
  6997. if ( SPH_FDSET_OVERFLOW(iClientSock) )
  6998. iClientSock = dup2 ( iClientSock, iClientFD );
  6999. #endif
  7000. HandleClient ( g_dListeners[i].m_eProto, iClientSock, sClientName, -1 );
  7001. sphSockClose ( iClientSock );
  7002. continue;
  7003. }
  7004. #if !USE_WINDOWS
  7005. int iChildPipe = PipeAndFork ( false, -1 );
  7006. if ( !g_bHeadDaemon )
  7007. {
  7008. // child process, handle client
  7009. if ( SPH_FDSET_OVERFLOW(iClientSock) )
  7010. iClientSock = dup2 ( iClientSock, iClientFD );
  7011. HandleClient ( g_dListeners[i].m_eProto, iClientSock, sClientName, iChildPipe );
  7012. sphSockClose ( iClientSock );
  7013. exit ( 0 );
  7014. } else
  7015. {
  7016. // parent process, continue accept()ing
  7017. sphSockClose ( iClientSock );
  7018. }
  7019. #endif // !USE_WINDOWS
  7020. }
  7021. }
  7022. }
  7023. bool DieCallback ( const char * sMessage )
  7024. {
  7025. sphLogFatal ( "%s", sMessage );
  7026. return false; // caller should not log
  7027. }
  7028. int main ( int argc, char **argv )
  7029. {
  7030. sphSetDieCallback ( DieCallback );
  7031. #if USE_WINDOWS
  7032. int iNameIndex = -1;
  7033. for ( int i=1; i<argc; i++ )
  7034. {
  7035. if ( strcmp ( argv[i], "--ntservice" )==0 )
  7036. g_bService = true;
  7037. if ( strcmp ( argv[i], "--servicename" )==0 && (i+1)<argc )
  7038. {
  7039. iNameIndex = i+1;
  7040. g_sServiceName = argv[iNameIndex];
  7041. }
  7042. }
  7043. if ( g_bService )
  7044. {
  7045. for ( int i=0; i<argc; i++ )
  7046. g_dArgs.Add ( argv[i] );
  7047. if ( iNameIndex>=0 )
  7048. g_sServiceName = g_dArgs[iNameIndex].cstr ();
  7049. SERVICE_TABLE_ENTRY dDispatcherTable[] =
  7050. {
  7051. { (LPSTR) g_sServiceName, (LPSERVICE_MAIN_FUNCTION)ServiceMain },
  7052. { NULL, NULL }
  7053. };
  7054. if ( !StartServiceCtrlDispatcher ( dDispatcherTable ) )
  7055. sphFatal ( "StartServiceCtrlDispatcher() failed: %s", WinErrorInfo() );
  7056. } else
  7057. #endif
  7058. return ServiceMain ( argc, argv );
  7059. }
  7060. //
  7061. // $Id$
  7062. //