ws_workunitsService.cpp 200 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "ws_workunitsService.hpp"
  14. #include "ws_fs.hpp"
  15. #include "jlib.hpp"
  16. #include "jflz.hpp"
  17. #include "daclient.hpp"
  18. #include "dadfs.hpp"
  19. #include "daaudit.hpp"
  20. #include "dautils.hpp"
  21. #include "exception_util.hpp"
  22. #include "wujobq.hpp"
  23. #include "eventqueue.hpp"
  24. #include "fileview.hpp"
  25. #include "hqlerror.hpp"
  26. #include "sacmd.hpp"
  27. #include "wuwebview.hpp"
  28. #include "portlist.h"
  29. #include "dllserver.hpp"
  30. #include "schedulectrl.hpp"
  31. #include "scheduleread.hpp"
  32. #include "dadfs.hpp"
  33. #include "dfuwu.hpp"
  34. #include "thorplugin.hpp"
  35. #include "roxiecontrol.hpp"
  36. #include "deftype.hpp"
  37. #include "thorcommon.hpp"
  38. #include "thorxmlwrite.hpp"
  39. #include "fvdatasource.hpp"
  40. #include "fvresultset.ipp"
  41. #include "ws_wudetails.hpp"
  42. #include "wuerror.hpp"
  43. #include "TpWrapper.hpp"
  44. #include "rtlformat.hpp"
  45. #include "package.h"
  46. #include "build-config.h"
  47. #ifdef _USE_ZLIB
  48. #include "zcrypt.hpp"
  49. #endif
  50. #define ESP_WORKUNIT_DIR "workunits/"
  51. #define WU_SDS_LOCK_TIMEOUT (5*60*1000) // 5 mins
  52. const unsigned CHECK_QUERY_STATUS_THREAD_POOL_SIZE = 25;
  53. const unsigned MAX_ZAP_BUFFER_SIZE = 10000000; //10M
  54. class ExecuteExistingQueryInfo
  55. {
  56. public:
  57. ExecuteExistingQueryInfo(IConstWorkUnit *cw)
  58. {
  59. const char *name = cw->queryJobName();
  60. const char *div = strchr(name, '.');
  61. if (div)
  62. {
  63. queryset.set(name, div-name);
  64. query.set(div+1);
  65. }
  66. }
  67. public:
  68. StringAttr queryset;
  69. StringAttr query;
  70. };
  71. //The ECLWUActionNames[] has to match with the ESPenum ECLWUActions in the ecm file.
  72. static unsigned NumOfECLWUActionNames = 12;
  73. static const char *ECLWUActionNames[] = { "Abort", "Delete", "Deschedule", "Reschedule", "Pause",
  74. "PauseNow", "Protect", "Unprotect", "Restore", "Resume", "SetToFailed", "Archive", nullptr };
  75. class CECLWUActionsEx : public SoapEnumParamNew<CECLWUActions>
  76. {
  77. public:
  78. CECLWUActionsEx() : SoapEnumParamNew<CECLWUActions>() { init("ECLWUActions","string", ECLWUActionNames); }
  79. };
  80. static CECLWUActionsEx eclWUActionType;
  81. void setActionResult(const char* wuid, CECLWUActions action, const char* result, const char* strAction, IArrayOf<IConstWUActionResult>* results)
  82. {
  83. if (!results || !wuid || !*wuid || !result || !*result)
  84. return;
  85. Owned<IEspWUActionResult> res = createWUActionResult("", "");
  86. res->setWuid(wuid);
  87. res->setAction(strAction);
  88. res->setResult(result);
  89. results->append(*res.getClear());
  90. }
  91. bool doAction(IEspContext& context, StringArray& wuids, CECLWUActions action, IProperties* params, IArrayOf<IConstWUActionResult>* results)
  92. {
  93. if (!wuids.length())
  94. return true;
  95. if ((action == CECLWUActions_Restore) || (action == CECLWUActions_Archive))
  96. {
  97. StringBuffer msg;
  98. ForEachItemIn(i, wuids)
  99. {
  100. StringBuffer wuidStr(wuids.item(i));
  101. const char* wuid = wuidStr.trim().str();
  102. if (isEmpty(wuid))
  103. {
  104. msg.appendf("Empty Workunit ID at %u. ", i);
  105. continue;
  106. }
  107. if ((action == CECLWUActions_Archive) && !validateWsWorkunitAccess(context, wuid, SecAccess_Full))
  108. msg.appendf("Access denied for Workunit %s. ", wuid);
  109. }
  110. if (!msg.isEmpty())
  111. throw makeStringException(ECLWATCH_INVALID_INPUT, msg);
  112. Owned<ISashaCommand> cmd = archiveOrRestoreWorkunits(wuids, params, action == CECLWUActions_Archive, false);
  113. ForEachItemIn(idx, wuids)
  114. {
  115. StringBuffer reply;
  116. cmd->getId(idx, reply);
  117. const char* wuid = wuids.item(idx);
  118. if ((action == CECLWUActions_Restore) && !validateWsWorkunitAccess(context, wuid, SecAccess_Full))
  119. reply.appendf("Access denied for Workunit %s. ", wuid);
  120. AuditSystemAccess(context.queryUserId(), true, "%s", reply.str());
  121. }
  122. return true;
  123. }
  124. bool bAllSuccess = true;
  125. const char* strAction = (action < NumOfECLWUActionNames) ? ECLWUActionNames[action] : "Unknown Action";
  126. for(aindex_t i=0; i<wuids.length();i++)
  127. {
  128. StringBuffer wuidStr(wuids.item(i));
  129. const char* wuid = wuidStr.trim().str();
  130. if (isEmpty(wuid))
  131. {
  132. UWARNLOG("Empty Workunit ID");
  133. continue;
  134. }
  135. try
  136. {
  137. if (!looksLikeAWuid(wuid, 'W'))
  138. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuid);
  139. PROGLOG("%s %s", strAction, wuid);
  140. if (action == CECLWUActions_EventDeschedule)
  141. {
  142. if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Full, false)
  143. || !context.validateFeatureAccess(OTHERS_WU_ACCESS, SecAccess_Full, false))
  144. ensureWsWorkunitAccess(context, wuid, SecAccess_Full);
  145. descheduleWorkunit(wuid);
  146. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  147. }
  148. else
  149. {
  150. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  151. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  152. if(!cw)
  153. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid);
  154. if ((action == CECLWUActions_Delete) && (cw->getState() == WUStateWait))
  155. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT,"Cannot delete a workunit which is in a 'Wait' status.");
  156. switch(action)
  157. {
  158. case CECLWUActions_Pause:
  159. {
  160. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  161. WorkunitUpdate wu(&cw->lock());
  162. wu->setAction(WUActionPause);
  163. break;
  164. }
  165. case CECLWUActions_PauseNow:
  166. {
  167. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  168. WorkunitUpdate wu(&cw->lock());
  169. wu->setAction(WUActionPauseNow);
  170. break;
  171. }
  172. case CECLWUActions_Resume:
  173. {
  174. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  175. WorkunitUpdate wu(&cw->lock());
  176. wu->setAction(WUActionResume);
  177. break;
  178. }
  179. case CECLWUActions_Delete:
  180. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  181. {
  182. cw.clear();
  183. factory->deleteWorkUnitEx(wuid, true),
  184. AuditSystemAccess(context.queryUserId(), true, "Deleted %s", wuid);
  185. }
  186. break;
  187. case CECLWUActions_Abort:
  188. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  189. {
  190. if (cw->getState() == WUStateWait)
  191. {
  192. WorkunitUpdate wu(&cw->lock());
  193. wu->deschedule();
  194. wu->setState(WUStateAborted);
  195. }
  196. else
  197. abortWorkUnit(wuid, context.querySecManager(), context.queryUser());
  198. AuditSystemAccess(context.queryUserId(), true, "Aborted %s", wuid);
  199. }
  200. break;
  201. case CECLWUActions_Protect:
  202. case CECLWUActions_Unprotect:
  203. ensureWsWorkunitAccess(context, *cw, SecAccess_Write);
  204. cw->protect((action == CECLWUActions_Protect) ? true:false);
  205. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  206. break;
  207. case CECLWUActions_SetToFailed:
  208. {
  209. ensureWsWorkunitAccess(context, *cw, SecAccess_Write);
  210. WorkunitUpdate wu(&cw->lock());
  211. wu->setState(WUStateFailed);
  212. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  213. }
  214. break;
  215. case CECLWUActions_EventReschedule:
  216. {
  217. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  218. WorkunitUpdate wu(&cw->lock());
  219. wu->schedule();
  220. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  221. }
  222. break;
  223. }
  224. }
  225. PROGLOG("%s %s done", strAction, wuid);
  226. setActionResult(wuid, action, "Success", strAction, results);
  227. }
  228. catch (IException *e)
  229. {
  230. bAllSuccess = false;
  231. StringBuffer eMsg;
  232. StringBuffer failedMsg("Failed: ");
  233. setActionResult(wuid, action, failedMsg.append(e->errorMessage(eMsg)).str(), strAction, results);
  234. OWARNLOG("Failed to %s for workunit: %s, %s", strAction, wuid, eMsg.str());
  235. AuditSystemAccess(context.queryUserId(), false, "Failed to %s %s", strAction, wuid);
  236. e->Release();
  237. continue;
  238. }
  239. catch (...)
  240. {
  241. bAllSuccess = false;
  242. StringBuffer failedMsg;
  243. failedMsg.appendf("Unknown exception");
  244. setActionResult(wuid, action, failedMsg.str(), strAction, results);
  245. IWARNLOG("Failed to %s for workunit: %s, %s", strAction, wuid, failedMsg.str());
  246. AuditSystemAccess(context.queryUserId(), false, "Failed to %s %s", strAction, wuid);
  247. continue;
  248. }
  249. }
  250. int timeToWait = 0;
  251. if (params)
  252. timeToWait = params->getPropInt("BlockTillFinishTimer");
  253. if (timeToWait != 0)
  254. {
  255. for(aindex_t i=0; i<wuids.length();i++)
  256. {
  257. const char* wuid=wuids.item(i);
  258. if (isEmpty(wuid))
  259. continue;
  260. waitForWorkUnitToComplete(wuid, timeToWait);
  261. }
  262. }
  263. return bAllSuccess;
  264. }
  265. bool doProtectWorkunits(IEspContext& context, StringArray& wuids, IArrayOf<IConstWUActionResult>* results)
  266. {
  267. Owned<IProperties> params(createProperties(true));
  268. params->setProp("BlockTillFinishTimer", 0);
  269. return doAction(context, wuids, CECLWUActions_Protect, params, results);
  270. }
  271. bool doUnProtectWorkunits(IEspContext& context, StringArray& wuids, IArrayOf<IConstWUActionResult>* results)
  272. {
  273. Owned<IProperties> params(createProperties(true));
  274. params->setProp("BlockTillFinishTimer", 0);
  275. return doAction(context, wuids, CECLWUActions_Unprotect, params, results);
  276. }
  277. static void checkUpdateQuerysetLibraries()
  278. {
  279. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, WU_SDS_LOCK_TIMEOUT);
  280. if (!globalLock)
  281. return;
  282. IPropertyTree *root = globalLock->queryRoot();
  283. if (!root)
  284. return;
  285. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  286. Owned<IPropertyTreeIterator> querySets = root->getElements("QuerySet");
  287. ForEach(*querySets)
  288. {
  289. IPropertyTree &querySet = querySets->query();
  290. if (querySet.hasProp("@updatedLibraries")) //only need to do this once, then publish and copy will keep up to date
  291. continue;
  292. Owned<IPropertyTreeIterator> queries = querySet.getElements("Query");
  293. ForEach(*queries)
  294. {
  295. IPropertyTree &query = queries->query();
  296. if (query.hasProp("@libCount"))
  297. continue;
  298. const char *wuid = query.queryProp("@wuid");
  299. if (!wuid || !*wuid)
  300. continue;
  301. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  302. if (!cw)
  303. continue;
  304. checkAddLibrariesToQueryEntry(&query, cw);
  305. }
  306. querySet.setPropBool("@updatedLibraries", true);
  307. }
  308. }
  309. void CWsWorkunitsEx::init(IPropertyTree *cfg, const char *process, const char *service)
  310. {
  311. if (!daliClientActive())
  312. {
  313. OERRLOG("No Dali Connection Active.");
  314. throw MakeStringException(-1, "No Dali Connection Active. Please Specify a Dali to connect to in you configuration file");
  315. }
  316. DBGLOG("Initializing %s service [process = %s]", service, process);
  317. checkUpdateQuerysetLibraries();
  318. refreshValidClusters();
  319. daliServers.set(cfg->queryProp("Software/EspProcess/@daliServers"));
  320. const char *computer = cfg->queryProp("Software/EspProcess/@computer");
  321. if (daliServers.isEmpty() || !computer || streq(computer, "localhost")) //otherwise can't assume environment "." netAddresses are the same as my address
  322. queryHostIP().getIpText(envLocalAddress);
  323. else
  324. {
  325. //a bit weird, but other netAddresses in the environment are not the same localhost as this server
  326. //use the address of the DALI
  327. const char *finger = daliServers.get();
  328. while (*finger && !strchr(":;,", *finger))
  329. envLocalAddress.append(*finger++);
  330. }
  331. awusCacheMinutes = AWUS_CACHE_MIN_DEFAULT;
  332. VStringBuffer xpath("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/AWUsCacheMinutes", process, service);
  333. cfg->getPropInt(xpath.str(), awusCacheMinutes);
  334. xpath.setf("Software/EspProcess[@name=\"%s\"]/@PageCacheTimeoutSeconds", process);
  335. if (cfg->hasProp(xpath.str()))
  336. setPageCacheTimeoutMilliSeconds(cfg->getPropInt(xpath.str()));
  337. xpath.setf("Software/EspProcess[@name=\"%s\"]/@MaxPageCacheItems", process);
  338. if (cfg->hasProp(xpath.str()))
  339. setMaxPageCacheItems(cfg->getPropInt(xpath.str()));
  340. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/serverForArchivedECLWU/@netAddress", process, service);
  341. if (cfg->hasProp(xpath.str()))
  342. {
  343. sashaServerIp.set(cfg->queryProp(xpath.str()));
  344. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/serverForArchivedECLWU/@port", process, service);
  345. sashaServerPort = cfg->getPropInt(xpath.str(), DEFAULT_SASHA_PORT);
  346. }
  347. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/ThorSlaveLogThreadPoolSize", process, service);
  348. thorSlaveLogThreadPoolSize = cfg->getPropInt(xpath, THOR_SLAVE_LOG_THREAD_POOL_SIZE);
  349. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/ZAPEmail", process, service);
  350. IPropertyTree *zapEmail = cfg->queryPropTree(xpath.str());
  351. if (zapEmail)
  352. {
  353. zapEmailTo = zapEmail->queryProp("@to");
  354. if (zapEmailTo.isEmpty())
  355. throw MakeStringException(-1, "ZAPEmail: EmailTo not specified.");
  356. zapEmailFrom = zapEmail->queryProp("@from");
  357. if (zapEmailFrom.isEmpty())
  358. throw MakeStringException(-1, "ZAPEmail: EmailFrom not specified.");
  359. zapEmailServer = zapEmail->queryProp("@serverURL");
  360. if (zapEmailServer.isEmpty())
  361. throw MakeStringException(-1, "ZAPEmail: EmailServer not specified.");
  362. zapEmailServerPort = zapEmail->getPropInt("@serverPort", WUDEFAULT_ZAPEMAILSERVER_PORT);
  363. zapEmailMaxAttachmentSize = zapEmail->getPropInt("@maxAttachmentSize", MAX_ZAP_BUFFER_SIZE);
  364. }
  365. maxRequestEntityLength = cfg->getPropInt("Software[1]/EspProcess[1]/EspProtocol[@type='http_protocol'][1]/@maxRequestEntityLength");
  366. directories.set(cfg->queryPropTree("Software/Directories"));
  367. const char *name = cfg->queryProp("Software/EspProcess/@name");
  368. getConfigurationDirectory(directories, "query", "esp", name ? name : "esp", queryDirectory);
  369. recursiveCreateDirectory(queryDirectory.str());
  370. dataCache.setown(new DataCache(DATA_SIZE));
  371. archivedWuCache.setown(new ArchivedWuCache(AWUS_CACHE_SIZE));
  372. wuArchiveCache.setown(new WUArchiveCache(WUARCHIVE_CACHE_SIZE));
  373. //Create a folder for temporarily holding gzip files by WUResultBin()
  374. Owned<IFile> tmpdir = createIFile(TEMPZIPDIR);
  375. if(!tmpdir->exists())
  376. tmpdir->createDirectory();
  377. recursiveCreateDirectory(ESP_WORKUNIT_DIR);
  378. m_sched.start();
  379. filesInUse.subscribe();
  380. //Start thread pool
  381. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/ClusterQueryStateThreadPoolSize", process, service);
  382. Owned<CClusterQueryStateThreadFactory> threadFactory = new CClusterQueryStateThreadFactory();
  383. clusterQueryStatePool.setown(createThreadPool("CheckAndSetClusterQueryState Thread Pool", threadFactory, NULL,
  384. cfg->getPropInt(xpath.str(), CHECK_QUERY_STATUS_THREAD_POOL_SIZE)));
  385. }
  386. void CWsWorkunitsEx::refreshValidClusters()
  387. {
  388. validClusters.kill();
  389. #ifdef _CONTAINERIZED
  390. // discovered from generated cluster names
  391. Owned<IPropertyTreeIterator> iter = queryComponentConfig().getElements("queues");
  392. ForEach(*iter)
  393. {
  394. IPropertyTree &queue = iter->query();
  395. const char *qName = queue.queryProp("@name");
  396. bool* found = validClusters.getValue(qName);
  397. if (!found || !*found)
  398. {
  399. validClusters.setValue(qName, true);
  400. PROGLOG("adding valid cluster: %s", qName);
  401. }
  402. }
  403. #else
  404. Owned<IStringIterator> it = getTargetClusters(NULL, NULL);
  405. ForEach(*it)
  406. {
  407. SCMStringBuffer s;
  408. IStringVal &val = it->str(s);
  409. bool* found = validClusters.getValue(val.str());
  410. if (!found || !*found)
  411. validClusters.setValue(val.str(), true);
  412. }
  413. #endif
  414. }
  415. bool CWsWorkunitsEx::isValidCluster(const char *cluster)
  416. {
  417. if (!cluster || !*cluster)
  418. return false;
  419. CriticalBlock block(crit);
  420. bool* found = validClusters.getValue(cluster);
  421. if (found && *found)
  422. return true;
  423. if (validateTargetClusterName(cluster))
  424. {
  425. refreshValidClusters();
  426. return true;
  427. }
  428. return false;
  429. }
  430. bool CWsWorkunitsEx::onWUCreate(IEspContext &context, IEspWUCreateRequest &req, IEspWUCreateResponse &resp)
  431. {
  432. try
  433. {
  434. ensureWsCreateWorkunitAccess(context);
  435. NewWsWorkunit wu(context);
  436. resp.updateWorkunit().setWuid(wu->queryWuid());
  437. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wu->queryWuid());
  438. }
  439. catch(IException* e)
  440. {
  441. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  442. }
  443. return true;
  444. }
  445. bool origValueChanged(const char *newValue, const char *origValue, StringBuffer &s, bool nillable)
  446. {
  447. if (!nillable && isEmpty(newValue))
  448. return false;
  449. if(newValue && origValue)
  450. {
  451. if (!streq(origValue, newValue))
  452. {
  453. s.append(newValue).trim();
  454. return true;
  455. }
  456. return false;
  457. }
  458. if (newValue)
  459. {
  460. s.append(newValue).trim();
  461. return true;
  462. }
  463. return (origValue!=NULL);
  464. }
  465. bool CWsWorkunitsEx::onWUUpdate(IEspContext &context, IEspWUUpdateRequest &req, IEspWUUpdateResponse &resp)
  466. {
  467. try
  468. {
  469. StringBuffer wuid(req.getWuid());
  470. WsWuHelpers::checkAndTrimWorkunit("WUUpdate", wuid);
  471. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Write);
  472. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  473. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  474. if(!cw)
  475. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  476. PROGLOG("WUUpdate: %s", wuid.str());
  477. if(req.getProtected() != req.getProtectedOrig())
  478. {
  479. cw->protect(req.getProtected());
  480. cw.clear();
  481. cw.setown(factory->openWorkUnit(wuid.str()));
  482. if(!cw)
  483. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  484. }
  485. if ((req.getState() == WUStateRunning)||(req.getState() == WUStateDebugPaused)||(req.getState() == WUStateDebugRunning))
  486. {
  487. WsWuInfo winfo(context, cw);
  488. winfo.getInfo(resp.updateWorkunit(), WUINFO_All);
  489. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
  490. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  491. return true;
  492. }
  493. WorkunitUpdate wu(&cw->lock());
  494. if(!req.getState_isNull() && (req.getStateOrig_isNull() || req.getState() != req.getStateOrig()))
  495. {
  496. if (!req.getStateOrig_isNull() && cw->getState() != (WUState) req.getStateOrig())
  497. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Cannot update workunit %s because its state has been changed internally. Please refresh the page and try again.", wuid.str());
  498. WUState state = (WUState) req.getState();
  499. if(state < WUStateSize)
  500. wu->setState(state);
  501. }
  502. StringBuffer s;
  503. if (origValueChanged(req.getJobname(), req.getJobnameOrig(), s))
  504. wu->setJobName(s.trim().str());
  505. if (origValueChanged(req.getDescription(), req.getDescriptionOrig(), s.clear()))
  506. wu->setDebugValue("description", (req.getDescription() && *req.getDescription()) ? s.trim().str() : NULL, true);
  507. double version = context.getClientVersion();
  508. if (version > 1.04)
  509. {
  510. if (origValueChanged(req.getClusterSelection(), req.getClusterOrig(), s.clear(), false))
  511. {
  512. if (!isValidCluster(s.str()))
  513. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", s.str());
  514. if (req.getState() == WUStateBlocked)
  515. switchWorkUnitQueue(wu.get(), s.str());
  516. else if ((req.getState() != WUStateSubmitted) && (req.getState() != WUStateRunning) && (req.getState() != WUStateDebugPaused) && (req.getState() != WUStateDebugRunning))
  517. wu->setClusterName(s.str());
  518. }
  519. }
  520. WsWuHelpers::setXmlParameters(wu, req.getXmlParams(), (req.getAction()==WUActionExecuteExisting));
  521. if (notEmpty(req.getQueryText()))
  522. {
  523. Owned<IWUQuery> query=wu->updateQuery();
  524. query->setQueryText(req.getQueryText());
  525. }
  526. if (version > 1.34 && notEmpty(req.getQueryMainDefinition()))
  527. {
  528. Owned<IWUQuery> query=wu->updateQuery();
  529. query->setQueryMainDefinition(req.getQueryMainDefinition());
  530. }
  531. if (!req.getResultLimit_isNull())
  532. wu->setResultLimit(req.getResultLimit());
  533. if (!req.getAction_isNull())
  534. {
  535. WUAction action = (WUAction) req.getAction();
  536. if(action < WUActionSize)
  537. wu->setAction(action);
  538. }
  539. if (!req.getPriorityClass_isNull())
  540. {
  541. WUPriorityClass priority = (WUPriorityClass) req.getPriorityClass();
  542. if(priority<PriorityClassSize)
  543. wu->setPriority(priority);
  544. }
  545. if (!req.getPriorityLevel_isNull())
  546. wu->setPriorityLevel(req.getPriorityLevel());
  547. if (origValueChanged(req.getScope(), req.getScopeOrig(), s.clear(), false))
  548. wu->setWuScope(s.str());
  549. ForEachItemIn(di, req.getDebugValues())
  550. {
  551. IConstDebugValue& item=req.getDebugValues().item(di);
  552. const char *debugName = item.getName();
  553. if (notEmpty(debugName))
  554. {
  555. StringBuffer expanded;
  556. if (*debugName=='-')
  557. debugName=expanded.append("eclcc").append(debugName).str();
  558. wu->setDebugValue(debugName, item.getValue(), true);
  559. }
  560. }
  561. ForEachItemIn(ai, req.getApplicationValues())
  562. {
  563. IConstApplicationValue& item=req.getApplicationValues().item(ai);
  564. if(notEmpty(item.getApplication()) && notEmpty(item.getName()))
  565. wu->setApplicationValue(item.getApplication(), item.getName(), item.getValue(), true);
  566. }
  567. wu->commit();
  568. wu.clear();
  569. WsWuInfo winfo(context, cw);
  570. winfo.getInfo(resp.updateWorkunit(), WUINFO_All);
  571. StringBuffer thorSlaveIP;
  572. if (version > 1.24 && notEmpty(req.getThorSlaveIP()))
  573. thorSlaveIP = req.getThorSlaveIP();
  574. if (thorSlaveIP.length() > 0)
  575. {
  576. StringBuffer url;
  577. url.appendf("/WsWorkunits/WUInfo?Wuid=%s&ThorSlaveIP=%s", wuid.str(), thorSlaveIP.str());
  578. resp.setRedirectUrl(url.str());
  579. }
  580. else
  581. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
  582. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  583. }
  584. catch(IException* e)
  585. {
  586. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  587. }
  588. return true;
  589. }
  590. bool CWsWorkunitsEx::onWUCreateAndUpdate(IEspContext &context, IEspWUUpdateRequest &req, IEspWUUpdateResponse &resp)
  591. {
  592. try
  593. {
  594. const char* wuid = req.getWuid();
  595. if (!wuid || !*wuid)
  596. {
  597. ensureWsCreateWorkunitAccess(context);
  598. NewWsWorkunit wu(context);
  599. req.setWuid(wu->queryWuid());
  600. }
  601. }
  602. catch(IException* e)
  603. {
  604. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  605. }
  606. return onWUUpdate(context, req, resp);
  607. }
  608. static inline StringBuffer &appendUrlParameter(StringBuffer &url, const char *name, const char *value, bool &first)
  609. {
  610. if (notEmpty(value))
  611. {
  612. url.append(first ? '?' : '&').append(name).append('=').append(value);
  613. first=false;
  614. }
  615. return url;
  616. }
  617. bool CWsWorkunitsEx::onWUAction(IEspContext &context, IEspWUActionRequest &req, IEspWUActionResponse &resp)
  618. {
  619. try
  620. {
  621. CECLWUActions action;
  622. double version = context.getClientVersion();
  623. if (version >= 1.57)
  624. action = req.getWUActionType();
  625. else
  626. action = eclWUActionType.toEnum(req.getActionType());
  627. if (action == ECLWUActions_Undefined)
  628. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Action not defined.");
  629. Owned<IProperties> params = createProperties(true);
  630. params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
  631. if (((action == CECLWUActions_Restore) || (action == CECLWUActions_Archive)) && !sashaServerIp.isEmpty())
  632. {
  633. params->setProp("sashaServerIP", sashaServerIp.get());
  634. params->setProp("sashaServerPort", sashaServerPort);
  635. }
  636. IArrayOf<IConstWUActionResult> results;
  637. if (doAction(context, req.getWuids(), action, params, &results) && (action != CECLWUActions_Delete) && checkRedirect(context))
  638. {
  639. StringBuffer redirect;
  640. if(req.getPageFrom() && strieq(req.getPageFrom(), "wuid"))
  641. redirect.append("/WsWorkunits/WUInfo?Wuid=").append(req.getWuids().item(0));
  642. else if (req.getPageFrom() && strieq(req.getPageFrom(), "scheduler"))
  643. {
  644. redirect.set("/WsWorkunits/WUShowScheduled");
  645. bool first=true;
  646. appendUrlParameter(redirect, "Cluster", req.getEventServer(), first);
  647. appendUrlParameter(redirect, "EventName", req.getEventName(), first);
  648. }
  649. else
  650. {
  651. redirect.append("/WsWorkunits/WUQuery");
  652. bool first=true;
  653. appendUrlParameter(redirect, "PageSize", req.getPageSize(), first);
  654. appendUrlParameter(redirect, "PageStartFrom", req.getCurrentPage(), first);
  655. appendUrlParameter(redirect, "Sortby", req.getSortby(), first);
  656. appendUrlParameter(redirect, "Descending", req.getDescending() ? "1" : "0", first);
  657. appendUrlParameter(redirect, "State", req.getState(), first);
  658. appendUrlParameter(redirect, "Cluster", req.getCluster(), first);
  659. appendUrlParameter(redirect, "Owner", req.getOwner(), first);
  660. appendUrlParameter(redirect, "StartDate", req.getStartDate(), first);
  661. appendUrlParameter(redirect, "EndDate", req.getEndDate(), first);
  662. appendUrlParameter(redirect, "ECL", req.getECL(), first);
  663. appendUrlParameter(redirect, "Jobname", req.getJobname(), first);
  664. }
  665. resp.setRedirectUrl(redirect.str());
  666. }
  667. else
  668. resp.setActionResults(results);
  669. }
  670. catch(IException* e)
  671. {
  672. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  673. }
  674. return true;
  675. }
  676. bool CWsWorkunitsEx::onWUDelete(IEspContext &context, IEspWUDeleteRequest &req, IEspWUDeleteResponse &resp)
  677. {
  678. try
  679. {
  680. IArrayOf<IConstWUActionResult> results;
  681. Owned<IProperties> params = createProperties(true);
  682. params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
  683. if (!doAction(context,req.getWuids(), CECLWUActions_Delete, params, &results))
  684. resp.setActionResults(results);
  685. }
  686. catch(IException* e)
  687. {
  688. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  689. }
  690. return true;
  691. }
  692. bool CWsWorkunitsEx::onWUAbort(IEspContext &context, IEspWUAbortRequest &req, IEspWUAbortResponse &resp)
  693. {
  694. try
  695. {
  696. IArrayOf<IConstWUActionResult> results;
  697. Owned<IProperties> params = createProperties(true);
  698. params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
  699. if (!doAction(context,req.getWuids(), CECLWUActions_Abort, params, &results))
  700. resp.setActionResults(results);
  701. }
  702. catch(IException* e)
  703. {
  704. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  705. }
  706. return true;
  707. }
  708. bool CWsWorkunitsEx::onWUProtect(IEspContext &context, IEspWUProtectRequest &req, IEspWUProtectResponse &resp)\
  709. {
  710. try
  711. {
  712. IArrayOf<IConstWUActionResult> results;
  713. Owned<IProperties> params(createProperties(true));
  714. params->setProp("BlockTillFinishTimer", 0);
  715. CECLWUActions action = req.getProtect() ? CECLWUActions_Protect : CECLWUActions_Unprotect;
  716. if (!doAction(context,req.getWuids(), action, params, &results))
  717. resp.setActionResults(results);
  718. }
  719. catch(IException* e)
  720. {
  721. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  722. }
  723. return true;
  724. }
  725. bool CWsWorkunitsEx::onWUResubmit(IEspContext &context, IEspWUResubmitRequest &req, IEspWUResubmitResponse &resp)
  726. {
  727. try
  728. {
  729. Owned<IMultiException> me = MakeMultiException();
  730. StringAttr wuid;
  731. StringArray wuids;
  732. double version = context.getClientVersion();
  733. IArrayOf<IEspResubmittedWU> resubmittedWUs;
  734. for(aindex_t i=0; i<req.getWuids().length();i++)
  735. {
  736. StringBuffer requestWuid(req.getWuids().item(i));
  737. WsWuHelpers::checkAndTrimWorkunit("WUResubmit", requestWuid);
  738. ensureWsWorkunitAccess(context, requestWuid.str(), SecAccess_Write);
  739. PROGLOG("WUResubmit: %s", requestWuid.str());
  740. wuid.set(requestWuid.str());
  741. try
  742. {
  743. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  744. if(req.getCloneWorkunit() || req.getRecompile())
  745. {
  746. Owned<IConstWorkUnit> src(factory->openWorkUnit(wuid.str()));
  747. NewWsWorkunit wu(factory, context);
  748. wuid.set(wu->queryWuid());
  749. queryExtendedWU(wu)->copyWorkUnit(src, false, false);
  750. }
  751. wuids.append(wuid.str());
  752. Owned<IConstWorkUnit> cw(factory->openWorkUnit(wuid.str()));
  753. if(!cw)
  754. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  755. WsWuHelpers::submitWsWorkunit(context, cw, NULL, NULL, 0, req.getRecompile(), req.getResetWorkflow(), false);
  756. if (version < 1.40)
  757. continue;
  758. Owned<IEspResubmittedWU> resubmittedWU = createResubmittedWU();
  759. resubmittedWU->setWUID(wuid.str());
  760. if (!streq(requestWuid.str(), wuid.str()))
  761. resubmittedWU->setParentWUID(requestWuid.str());
  762. resubmittedWUs.append(*resubmittedWU.getClear());
  763. }
  764. catch (IException *E)
  765. {
  766. me->append(*E);
  767. }
  768. catch (...)
  769. {
  770. me->append(*MakeStringException(0,"Unknown exception submitting %s",wuid.str()));
  771. }
  772. }
  773. if(me->ordinality())
  774. throw me.getLink();
  775. int timeToWait = req.getBlockTillFinishTimer();
  776. if (timeToWait != 0)
  777. {
  778. for(aindex_t i=0; i<wuids.length(); i++)
  779. waitForWorkUnitToComplete(wuids.item(i), timeToWait);
  780. }
  781. if (version >= 1.40)
  782. resp.setWUs(resubmittedWUs);
  783. if(wuids.length()==1)
  784. {
  785. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuids.item(0)));
  786. }
  787. }
  788. catch(IException* e)
  789. {
  790. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  791. }
  792. return true;
  793. }
  794. bool CWsWorkunitsEx::onWUPushEvent(IEspContext &context, IEspWUPushEventRequest &req, IEspWUPushEventResponse &resp)
  795. {
  796. try
  797. {
  798. const char *name = req.getEventName();
  799. const char *text = req.getEventText();
  800. const char *target = NULL;
  801. if (notEmpty(name) && notEmpty(text))
  802. {
  803. PROGLOG("WUPushEvent: EventName %s, EventText %s", name, text);
  804. Owned<IScheduleEventPusher> pusher(getScheduleEventPusher());
  805. pusher->push(name, text, target);
  806. StringBuffer redirect("/WsWorkunits/WUShowScheduled");
  807. bool first=true;
  808. appendUrlParameter(redirect, "PushEventName", name, first);
  809. appendUrlParameter(redirect, "PushEventText", text, first);
  810. resp.setRedirectUrl(redirect.str());
  811. return true;
  812. }
  813. }
  814. catch(IException* e)
  815. {
  816. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  817. }
  818. return false;
  819. }
  820. bool CWsWorkunitsEx::onWUSchedule(IEspContext &context, IEspWUScheduleRequest &req, IEspWUScheduleResponse &resp)
  821. {
  822. try
  823. {
  824. StringBuffer wuid(req.getWuid());
  825. WsWuHelpers::checkAndTrimWorkunit("WUSchedule", wuid);
  826. const char* cluster = req.getCluster();
  827. if (isEmpty(cluster))
  828. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No Cluster defined.");
  829. if (!isValidCluster(cluster))
  830. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
  831. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  832. WorkunitUpdate wu(factory->updateWorkUnit(wuid.str()));
  833. ensureWsWorkunitAccess(context, *wu.get(), SecAccess_Write);
  834. switch(wu->getState())
  835. {
  836. case WUStateDebugPaused:
  837. case WUStateDebugRunning:
  838. case WUStateRunning:
  839. case WUStateAborting:
  840. case WUStateBlocked:
  841. throw MakeStringException(ECLWATCH_CANNOT_SCHEDULE_WORKUNIT, "Cannot schedule the workunit. Workunit state is '%s'.", wu->queryStateDesc());
  842. }
  843. PROGLOG("WUSchedule: %s", wuid.str());
  844. wu->clearExceptions();
  845. wu->setClusterName(cluster);
  846. if (notEmpty(req.getWhen()))
  847. {
  848. WsWuDateTime dt;
  849. dt.setString(req.getWhen());
  850. wu->setTimeScheduled(dt);
  851. }
  852. if(notEmpty(req.getSnapshot()))
  853. wu->setSnapshot(req.getSnapshot());
  854. wu->setState(WUStateScheduled);
  855. if (req.getMaxRunTime())
  856. wu->setDebugValueInt("maxRunTime", req.getMaxRunTime(), true);
  857. AuditSystemAccess(context.queryUserId(), true, "Scheduled %s", wuid.str());
  858. }
  859. catch(IException* e)
  860. {
  861. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  862. }
  863. return true;
  864. }
  865. bool CWsWorkunitsEx::onWUSubmit(IEspContext &context, IEspWUSubmitRequest &req, IEspWUSubmitResponse &resp)
  866. {
  867. try
  868. {
  869. StringBuffer wuid(req.getWuid());
  870. WsWuHelpers::checkAndTrimWorkunit("WUSubmit", wuid);
  871. const char *cluster = req.getCluster();
  872. if (isEmpty(cluster))
  873. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No Cluster defined.");
  874. if (!isValidCluster(cluster))
  875. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
  876. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  877. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  878. if(!cw)
  879. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  880. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  881. if (cw->getAction()==WUActionExecuteExisting)
  882. {
  883. ExecuteExistingQueryInfo info(cw);
  884. if (info.queryset.isEmpty() || info.query.isEmpty())
  885. {
  886. WorkunitUpdate wu(&cw->lock());
  887. throw WsWuHelpers::noteException(wu, MakeStringException(ECLWATCH_INVALID_INPUT,"Queryset and/or query not specified"));
  888. }
  889. WsWuHelpers::runWsWuQuery(context, cw, info.queryset.str(), info.query.str(), cluster, NULL);
  890. }
  891. else
  892. WsWuHelpers::submitWsWorkunit(context, cw, cluster, req.getSnapshot(), req.getMaxRunTime(), true, false, false);
  893. PROGLOG("WUSubmit: %s", wuid.str());
  894. if (req.getBlockTillFinishTimer() != 0)
  895. waitForWorkUnitToComplete(wuid.str(), req.getBlockTillFinishTimer());
  896. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
  897. }
  898. catch(IException* e)
  899. {
  900. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  901. }
  902. return true;
  903. }
  904. ErrorSeverity checkGetExceptionSeverity(CWUExceptionSeverity severity)
  905. {
  906. switch (severity)
  907. {
  908. case CWUExceptionSeverity_INFO:
  909. return SeverityInformation;
  910. case CWUExceptionSeverity_WARNING:
  911. return SeverityWarning;
  912. case CWUExceptionSeverity_ERROR:
  913. return SeverityError;
  914. case CWUExceptionSeverity_ALERT:
  915. return SeverityAlert;
  916. }
  917. throw MakeStringExceptionDirect(ECLWATCH_INVALID_INPUT,"invalid exception severity");
  918. }
  919. bool CWsWorkunitsEx::onWURun(IEspContext &context, IEspWURunRequest &req, IEspWURunResponse &resp)
  920. {
  921. try
  922. {
  923. const char *cluster = req.getCluster();
  924. if (notEmpty(cluster) && !isValidCluster(cluster))
  925. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
  926. StringBuffer wuidStr(req.getWuid());
  927. const char* runWuid = wuidStr.trim().str();
  928. StringBuffer wuid;
  929. ErrorSeverity severity = checkGetExceptionSeverity(req.getExceptionSeverity());
  930. if (runWuid && *runWuid)
  931. {
  932. if (!looksLikeAWuid(runWuid, 'W'))
  933. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", runWuid);
  934. ensureWsWorkunitAccess(context, runWuid, SecAccess_Full);
  935. PROGLOG("WURun: %s", runWuid);
  936. if (req.getCloneWorkunit())
  937. WsWuHelpers::runWsWorkunit(context, wuid, runWuid, cluster, req.getInput(), &req.getVariables(),
  938. &req.getDebugValues(), &req.getApplicationValues());
  939. else
  940. {
  941. WsWuHelpers::submitWsWorkunit(context, runWuid, cluster, NULL, 0, false, true, true, req.getInput(),
  942. &req.getVariables(), &req.getDebugValues(), &req.getApplicationValues());
  943. wuid.set(runWuid);
  944. }
  945. }
  946. else if (notEmpty(req.getQuerySet()) && notEmpty(req.getQuery()))
  947. {
  948. PROGLOG("WURun: QuerySet %s, Query %s", req.getQuerySet(), req.getQuery());
  949. WsWuHelpers::runWsWuQuery(context, wuid, req.getQuerySet(), req.getQuery(), cluster, req.getInput(),
  950. &req.getApplicationValues());
  951. }
  952. else
  953. throw MakeStringException(ECLWATCH_MISSING_PARAMS,"Workunit or Query required");
  954. int timeToWait = req.getWait();
  955. if (timeToWait != 0)
  956. waitForWorkUnitToComplete(wuid.str(), timeToWait);
  957. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  958. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  959. if (!cw)
  960. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.", wuid.str());
  961. resp.setState(cw->queryStateDesc());
  962. resp.setWuid(wuid.str());
  963. switch (cw->getState())
  964. {
  965. case WUStateCompleted:
  966. case WUStateFailed:
  967. case WUStateUnknown:
  968. {
  969. SCMStringBuffer result;
  970. unsigned flags = WorkUnitXML_SeverityTags;
  971. if (req.getNoRootTag())
  972. flags |= WorkUnitXML_NoRoot;
  973. getFullWorkUnitResultsXML(context.queryUserId(), context.queryPassword(), cw.get(), result, flags, severity);
  974. resp.setResults(result.str());
  975. break;
  976. }
  977. default:
  978. break;
  979. }
  980. }
  981. catch(IException* e)
  982. {
  983. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  984. }
  985. return true;
  986. }
  987. bool CWsWorkunitsEx::onWUFullResult(IEspContext &context, IEspWUFullResultRequest &req, IEspWUFullResultResponse &resp)
  988. {
  989. try
  990. {
  991. StringBuffer wuid(req.getWuid());
  992. WsWuHelpers::checkAndTrimWorkunit("WUFullResult", wuid);
  993. ErrorSeverity severity = checkGetExceptionSeverity(req.getExceptionSeverity());
  994. if (!wuid.length())
  995. throw MakeStringException(ECLWATCH_MISSING_PARAMS,"Workunit or Query required");
  996. if (!looksLikeAWuid(wuid, 'W'))
  997. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuid.str());
  998. PROGLOG("WUFullResults: %s", wuid.str());
  999. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1000. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  1001. if (!cw)
  1002. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.", wuid.str());
  1003. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  1004. resp.setWuid(wuid.str());
  1005. switch (cw->getState())
  1006. {
  1007. case WUStateCompleted:
  1008. case WUStateFailed:
  1009. case WUStateUnknown:
  1010. {
  1011. SCMStringBuffer result;
  1012. unsigned flags = WorkUnitXML_SeverityTags;
  1013. if (req.getNoRootTag())
  1014. flags |= WorkUnitXML_NoRoot;
  1015. if (context.getResponseFormat()==ESPSerializationJSON)
  1016. getFullWorkUnitResultsJSON(context.queryUserId(), context.queryPassword(), cw.get(), result, flags, severity);
  1017. else
  1018. getFullWorkUnitResultsXML(context.queryUserId(), context.queryPassword(), cw.get(), result, flags, severity);
  1019. resp.setResults(result.str());
  1020. break;
  1021. }
  1022. default:
  1023. throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT, "Cannot get results Workunit %s %s.", wuid.str(), getWorkunitStateStr(cw->getState()));
  1024. }
  1025. }
  1026. catch(IException* e)
  1027. {
  1028. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1029. }
  1030. return true;
  1031. }
  1032. bool CWsWorkunitsEx::onWUWaitCompiled(IEspContext &context, IEspWUWaitRequest &req, IEspWUWaitResponse &resp)
  1033. {
  1034. try
  1035. {
  1036. StringBuffer wuid(req.getWuid());
  1037. WsWuHelpers::checkAndTrimWorkunit("WUWaitCompiled", wuid);
  1038. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Full);
  1039. PROGLOG("WUWaitCompiled: %s", wuid.str());
  1040. secWaitForWorkUnitToCompile(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getWait());
  1041. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1042. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  1043. if(!cw)
  1044. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  1045. resp.setStateID(cw->getState());
  1046. }
  1047. catch(IException* e)
  1048. {
  1049. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1050. }
  1051. return true;
  1052. }
  1053. bool CWsWorkunitsEx::onWUWaitComplete(IEspContext &context, IEspWUWaitRequest &req, IEspWUWaitResponse &resp)
  1054. {
  1055. try
  1056. {
  1057. StringBuffer wuid(req.getWuid());
  1058. WsWuHelpers::checkAndTrimWorkunit("WUWaitComplete", wuid);
  1059. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Full);
  1060. PROGLOG("WUWaitComplete: %s", wuid.str());
  1061. std::list<WUState> expectedStates;
  1062. if (req.getReturnOnWait())
  1063. expectedStates.push_back(WUStateWait);
  1064. resp.setStateID(secWaitForWorkUnitToComplete(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getWait(), expectedStates));
  1065. }
  1066. catch(IException* e)
  1067. {
  1068. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1069. }
  1070. return true;
  1071. }
  1072. bool CWsWorkunitsEx::onWUCDebug(IEspContext &context, IEspWUDebugRequest &req, IEspWUDebugResponse &resp)
  1073. {
  1074. try
  1075. {
  1076. StringBuffer wuid(req.getWuid());
  1077. WsWuHelpers::checkAndTrimWorkunit("WUCDebug", wuid);
  1078. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Full);
  1079. PROGLOG("WUCDebug: %s", wuid.str());
  1080. StringBuffer result;
  1081. secDebugWorkunit(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getCommand(), result);
  1082. resp.setResult(result);
  1083. }
  1084. catch(IException* e)
  1085. {
  1086. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1087. }
  1088. return true;
  1089. }
  1090. bool CWsWorkunitsEx::onWUSyntaxCheckECL(IEspContext &context, IEspWUSyntaxCheckRequest &req, IEspWUSyntaxCheckResponse &resp)
  1091. {
  1092. try
  1093. {
  1094. ensureWsCreateWorkunitAccess(context);
  1095. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1096. NewWsWorkunit wu(factory, context);
  1097. wu->setAction(WUActionCheck);
  1098. if(notEmpty(req.getModuleName()) && notEmpty(req.getAttributeName()))
  1099. {
  1100. wu->setApplicationValue("SyntaxCheck", "ModuleName", req.getModuleName(), true);
  1101. wu->setApplicationValue("SyntaxCheck", "AttributeName", req.getAttributeName(), true);
  1102. }
  1103. ForEachItemIn(di, req.getDebugValues())
  1104. {
  1105. IConstDebugValue& item=req.getDebugValues().item(di);
  1106. const char *debugName = item.getName();
  1107. if (notEmpty(debugName))
  1108. {
  1109. StringBuffer expanded;
  1110. if (*debugName=='-')
  1111. debugName=expanded.append("eclcc").append(debugName).str();
  1112. wu->setDebugValue(debugName, item.getValue(), true);
  1113. }
  1114. }
  1115. wu.setQueryText(req.getECL());
  1116. StringAttr wuid(wu->queryWuid()); // NB queryWuid() not valid after workunit,clear()
  1117. wu->commit();
  1118. wu.clear();
  1119. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
  1120. waitForWorkUnitToComplete(wuid.str(), req.getTimeToWait());
  1121. Owned<IConstWorkUnit> cw(factory->openWorkUnit(wuid.str()));
  1122. WsWUExceptions errors(*cw);
  1123. resp.setErrors(errors);
  1124. StringBuffer msg;
  1125. WUState st = cw->getState();
  1126. cw.clear();
  1127. switch (st)
  1128. {
  1129. case WUStateAborted:
  1130. case WUStateCompleted:
  1131. case WUStateFailed:
  1132. factory->deleteWorkUnitEx(wuid.str(), true);
  1133. break;
  1134. default:
  1135. abortWorkUnit(wuid.str(), context.querySecManager(), context.queryUser());
  1136. if (!factory->deleteWorkUnit(wuid.str()))
  1137. {
  1138. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT,
  1139. "WUSyntaxCheckECL has timed out. Workunit %s cannot be deleted now. You may delete it when its status changes.", wuid.str());
  1140. }
  1141. if (context.getClientVersion() < 1.57)
  1142. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "WUSyntaxCheckECL has timed out.");
  1143. resp.setMessage("WUSyntaxCheckECL has timed out.");
  1144. break;
  1145. }
  1146. }
  1147. catch(IException* e)
  1148. {
  1149. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1150. }
  1151. return true;
  1152. }
  1153. bool CWsWorkunitsEx::onWUCompileECL(IEspContext &context, IEspWUCompileECLRequest &req, IEspWUCompileECLResponse &resp)
  1154. {
  1155. try
  1156. {
  1157. ensureWsCreateWorkunitAccess(context);
  1158. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1159. NewWsWorkunit wu(factory, context);
  1160. if(req.getIncludeComplexity())
  1161. {
  1162. wu->setAction(WUActionCompile);
  1163. wu->setDebugValueInt("calculateComplexity",1,true);
  1164. }
  1165. else
  1166. wu->setAction(WUActionCheck);
  1167. if(req.getModuleName() && req.getAttributeName())
  1168. {
  1169. wu->setApplicationValue("SyntaxCheck","ModuleName",req.getModuleName(),true);
  1170. wu->setApplicationValue("SyntaxCheck","AttributeName",req.getAttributeName(),true);
  1171. }
  1172. if(req.getIncludeDependencies())
  1173. wu->setApplicationValueInt("SyntaxCheck","IncludeDependencies",1,true);
  1174. wu.setQueryText(req.getECL());
  1175. StringAttr wuid(wu->queryWuid()); // NB queryWuid() not valid after workunit,clear() StringAttr wuid(wu->queryWuid());
  1176. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
  1177. waitForWorkUnitToComplete(wuid.str(),req.getTimeToWait());
  1178. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  1179. SCMStringBuffer s;
  1180. cw->getDebugValue("__Calculated__Complexity__",s);
  1181. if(s.length())
  1182. resp.setComplexity(s.str());
  1183. WsWUExceptions errors(*cw);
  1184. resp.setErrors(errors);
  1185. if(!errors.ErrCount())
  1186. {
  1187. IArrayOf<IEspWUECLAttribute> dependencies;
  1188. for(unsigned count=1;;count++)
  1189. {
  1190. SCMStringBuffer xml;
  1191. cw->getApplicationValue("SyntaxCheck",StringBuffer("Dependency").append(count).str(),xml);
  1192. if(!xml.length())
  1193. break;
  1194. Owned<IPropertyTree> dep=createPTreeFromXMLString(xml.str(), ipt_caseInsensitive);
  1195. if(!dep)
  1196. continue;
  1197. Owned<IEspWUECLAttribute> att = createWUECLAttribute("","");
  1198. att->setModuleName(dep->queryProp("@module"));
  1199. att->setAttributeName(dep->queryProp("@name"));
  1200. int flags = dep->getPropInt("@flags",0);
  1201. if(flags & ob_locked)
  1202. {
  1203. if(flags & ob_lockedself)
  1204. att->setIsCheckedOut(true);
  1205. else
  1206. att->setIsLocked(true);
  1207. }
  1208. if(flags & ob_sandbox)
  1209. att->setIsSandbox(true);
  1210. if(flags & ob_orphaned)
  1211. att->setIsOrphaned(true);
  1212. dependencies.append(*att.getLink());
  1213. }
  1214. resp.setDependencies(dependencies);
  1215. }
  1216. cw.clear();
  1217. factory->deleteWorkUnitEx(wuid.str(), true);
  1218. }
  1219. catch(IException* e)
  1220. {
  1221. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1222. }
  1223. return true;
  1224. }
  1225. bool CWsWorkunitsEx::onWUGetDependancyTrees(IEspContext& context, IEspWUGetDependancyTreesRequest& req, IEspWUGetDependancyTreesResponse& resp)
  1226. {
  1227. try
  1228. {
  1229. ensureWsCreateWorkunitAccess(context);
  1230. unsigned int timeMilliSec = 500;
  1231. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1232. NewWsWorkunit wu(factory, context);
  1233. wu->setAction(WUActionCheck);
  1234. if (notEmpty(req.getCluster()))
  1235. wu->setClusterName(req.getCluster());
  1236. if (notEmpty(req.getSnapshot()))
  1237. wu->setSnapshot(req.getSnapshot());
  1238. wu->setDebugValue("gatherDependenciesSelection",notEmpty(req.getItems()) ? req.getItems() : NULL,true);
  1239. if (context.getClientVersion() > 1.12)
  1240. {
  1241. wu->setDebugValueInt("gatherDependencies", 1, true);
  1242. const char *timeout = req.getTimeoutMilliSec();
  1243. if (notEmpty(timeout))
  1244. {
  1245. const char *finger = timeout;
  1246. while (*finger)
  1247. {
  1248. if (!isdigit(*finger++))
  1249. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Incorrect timeout value");
  1250. }
  1251. timeMilliSec = atol(timeout);
  1252. }
  1253. }
  1254. StringAttr wuid(wu->queryWuid()); // NB queryWuid() not valid after workunit,clear()
  1255. wu->commit();
  1256. wu.clear();
  1257. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
  1258. int state = waitForWorkUnitToComplete(wuid.str(), timeMilliSec);
  1259. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  1260. WsWUExceptions errors(*cw);
  1261. resp.setErrors(errors);
  1262. MemoryBuffer temp;
  1263. MemoryBuffer2IDataVal xmlresult(temp);
  1264. Owned<IConstWUResult> result = cw->getResultBySequence(0);
  1265. if (result)
  1266. {
  1267. result->getResultRaw(xmlresult, NULL, NULL);
  1268. resp.setDependancyTrees(temp);
  1269. }
  1270. wu.setown(&cw->lock());
  1271. wu->setState(WUStateAborted);
  1272. wu->commit();
  1273. wu.clear();
  1274. factory->deleteWorkUnitEx(wuid.str(), true);
  1275. }
  1276. catch(IException* e)
  1277. {
  1278. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1279. }
  1280. return true;
  1281. }
  1282. bool getWsWuInfoFromSasha(IEspContext &context, SocketEndpoint &ep, const char* wuid, IEspECLWorkunit *info)
  1283. {
  1284. Owned<INode> node = createINode(ep);
  1285. Owned<ISashaCommand> cmd = createSashaCommand();
  1286. cmd->addId(wuid);
  1287. cmd->setAction(SCA_GET);
  1288. if (!cmd->send(node, 1*60*1000))
  1289. {
  1290. StringBuffer url;
  1291. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,
  1292. "Sasha (%s) took too long to respond from: Get information for %s.",
  1293. ep.getUrlStr(url).str(), wuid);
  1294. }
  1295. if (cmd->numIds()==0)
  1296. {
  1297. DBGLOG("Could not read archived workunit %s",wuid);
  1298. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot read workunit %s.",wuid);
  1299. }
  1300. unsigned num = cmd->numResults();
  1301. if (num < 1)
  1302. return false;
  1303. StringBuffer res;
  1304. cmd->getResult(0, res);
  1305. if(res.length() < 1)
  1306. return false;
  1307. Owned<IPropertyTree> wpt = createPTreeFromXMLString(res.str());
  1308. if (!wpt)
  1309. return false;
  1310. const char * owner = wpt->queryProp("@submitID");
  1311. ensureWsWorkunitAccessByOwnerId(context, owner, SecAccess_Read);
  1312. PROGLOG("GetArchivedWUInfo: %s", wuid);
  1313. info->setWuid(wuid);
  1314. info->setArchived(true);
  1315. if (notEmpty(owner))
  1316. info->setOwner(owner);
  1317. const char * state = wpt->queryProp("@state");
  1318. if (notEmpty(state))
  1319. info->setState(state);
  1320. const char * cluster = wpt->queryProp("@clusterName");
  1321. if (notEmpty(cluster))
  1322. info->setCluster(cluster);
  1323. if (context.querySecManager())
  1324. {
  1325. const char * scope = wpt->queryProp("@scope");
  1326. if (notEmpty(scope))
  1327. info->setScope(scope);
  1328. }
  1329. const char * jobName = wpt->queryProp("@jobName");
  1330. if (notEmpty(jobName))
  1331. info->setJobname(jobName);
  1332. const char * description = wpt->queryProp("Debug/description");
  1333. if (notEmpty(description))
  1334. info->setDescription(description);
  1335. const char * queryText = wpt->queryProp("Query/Text");
  1336. if (notEmpty(queryText))
  1337. info->updateQuery().setText(queryText);
  1338. const char * protectedWU = wpt->queryProp("@protected");
  1339. info->setProtected((protectedWU && *protectedWU!='0'));
  1340. return true;
  1341. }
  1342. #define WUDETAILS_REFRESH_MINS 1
  1343. void getArchivedWUInfo(IEspContext &context, const char* sashaServerIP, unsigned sashaServerPort, const char *wuid, IEspWUInfoResponse &resp)
  1344. {
  1345. SocketEndpoint ep;
  1346. if (sashaServerIP && *sashaServerIP)
  1347. ep.set(sashaServerIP, sashaServerPort);
  1348. else
  1349. getSashaNode(ep);
  1350. if (getWsWuInfoFromSasha(context, ep, wuid, &resp.updateWorkunit()))
  1351. {
  1352. resp.setCanCompile(false);
  1353. return;
  1354. }
  1355. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Cannot find workunit %s.", wuid);
  1356. return;
  1357. }
  1358. #define WUDETAILS_REFRESH_MINS 1
  1359. bool CWsWorkunitsEx::onWUInfo(IEspContext &context, IEspWUInfoRequest &req, IEspWUInfoResponse &resp)
  1360. {
  1361. try
  1362. {
  1363. StringBuffer wuid(req.getWuid());
  1364. WsWuHelpers::checkAndTrimWorkunit("WUInfo", wuid);
  1365. double version = context.getClientVersion();
  1366. if (req.getType() && strieq(req.getType(), "archived workunits"))
  1367. getArchivedWUInfo(context, sashaServerIp.get(), sashaServerPort, wuid.str(), resp);
  1368. else
  1369. {
  1370. try
  1371. {
  1372. //The access is checked here because getArchivedWUInfo() has its own access check.
  1373. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  1374. unsigned long flags=0;
  1375. if (req.getTruncateEclTo64k())
  1376. flags|=WUINFO_TruncateEclTo64k;
  1377. if (req.getIncludeExceptions())
  1378. flags|=WUINFO_IncludeExceptions;
  1379. if (req.getIncludeGraphs())
  1380. flags|=WUINFO_IncludeGraphs;
  1381. if (req.getIncludeSourceFiles())
  1382. flags|=WUINFO_IncludeSourceFiles;
  1383. if (req.getIncludeResults())
  1384. flags|=WUINFO_IncludeResults;
  1385. if (req.getIncludeVariables())
  1386. flags|=WUINFO_IncludeVariables;
  1387. if (req.getIncludeTimers())
  1388. flags|=WUINFO_IncludeTimers;
  1389. if (req.getIncludeDebugValues())
  1390. flags|=WUINFO_IncludeDebugValues;
  1391. if (req.getIncludeApplicationValues())
  1392. flags|=WUINFO_IncludeApplicationValues;
  1393. if (req.getIncludeWorkflows())
  1394. flags|=WUINFO_IncludeWorkflows;
  1395. if (!req.getSuppressResultSchemas())
  1396. flags|=WUINFO_IncludeEclSchemas;
  1397. if (req.getIncludeXmlSchemas())
  1398. flags|=WUINFO_IncludeXmlSchema;
  1399. if (req.getIncludeResultsViewNames())
  1400. flags|=WUINFO_IncludeResultsViewNames;
  1401. if (req.getIncludeResourceURLs())
  1402. flags|=WUINFO_IncludeResourceURLs;
  1403. if (req.getIncludeECL())
  1404. flags|=WUINFO_IncludeECL;
  1405. if (req.getIncludeHelpers())
  1406. flags|=WUINFO_IncludeHelpers;
  1407. if (req.getIncludeAllowedClusters())
  1408. flags|=WUINFO_IncludeAllowedClusters;
  1409. if (req.getIncludeTotalClusterTime())
  1410. flags|=WUINFO_IncludeTotalClusterTime;
  1411. PROGLOG("WUInfo: %s %lx", wuid.str(), flags);
  1412. WsWuInfo winfo(context, wuid.str());
  1413. winfo.getInfo(resp.updateWorkunit(), flags);
  1414. if (req.getIncludeResultsViewNames()||req.getIncludeResourceURLs()||(version >= 1.50))
  1415. {
  1416. StringArray views, urls;
  1417. winfo.getResourceInfo(views, urls, WUINFO_IncludeResultsViewNames|WUINFO_IncludeResourceURLs);
  1418. IEspECLWorkunit& eclWU = resp.updateWorkunit();
  1419. if (req.getIncludeResultsViewNames())
  1420. resp.setResultViews(views);
  1421. if (req.getIncludeResourceURLs())
  1422. eclWU.setResourceURLs(urls);
  1423. if (version >= 1.50)
  1424. {
  1425. eclWU.setResultViewCount(views.length());
  1426. eclWU.setResourceURLCount(urls.length());
  1427. }
  1428. }
  1429. }
  1430. catch (IException *e)
  1431. {
  1432. if (e->errorCode() != ECLWATCH_CANNOT_OPEN_WORKUNIT)
  1433. throw e;
  1434. getArchivedWUInfo(context, sashaServerIp.get(), sashaServerPort, wuid.str(), resp);
  1435. e->Release();
  1436. }
  1437. switch (resp.getWorkunit().getStateID())
  1438. {
  1439. case WUStateCompiling:
  1440. case WUStateCompiled:
  1441. case WUStateScheduled:
  1442. case WUStateSubmitted:
  1443. case WUStateRunning:
  1444. case WUStateAborting:
  1445. case WUStateWait:
  1446. case WUStateUploadingFiles:
  1447. case WUStateDebugPaused:
  1448. case WUStateDebugRunning:
  1449. resp.setAutoRefresh(WUDETAILS_REFRESH_MINS);
  1450. break;
  1451. case WUStateBlocked:
  1452. resp.setAutoRefresh(WUDETAILS_REFRESH_MINS*5);
  1453. break;
  1454. }
  1455. resp.setCanCompile(notEmpty(context.queryUserId()));
  1456. if (version > 1.24 && notEmpty(req.getThorSlaveIP()))
  1457. resp.setThorSlaveIP(req.getThorSlaveIP());
  1458. ISecManager* secmgr = context.querySecManager();
  1459. if (!secmgr)
  1460. resp.setSecMethod(NULL);
  1461. else
  1462. resp.setSecMethod(secmgr->querySecMgrTypeName());
  1463. }
  1464. }
  1465. catch(IException* e)
  1466. {
  1467. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1468. }
  1469. return true;
  1470. }
  1471. bool CWsWorkunitsEx::onWUInfoDetails(IEspContext &context, IEspWUInfoRequest &req, IEspWUInfoResponse &resp)
  1472. {
  1473. return onWUInfo(context, req, resp);
  1474. }
  1475. bool CWsWorkunitsEx::onWUResultView(IEspContext &context, IEspWUResultViewRequest &req, IEspWUResultViewResponse &resp)
  1476. {
  1477. StringBuffer wuid(req.getWuid());
  1478. WsWuHelpers::checkAndTrimWorkunit("WUResultView", wuid);
  1479. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  1480. PROGLOG("WUResultView: %s", wuid.str());
  1481. Owned<IWuWebView> wv = createWuWebView(wuid.str(), NULL, NULL, getCFD(), true, nullptr);
  1482. StringBuffer html;
  1483. wv->renderSingleResult(req.getViewName(), req.getResultName(), html);
  1484. resp.setResult(html.str());
  1485. resp.setResult_mimetype("text/html");
  1486. return true;
  1487. }
  1488. void doWUQueryBySingleWuid(IEspContext &context, const char *wuid, IEspWUQueryResponse &resp)
  1489. {
  1490. Owned<IEspECLWorkunit> info= createECLWorkunit("","");
  1491. WsWuInfo winfo(context, wuid);
  1492. winfo.getCommon(*info, 0);
  1493. IArrayOf<IEspECLWorkunit> results;
  1494. results.append(*info.getClear());
  1495. resp.setWorkunits(results);
  1496. resp.setPageSize(1);
  1497. resp.setCount(1);
  1498. PROGLOG("getWUInfo: %s", wuid);
  1499. }
  1500. void doWUQueryByFile(IEspContext &context, const char *logicalFile, IEspWUQueryResponse &resp)
  1501. {
  1502. StringBuffer wuid;
  1503. getWuidFromLogicalFileName(context, logicalFile, wuid);
  1504. if (!wuid.length())
  1505. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot find the workunit for file %s.", logicalFile);
  1506. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1507. Owned<IConstWorkUnit> cw= factory->openWorkUnit(wuid.str());
  1508. if (!cw)
  1509. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot find the workunit for file %s.", logicalFile);
  1510. if (getWsWorkunitAccess(context, *cw) < SecAccess_Read)
  1511. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED,"Cannot access the workunit for file %s.",logicalFile);
  1512. doWUQueryBySingleWuid(context, wuid.str(), resp);
  1513. resp.setFirst(false);
  1514. resp.setPageSize(1);
  1515. resp.setCount(1);
  1516. }
  1517. bool addWUQueryFilter(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *name, WUSortField value)
  1518. {
  1519. if (isEmpty(name))
  1520. return false;
  1521. filters[count++] = value;
  1522. if ((value & WUSFwild) != 0 && !containsWildcard(name))
  1523. {
  1524. VStringBuffer s("*%s*", name);
  1525. buff.append(s);
  1526. }
  1527. else
  1528. buff.append(name);
  1529. return true;
  1530. }
  1531. bool addWUQueryFilterTime(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *stime, WUSortField value)
  1532. {
  1533. if (isEmpty(stime))
  1534. return false;
  1535. CDateTime dt;
  1536. dt.setString(stime, NULL, true);
  1537. unsigned year, month, day, hour, minute, second, nano;
  1538. dt.getDate(year, month, day, true);
  1539. dt.getTime(hour, minute, second, nano, true);
  1540. VStringBuffer wuid("W%4d%02d%02d-%02d%02d%02d",year,month,day,hour,minute,second);
  1541. filters[count++] = value;
  1542. buff.append(wuid.str());
  1543. return true;
  1544. }
  1545. bool addWUQueryFilterTotalClusterTime(WUSortField *filters, unsigned short &count, MemoryBuffer &filterBuf, unsigned milliseconds, WUSortField value)
  1546. {
  1547. if (milliseconds == 0)
  1548. return false;
  1549. VStringBuffer vBuf("%u", milliseconds);
  1550. filters[count++] = value;
  1551. filterBuf.append(vBuf);
  1552. return true;
  1553. }
  1554. bool addWUQueryFilterApplication(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *appname, const char *appkey, const char *appdata)
  1555. {
  1556. if (isEmpty(appname))
  1557. return false; // appname must be specified
  1558. if (isEmpty(appkey) && isEmpty(appdata)) //one or other is required ( MORE - see if cassandra can relax that)
  1559. return false;
  1560. VStringBuffer path("%s/%s", appname, appkey && *appkey ? appkey : "*");
  1561. buff.append(path.str());
  1562. buff.append(appdata);
  1563. filters[count++] = WUSFappvalue;
  1564. return true;
  1565. }
  1566. void readWUQuerySortOrder(const char* sortBy, const bool descending, WUSortField& sortOrder)
  1567. {
  1568. if (isEmpty(sortBy))
  1569. {
  1570. sortOrder = (WUSortField) (WUSFwuid | WUSFreverse);
  1571. return;
  1572. }
  1573. if (strieq(sortBy, "Owner"))
  1574. sortOrder = WUSFuser;
  1575. else if (strieq(sortBy, "JobName"))
  1576. sortOrder = WUSFjob;
  1577. else if (strieq(sortBy, "Cluster"))
  1578. sortOrder = WUSFcluster;
  1579. else if (strieq(sortBy, "Protected"))
  1580. sortOrder = WUSFprotected;
  1581. else if (strieq(sortBy, "State"))
  1582. sortOrder = WUSFstate;
  1583. else if (strieq(sortBy, "ClusterTime"))
  1584. sortOrder = (WUSortField) (WUSFtotalthortime+WUSFnumeric);
  1585. else
  1586. sortOrder = WUSFwuid;
  1587. sortOrder = (WUSortField) (sortOrder | WUSFnocase);
  1588. if (descending)
  1589. sortOrder = (WUSortField) (sortOrder | WUSFreverse);
  1590. }
  1591. void doWUQueryWithSort(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  1592. {
  1593. SecAccessFlags accessOwn;
  1594. SecAccessFlags accessOthers;
  1595. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  1596. double version = context.getClientVersion();
  1597. IArrayOf<IEspECLWorkunit> results;
  1598. int begin = 0;
  1599. unsigned int count = 100;
  1600. int pagesize = 100;
  1601. if (version > 1.01)
  1602. {
  1603. pagesize = (int)req.getPageSize();
  1604. if (!req.getCount_isNull())
  1605. pagesize = req.getCount();
  1606. if(pagesize < 1)
  1607. pagesize = 100;
  1608. begin = (int)req.getPageStartFrom();
  1609. }
  1610. else
  1611. {
  1612. count=(unsigned)req.getCount();
  1613. if(!count)
  1614. count=100;
  1615. if (notEmpty(req.getAfter()))
  1616. begin=atoi(req.getAfter());
  1617. else if (notEmpty(req.getBefore()))
  1618. begin=atoi(req.getBefore())-count;
  1619. if (begin < 0)
  1620. begin = 0;
  1621. pagesize = count;
  1622. }
  1623. WUSortField sortorder;
  1624. readWUQuerySortOrder(req.getSortby(), req.getDescending(), sortorder);
  1625. WUSortField filters[10];
  1626. unsigned short filterCount = 0;
  1627. MemoryBuffer filterbuf;
  1628. // Query filters should be added in order of expected power - add the most restrictive filters first
  1629. bool bDoubleCheckState = false;
  1630. if(req.getState() && *req.getState())
  1631. {
  1632. filters[filterCount++] = WUSFstate;
  1633. if (!strieq(req.getState(), "unknown"))
  1634. filterbuf.append(req.getState());
  1635. else
  1636. filterbuf.append("");
  1637. if (strieq(req.getState(), "submitted"))
  1638. bDoubleCheckState = true;
  1639. }
  1640. addWUQueryFilter(filters, filterCount, filterbuf, req.getWuid(), WUSFwildwuid);
  1641. addWUQueryFilter(filters, filterCount, filterbuf, req.getCluster(), WUSFcluster);
  1642. addWUQueryFilter(filters, filterCount, filterbuf, req.getLogicalFile(), (WUSortField) (WUSFfileread | WUSFnocase));
  1643. addWUQueryFilter(filters, filterCount, filterbuf, req.getOwner(), (WUSortField) (WUSFuser | WUSFnocase));
  1644. addWUQueryFilter(filters, filterCount, filterbuf, req.getJobname(), (WUSortField) (WUSFjob | WUSFnocase));
  1645. addWUQueryFilter(filters, filterCount, filterbuf, req.getECL(), (WUSortField) (WUSFecl | WUSFwild));
  1646. addWUQueryFilterTotalClusterTime(filters, filterCount, filterbuf, req.getTotalClusterTimeThresholdMilliSec(), WUSFtotalthortime);
  1647. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getStartDate(), WUSFwuid);
  1648. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getEndDate(), WUSFwuidhigh);
  1649. if (version < 1.55)
  1650. addWUQueryFilterApplication(filters, filterCount, filterbuf, req.getApplicationName(), req.getApplicationKey(), req.getApplicationData());
  1651. else
  1652. {
  1653. IArrayOf<IConstApplicationValue>& applicationFilters = req.getApplicationValues();
  1654. ForEachItemIn(i, applicationFilters)
  1655. {
  1656. IConstApplicationValue &item = applicationFilters.item(i);
  1657. addWUQueryFilterApplication(filters, filterCount, filterbuf, item.getApplication(), item.getName(), item.getValue());
  1658. }
  1659. }
  1660. filters[filterCount] = WUSFterm;
  1661. __int64 cacheHint = 0;
  1662. if (!req.getCacheHint_isNull())
  1663. cacheHint = req.getCacheHint();
  1664. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1665. unsigned numWUs;
  1666. PROGLOG("WUQuery: getWorkUnitsSorted");
  1667. Owned<IConstWorkUnitIterator> it = factory->getWorkUnitsSorted(sortorder, filters, filterbuf.bufferBase(), begin, pagesize+1, &cacheHint, &numWUs); // MORE - need security flags here!
  1668. if (version >= 1.41)
  1669. resp.setCacheHint(cacheHint);
  1670. PROGLOG("WUQuery: getWorkUnitsSorted done");
  1671. unsigned actualCount = 0;
  1672. ForEach(*it)
  1673. {
  1674. IConstWorkUnitInfo& cw = it->query();
  1675. if (bDoubleCheckState && (cw.getState() != WUStateSubmitted))
  1676. {
  1677. numWUs--;
  1678. continue;
  1679. }
  1680. // This test is presumably trying to remove the global workunit, though it's not the right way to do so (since it will mess up page counts etc)
  1681. const char* wuid = cw.queryWuid();
  1682. if (!looksLikeAWuid(wuid, 'W'))
  1683. {
  1684. numWUs--;
  1685. continue;
  1686. }
  1687. actualCount++;
  1688. Owned<IEspECLWorkunit> info = createECLWorkunit("","");
  1689. info->setWuid(cw.queryWuid());
  1690. if (chooseWuAccessFlagsByOwnership(context.queryUserId(), cw, accessOwn, accessOthers) < SecAccess_Read)
  1691. {
  1692. info->setState("<Hidden>");
  1693. results.append(*info.getClear());
  1694. continue;
  1695. }
  1696. info->setProtected(cw.isProtected() ? 1 : 0);
  1697. info->setJobname(cw.queryJobName());
  1698. info->setOwner(cw.queryUser());
  1699. info->setCluster(cw.queryClusterName());
  1700. SCMStringBuffer s;
  1701. // info.setSnapshot(cw->getSnapshot(s).str());
  1702. info->setStateID(cw.getState());
  1703. info->setState(cw.queryStateDesc());
  1704. unsigned totalThorTimeMS = cw.getTotalThorTime();
  1705. StringBuffer totalThorTimeStr;
  1706. formatDuration(totalThorTimeStr, totalThorTimeMS);
  1707. if (version > 1.52)
  1708. info->setTotalClusterTime(totalThorTimeStr.str());
  1709. else
  1710. info->setTotalThorTime(totalThorTimeStr.str());
  1711. //if (cw->isPausing())
  1712. // info.setIsPausing(true);
  1713. // getEventScheduleFlag(info);
  1714. WsWuDateTime dt;
  1715. cw.getTimeScheduled(dt);
  1716. if(dt.isValid())
  1717. info->setDateTimeScheduled(dt.getString(s).str());
  1718. if (version >= 1.55)
  1719. {
  1720. IArrayOf<IEspApplicationValue> av;
  1721. Owned<IConstWUAppValueIterator> app(&cw.getApplicationValues());
  1722. ForEach(*app)
  1723. {
  1724. IConstWUAppValue& val=app->query();
  1725. Owned<IEspApplicationValue> t= createApplicationValue("","");
  1726. t->setApplication(val.queryApplication());
  1727. t->setName(val.queryName());
  1728. t->setValue(val.queryValue());
  1729. av.append(*t.getLink());
  1730. }
  1731. info->setApplicationValues(av);
  1732. }
  1733. results.append(*info.getClear());
  1734. }
  1735. if (version > 1.02)
  1736. {
  1737. resp.setPageStartFrom(begin+1);
  1738. resp.setNumWUs(numWUs);
  1739. if (results.length() > (aindex_t)pagesize)
  1740. results.pop();
  1741. if(unsigned (begin + pagesize) < numWUs)
  1742. {
  1743. resp.setNextPage(begin + pagesize);
  1744. resp.setPageEndAt(begin + pagesize);
  1745. int last = begin + pagesize;
  1746. while (numWUs > (unsigned) last + pagesize)
  1747. last += pagesize;
  1748. resp.setLastPage(last);
  1749. }
  1750. else
  1751. {
  1752. resp.setNextPage(-1);
  1753. resp.setPageEndAt(numWUs);
  1754. }
  1755. if(begin > 0)
  1756. {
  1757. resp.setFirst(false);
  1758. if (begin - pagesize > 0)
  1759. resp.setPrevPage(begin - pagesize);
  1760. else
  1761. resp.setPrevPage(0);
  1762. }
  1763. resp.setPageSize(pagesize);
  1764. }
  1765. else
  1766. {
  1767. if(begin>0 && actualCount > 0)
  1768. {
  1769. char buf[10];
  1770. itoa(begin, buf, 10);
  1771. resp.setCurrent(buf);
  1772. }
  1773. if(count<actualCount)
  1774. {
  1775. char buf[10];
  1776. itoa(begin+count, buf, 10);
  1777. resp.setNext(buf);
  1778. resp.setNumWUs(numWUs);
  1779. if (results.length() > count)
  1780. results.pop();
  1781. }
  1782. if(begin == 0 && actualCount <= count)
  1783. resp.setFirst(false);
  1784. resp.setCount(count);
  1785. }
  1786. resp.setWorkunits(results);
  1787. return;
  1788. }
  1789. void doWULightWeightQueryWithSort(IEspContext &context, IEspWULightWeightQueryRequest & req, IEspWULightWeightQueryResponse & resp)
  1790. {
  1791. SecAccessFlags accessOwn;
  1792. SecAccessFlags accessOthers;
  1793. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  1794. double version = context.getClientVersion();
  1795. int pageStartFrom = 0;
  1796. int pageSize = 100;
  1797. if (!req.getPageStartFrom_isNull())
  1798. pageStartFrom = req.getPageStartFrom();
  1799. if (!req.getPageSize_isNull())
  1800. pageSize = req.getPageSize();
  1801. WUSortField sortOrder;
  1802. readWUQuerySortOrder(req.getSortBy(), req.getDescending(), sortOrder);
  1803. WUSortField filters[10];
  1804. unsigned short filterCount = 0;
  1805. MemoryBuffer filterbuf;
  1806. // Query filters should be added in order of expected power - add the most restrictive filters first
  1807. bool bDoubleCheckState = false;
  1808. if(req.getState() && *req.getState())
  1809. {
  1810. filters[filterCount++] = WUSFstate;
  1811. if (!strieq(req.getState(), "unknown"))
  1812. filterbuf.append(req.getState());
  1813. else
  1814. filterbuf.append("");
  1815. if (strieq(req.getState(), "submitted"))
  1816. bDoubleCheckState = true;
  1817. }
  1818. addWUQueryFilter(filters, filterCount, filterbuf, req.getWuid(), WUSFwildwuid);
  1819. addWUQueryFilter(filters, filterCount, filterbuf, req.getCluster(), WUSFcluster);
  1820. addWUQueryFilter(filters, filterCount, filterbuf, req.getOwner(), (WUSortField) (WUSFuser | WUSFnocase));
  1821. addWUQueryFilter(filters, filterCount, filterbuf, req.getJobName(), (WUSortField) (WUSFjob | WUSFnocase));
  1822. //StartDate example: 2015-08-26T14:26:00
  1823. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getStartDate(), WUSFwuid);
  1824. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getEndDate(), WUSFwuidhigh);
  1825. IArrayOf<IConstApplicationValue>& applicationFilters = req.getApplicationValues();
  1826. ForEachItemIn(i, applicationFilters)
  1827. {
  1828. IConstApplicationValue &item = applicationFilters.item(i);
  1829. addWUQueryFilterApplication(filters, filterCount, filterbuf, item.getApplication(), item.getName(), item.getValue());
  1830. }
  1831. filters[filterCount] = WUSFterm;
  1832. __int64 cacheHint = 0;
  1833. if (!req.getCacheHint_isNull())
  1834. cacheHint = req.getCacheHint();
  1835. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1836. unsigned numWUs;
  1837. PROGLOG("getWorkUnitsSorted(LightWeight)");
  1838. Owned<IConstWorkUnitIterator> it = factory->getWorkUnitsSorted(sortOrder, filters, filterbuf.bufferBase(), pageStartFrom, pageSize+1, &cacheHint, &numWUs); // MORE - need security flags here!
  1839. resp.setCacheHint(cacheHint);
  1840. PROGLOG("getWorkUnitsSorted(LightWeight) done");
  1841. IArrayOf<IEspECLWorkunitLW> results;
  1842. ForEach(*it)
  1843. {
  1844. IConstWorkUnitInfo& cw = it->query();
  1845. if (bDoubleCheckState && (cw.getState() != WUStateSubmitted))
  1846. {
  1847. numWUs--;
  1848. continue;
  1849. }
  1850. // This test is presumably trying to remove the global workunit, though it's not the right way to do so (since it will mess up page counts etc)
  1851. const char* wuid = cw.queryWuid();
  1852. if (!looksLikeAWuid(wuid, 'W'))
  1853. {
  1854. numWUs--;
  1855. continue;
  1856. }
  1857. Owned<IEspECLWorkunitLW> info = createECLWorkunitLW("","");
  1858. info->setWuid(cw.queryWuid());
  1859. if (chooseWuAccessFlagsByOwnership(context.queryUserId(), cw, accessOwn, accessOthers) < SecAccess_Read)
  1860. {
  1861. info->setStateDesc("<Hidden>");
  1862. results.append(*info.getClear());
  1863. continue;
  1864. }
  1865. SCMStringBuffer s;
  1866. info->setIsProtected(cw.isProtected() ? 1 : 0);
  1867. info->setJobName(cw.queryJobName());
  1868. info->setWuScope(cw.queryWuScope());
  1869. info->setOwner(cw.queryUser());
  1870. info->setClusterName(cw.queryClusterName());
  1871. info->setState(cw.getState());
  1872. info->setStateDesc(cw.queryStateDesc());
  1873. info->setAction(cw.getAction());
  1874. info->setActionDesc(cw.queryActionDesc());
  1875. info->setPriority(cw.getPriority());
  1876. info->setPriorityLevel(cw.getPriorityLevel());
  1877. info->setPriorityDesc(cw.queryPriorityDesc());
  1878. info->setTotalClusterTime(cw.getTotalThorTime());
  1879. WsWuDateTime dt;
  1880. cw.getTimeScheduled(dt);
  1881. if(dt.isValid())
  1882. info->setDateTimeScheduled(dt.getString(s).str());
  1883. IArrayOf<IEspApplicationValue> av;
  1884. Owned<IConstWUAppValueIterator> app(&cw.getApplicationValues());
  1885. ForEach(*app)
  1886. {
  1887. IConstWUAppValue& val=app->query();
  1888. Owned<IEspApplicationValue> t= createApplicationValue("","");
  1889. t->setApplication(val.queryApplication());
  1890. t->setName(val.queryName());
  1891. t->setValue(val.queryValue());
  1892. av.append(*t.getClear());
  1893. }
  1894. info->setApplicationValues(av);
  1895. results.append(*info.getClear());
  1896. }
  1897. resp.setNumWUs(numWUs);
  1898. if (results.length() > (aindex_t)pageSize)
  1899. results.pop();
  1900. resp.setWorkunits(results);
  1901. return;
  1902. }
  1903. class CArchivedWUsReader : public CInterface, implements IArchivedWUsReader
  1904. {
  1905. IEspContext& context;
  1906. unsigned pageSize;
  1907. StringAttr sashaServerIP;
  1908. unsigned sashaServerPort;
  1909. unsigned cacheMinutes;
  1910. StringBuffer filterStr;
  1911. ArchivedWuCache& archivedWuCache;
  1912. unsigned numberOfWUsReturned;
  1913. bool hasMoreWU;
  1914. void readDateFilters(const char* startDateReq, const char* endDateReq, StringBuffer& from, StringBuffer& to)
  1915. {
  1916. CDateTime timeFrom, timeTo;
  1917. if(notEmpty(endDateReq))
  1918. {//endDateReq example: 2015-08-26T14:26:00
  1919. unsigned year, month, day, hour, minute, second, nano;
  1920. timeTo.setString(endDateReq, NULL, true);
  1921. timeTo.getDate(year, month, day, true);
  1922. timeTo.getTime(hour, minute, second, nano, true);
  1923. to.setf("%4d%02d%02d-%02d%02d%02d", year, month, day, hour, minute, second);
  1924. }
  1925. if(isEmpty(startDateReq))
  1926. return;
  1927. timeFrom.setString(startDateReq, NULL, true);
  1928. if (timeFrom >= timeTo)
  1929. return;
  1930. unsigned year0, month0, day0, hour0, minute0, second0, nano0;
  1931. timeFrom.getDate(year0, month0, day0, true);
  1932. timeFrom.getTime(hour0, minute0, second0, nano0, true);
  1933. from.setf("%4d%02d%02d-%02d%02d%02d", year0, month0, day0, hour0, minute0, second0);
  1934. return;
  1935. }
  1936. bool addToFilterString(const char *name, const char *value)
  1937. {
  1938. if (isEmpty(name) || isEmpty(value))
  1939. return false;
  1940. filterStr.append(';').append(name).append("=").append(value);
  1941. return true;
  1942. }
  1943. bool addToFilterString(const char *name, unsigned value)
  1944. {
  1945. if (isEmpty(name))
  1946. return false;
  1947. filterStr.append(';').append(name).append("=").append(value);
  1948. return true;
  1949. }
  1950. void setFilterString(IEspWUQueryRequest& req)
  1951. {
  1952. filterStr.set("0");
  1953. addToFilterString("wuid", req.getWuid());
  1954. addToFilterString("cluster", req.getCluster());
  1955. addToFilterString("owner", req.getOwner());
  1956. addToFilterString("jobName", req.getJobname());
  1957. addToFilterString("state", req.getState());
  1958. addToFilterString("timeFrom", req.getStartDate());
  1959. addToFilterString("timeTo", req.getEndDate());
  1960. addToFilterString("beforeWU", req.getBeforeWU());
  1961. addToFilterString("afterWU", req.getAfterWU());
  1962. addToFilterString("descending", req.getDescending());
  1963. addToFilterString("pageSize", pageSize);
  1964. if (sashaServerIP && *sashaServerIP)
  1965. {
  1966. addToFilterString("sashaServerIP", sashaServerIP.get());
  1967. addToFilterString("sashaServerPort", sashaServerPort);
  1968. }
  1969. }
  1970. void setFilterStringLW(IEspWULightWeightQueryRequest& req)
  1971. {
  1972. filterStr.set("1");
  1973. addToFilterString("wuid", req.getWuid());
  1974. addToFilterString("cluster", req.getCluster());
  1975. addToFilterString("owner", req.getOwner());
  1976. addToFilterString("jobName", req.getJobName());
  1977. addToFilterString("state", req.getState());
  1978. addToFilterString("timeFrom", req.getStartDate());
  1979. addToFilterString("timeTo", req.getEndDate());
  1980. addToFilterString("beforeWU", req.getBeforeWU());
  1981. addToFilterString("afterWU", req.getAfterWU());
  1982. addToFilterString("descending", req.getDescending());
  1983. addToFilterString("pageSize", pageSize);
  1984. if (sashaServerIP && *sashaServerIP)
  1985. {
  1986. addToFilterString("sashaServerIP", sashaServerIP.get());
  1987. addToFilterString("sashaServerPort", sashaServerPort);
  1988. }
  1989. }
  1990. void initSashaCommand(ISashaCommand* cmd)
  1991. {
  1992. cmd->setAction(SCA_LIST);
  1993. cmd->setOutputFormat("owner,jobname,cluster,state");
  1994. cmd->setOnline(false);
  1995. cmd->setArchived(true);
  1996. cmd->setLimit(pageSize+1); //read an extra WU to check hasMoreWU
  1997. }
  1998. void setSashaCommand(IEspWUQueryRequest& req, ISashaCommand* cmd)
  1999. {
  2000. if (notEmpty(req.getWuid()))
  2001. cmd->addId(req.getWuid());
  2002. if (notEmpty(req.getCluster()))
  2003. cmd->setCluster(req.getCluster());
  2004. if (notEmpty(req.getOwner()))
  2005. cmd->setOwner(req.getOwner());
  2006. if (notEmpty(req.getJobname()))
  2007. cmd->setJobName(req.getJobname());
  2008. if (notEmpty(req.getState()))
  2009. cmd->setState(req.getState());
  2010. StringBuffer timeFrom, timeTo;
  2011. readDateFilters(req.getStartDate(), req.getEndDate(), timeFrom, timeTo);
  2012. if (timeFrom.length())
  2013. cmd->setAfter(timeFrom.str());
  2014. if (timeTo.length())
  2015. cmd->setBefore(timeTo.str());
  2016. if (notEmpty(req.getBeforeWU()))
  2017. cmd->setBeforeWU(req.getBeforeWU());
  2018. if (notEmpty(req.getAfterWU()))
  2019. cmd->setAfterWU(req.getAfterWU());
  2020. cmd->setSortDescending(req.getDescending());
  2021. return;
  2022. }
  2023. void setSashaCommandLW(IEspWULightWeightQueryRequest& req, ISashaCommand* cmd)
  2024. {
  2025. if (notEmpty(req.getWuid()))
  2026. cmd->addId(req.getWuid());
  2027. if (notEmpty(req.getCluster()))
  2028. cmd->setCluster(req.getCluster());
  2029. if (notEmpty(req.getOwner()))
  2030. cmd->setOwner(req.getOwner());
  2031. if (notEmpty(req.getJobName()))
  2032. cmd->setJobName(req.getJobName());
  2033. if (notEmpty(req.getState()))
  2034. cmd->setState(req.getState());
  2035. StringBuffer timeFrom, timeTo;
  2036. readDateFilters(req.getStartDate(), req.getEndDate(), timeFrom, timeTo);
  2037. if (timeFrom.length())
  2038. cmd->setAfter(timeFrom.str());
  2039. if (timeTo.length())
  2040. cmd->setBefore(timeTo.str());
  2041. if (notEmpty(req.getBeforeWU()))
  2042. cmd->setBeforeWU(req.getBeforeWU());
  2043. if (notEmpty(req.getAfterWU()))
  2044. cmd->setAfterWU(req.getAfterWU());
  2045. cmd->setSortDescending(req.getDescending());
  2046. return;
  2047. }
  2048. IEspECLWorkunit *createArchivedWUEntry(StringArray& wuDataArray, bool canAccess)
  2049. {
  2050. Owned<IEspECLWorkunit> info= createECLWorkunit();
  2051. info->setWuid(wuDataArray.item(0));
  2052. if (!canAccess)
  2053. {
  2054. info->setState("<Hidden>");
  2055. return info.getClear();
  2056. }
  2057. const char* owner = wuDataArray.item(1);
  2058. const char* jobName = wuDataArray.item(2);
  2059. const char* cluster = wuDataArray.item(3);
  2060. const char* state = wuDataArray.item(4);
  2061. if (notEmpty(owner))
  2062. info->setOwner(owner);
  2063. if (notEmpty(jobName))
  2064. info->setJobname(jobName);
  2065. if (notEmpty(cluster))
  2066. info->setCluster(cluster);
  2067. if (notEmpty(state))
  2068. info->setState(state);
  2069. return info.getClear();
  2070. }
  2071. IEspECLWorkunitLW *createArchivedLWWUEntry(StringArray& wuDataArray, bool canAccess)
  2072. {
  2073. Owned<IEspECLWorkunitLW> info= createECLWorkunitLW();
  2074. info->setWuid(wuDataArray.item(0));
  2075. if (!canAccess)
  2076. {
  2077. info->setStateDesc("<Hidden>");
  2078. return info.getClear();
  2079. }
  2080. const char* owner = wuDataArray.item(1);
  2081. const char* jobName = wuDataArray.item(2);
  2082. const char* cluster = wuDataArray.item(3);
  2083. const char* state = wuDataArray.item(4);
  2084. if (notEmpty(owner))
  2085. info->setOwner(owner);
  2086. if (notEmpty(jobName))
  2087. info->setJobName(jobName);
  2088. if (notEmpty(cluster))
  2089. info->setClusterName(cluster);
  2090. if (notEmpty(state))
  2091. info->setStateDesc(state);
  2092. return info.getClear();
  2093. }
  2094. static int compareWuids(IInterface * const *_a, IInterface * const *_b)
  2095. {
  2096. IEspECLWorkunit *a = *(IEspECLWorkunit **)_a;
  2097. IEspECLWorkunit *b = *(IEspECLWorkunit **)_b;
  2098. return strcmp(b->getWuid(), a->getWuid());
  2099. }
  2100. static int compareLWWuids(IInterface * const *_a, IInterface * const *_b)
  2101. {
  2102. IEspECLWorkunitLW *a = *(IEspECLWorkunitLW **)_a;
  2103. IEspECLWorkunitLW *b = *(IEspECLWorkunitLW **)_b;
  2104. return strcmp(b->getWuid(), a->getWuid());
  2105. }
  2106. public:
  2107. IMPLEMENT_IINTERFACE_USING(CInterface);
  2108. CArchivedWUsReader(IEspContext& _context, const char* _sashaServerIP, unsigned _sashaServerPort, ArchivedWuCache& _archivedWuCache,
  2109. unsigned _cacheMinutes, unsigned _pageSize)
  2110. : context(_context), sashaServerIP(_sashaServerIP), sashaServerPort(_sashaServerPort),
  2111. archivedWuCache(_archivedWuCache), cacheMinutes(_cacheMinutes), pageSize(_pageSize)
  2112. {
  2113. hasMoreWU = false;
  2114. numberOfWUsReturned = 0;
  2115. }
  2116. void getArchivedWUs(bool lightWeight, IEspWUQueryRequest& req, IEspWULightWeightQueryRequest& reqLW, IArrayOf<IEspECLWorkunit>& archivedWUs, IArrayOf<IEspECLWorkunitLW>& archivedLWWUs)
  2117. {
  2118. if (!lightWeight)
  2119. setFilterString(req);
  2120. else
  2121. setFilterStringLW(reqLW);
  2122. Owned<ArchivedWuCacheElement> cachedResults = archivedWuCache.lookup(context, filterStr, "AddWhenAvailable", cacheMinutes);
  2123. if (cachedResults)
  2124. {
  2125. hasMoreWU = cachedResults->m_hasNextPage;
  2126. numberOfWUsReturned = cachedResults->numWUsReturned;
  2127. if (!lightWeight && cachedResults->m_results.length())
  2128. {
  2129. ForEachItemIn(i, cachedResults->m_results)
  2130. archivedWUs.append(*LINK(&cachedResults->m_results.item(i)));
  2131. }
  2132. if (lightWeight && cachedResults->resultsLW.length())
  2133. {
  2134. ForEachItemIn(i, cachedResults->resultsLW)
  2135. archivedLWWUs.append(*LINK(&cachedResults->resultsLW.item(i)));
  2136. }
  2137. return;
  2138. }
  2139. SocketEndpoint ep;
  2140. if (sashaServerIP && *sashaServerIP)
  2141. ep.set(sashaServerIP, sashaServerPort);
  2142. else
  2143. getSashaNode(ep);
  2144. Owned<INode> sashaserver = createINode(ep);
  2145. Owned<ISashaCommand> cmd = createSashaCommand();
  2146. initSashaCommand(cmd);
  2147. if (!lightWeight)
  2148. setSashaCommand(req, cmd);
  2149. else
  2150. setSashaCommandLW(reqLW, cmd);
  2151. if (!cmd->send(sashaserver))
  2152. {
  2153. StringBuffer url;
  2154. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,
  2155. "Sasha (%s) took too long to respond from: Get archived workUnits.",
  2156. ep.getUrlStr(url).str());
  2157. }
  2158. numberOfWUsReturned = cmd->numIds();
  2159. hasMoreWU = (numberOfWUsReturned > pageSize);
  2160. if (hasMoreWU)
  2161. numberOfWUsReturned--;
  2162. if (numberOfWUsReturned == 0)
  2163. return;
  2164. SecAccessFlags accessOwn, accessOthers;
  2165. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  2166. for (unsigned i=0; i<numberOfWUsReturned; i++)
  2167. {
  2168. const char *csline = cmd->queryId(i);
  2169. if (!csline || !*csline)
  2170. continue;
  2171. StringArray wuDataArray;
  2172. wuDataArray.appendList(csline, ",");
  2173. const char* wuid = wuDataArray.item(0);
  2174. if (isEmpty(wuid))
  2175. {
  2176. IWARNLOG("Empty WUID in SCA_LIST response"); // JCS->KW - have u ever seen this happen?
  2177. continue;
  2178. }
  2179. const char* owner = wuDataArray.item(1);
  2180. bool canAccess = chooseWuAccessFlagsByOwnership(context.queryUserId(), owner, accessOwn, accessOthers) >= SecAccess_Read;
  2181. if (!lightWeight)
  2182. {
  2183. Owned<IEspECLWorkunit> info = createArchivedWUEntry(wuDataArray, canAccess);
  2184. archivedWUs.append(*info.getClear());
  2185. }
  2186. else
  2187. {
  2188. Owned<IEspECLWorkunitLW> info = createArchivedLWWUEntry(wuDataArray, canAccess);
  2189. archivedLWWUs.append(*info.getClear());
  2190. }
  2191. }
  2192. archivedWuCache.add(filterStr, "AddWhenAvailable", hasMoreWU, numberOfWUsReturned, archivedWUs, archivedLWWUs);
  2193. return;
  2194. };
  2195. bool getHasMoreWU() { return hasMoreWU; };
  2196. unsigned getNumberOfWUsReturned() { return numberOfWUsReturned; };
  2197. };
  2198. void doWUQueryFromArchive(IEspContext &context, const char* sashaServerIP, unsigned sashaServerPort,
  2199. ArchivedWuCache &archivedWuCache, unsigned cacheMinutes, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  2200. {
  2201. //Sasha server does noy support the PageStartFrom due to inefficient access to archived workunits for pages>1.
  2202. unsigned pageSize = (unsigned) req.getPageSize();
  2203. if(pageSize < 1)
  2204. pageSize=500;
  2205. Owned<IArchivedWUsReader> archiveWUsReader = new CArchivedWUsReader(context, sashaServerIP, sashaServerPort, archivedWuCache,
  2206. cacheMinutes, pageSize);
  2207. IArrayOf<IEspECLWorkunit> archivedWUs;
  2208. IArrayOf<IEspECLWorkunitLW> dummyWUs;
  2209. Owned<CWULightWeightQueryRequest> dummyReq = new CWULightWeightQueryRequest("WsWorkunits");
  2210. PROGLOG("getWorkUnitsFromArchive");
  2211. archiveWUsReader->getArchivedWUs(false, req, *dummyReq, archivedWUs, dummyWUs);
  2212. PROGLOG("getWorkUnitsFromArchive done");
  2213. resp.setWorkunits(archivedWUs);
  2214. resp.setNumWUs(archiveWUsReader->getNumberOfWUsReturned());
  2215. resp.setType("archived only");
  2216. resp.setPageSize(pageSize);
  2217. return;
  2218. }
  2219. void doWULightWeightQueryFromArchive(IEspContext &context, const char* sashaServerIP, unsigned sashaServerPort,
  2220. ArchivedWuCache &archivedWuCache, unsigned cacheMinutes, IEspWULightWeightQueryRequest & req, IEspWULightWeightQueryResponse & resp)
  2221. {
  2222. int pageSize = req.getPageSize_isNull()? 500 : req.getPageSize();
  2223. Owned<IArchivedWUsReader> archiveWUsReader = new CArchivedWUsReader(context, sashaServerIP, sashaServerPort, archivedWuCache,
  2224. cacheMinutes, pageSize);
  2225. Owned<CWUQueryRequest> dummyReq = new CWUQueryRequest("WsWorkunits");
  2226. IArrayOf<IEspECLWorkunit> dummyWUs;
  2227. IArrayOf<IEspECLWorkunitLW> archivedWUs;
  2228. PROGLOG("getWorkUnitsFromArchive(LightWeight)");
  2229. archiveWUsReader->getArchivedWUs(true, *dummyReq, req, dummyWUs, archivedWUs);
  2230. PROGLOG("getWorkUnitsFromArchive(LightWeight) done");
  2231. resp.setWorkunits(archivedWUs);
  2232. resp.setNumWUs(archiveWUsReader->getNumberOfWUsReturned());
  2233. return;
  2234. }
  2235. bool CWsWorkunitsEx::onWUQuery(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  2236. {
  2237. try
  2238. {
  2239. StringBuffer wuidStr(req.getWuid());
  2240. const char* wuid = wuidStr.trim().str();
  2241. if (req.getType() && strieq(req.getType(), "archived workunits"))
  2242. doWUQueryFromArchive(context, sashaServerIp.get(), sashaServerPort, *archivedWuCache, awusCacheMinutes, req, resp);
  2243. else if(notEmpty(wuid) && looksLikeAWuid(wuid, 'W'))
  2244. doWUQueryBySingleWuid(context, wuid, resp);
  2245. else if (notEmpty(req.getLogicalFile()) && req.getLogicalFileSearchType() && strieq(req.getLogicalFileSearchType(), "Created"))
  2246. doWUQueryByFile(context, req.getLogicalFile(), resp);
  2247. else
  2248. doWUQueryWithSort(context, req, resp);
  2249. resp.setState(req.getState());
  2250. resp.setCluster(req.getCluster());
  2251. resp.setRoxieCluster(req.getRoxieCluster());
  2252. resp.setOwner(req.getOwner());
  2253. resp.setStartDate(req.getStartDate());
  2254. resp.setEndDate(req.getEndDate());
  2255. double version = context.getClientVersion();
  2256. StringBuffer basicQuery;
  2257. addToQueryString(basicQuery, "State", req.getState());
  2258. addToQueryString(basicQuery, "Cluster", req.getCluster());
  2259. addToQueryString(basicQuery, "Owner", req.getOwner());
  2260. addToQueryString(basicQuery, "StartDate", req.getStartDate());
  2261. addToQueryString(basicQuery, "EndDate", req.getEndDate());
  2262. if (version >= 1.26 && version < 1.72 && req.getLastNDays() > -1)
  2263. addToQueryString(basicQuery, "LastNDays", StringBuffer().append(req.getLastNDays()).str());
  2264. addToQueryString(basicQuery, "ECL", req.getECL());
  2265. addToQueryString(basicQuery, "Jobname", req.getJobname());
  2266. addToQueryString(basicQuery, "Type", req.getType());
  2267. if (addToQueryString(basicQuery, "LogicalFile", req.getLogicalFile()))
  2268. addToQueryString(basicQuery, "LogicalFileSearchType", req.getLogicalFileSearchType());
  2269. resp.setFilters(basicQuery.str());
  2270. if (notEmpty(req.getSortby()) && !strstr(basicQuery.str(), StringBuffer(req.getSortby()).append('=').str()))
  2271. {
  2272. resp.setSortby(req.getSortby());
  2273. addToQueryString(basicQuery, "Sortby", req.getSortby());
  2274. if (req.getDescending())
  2275. {
  2276. resp.setDescending(req.getDescending());
  2277. addToQueryString(basicQuery, "Descending", "1");
  2278. }
  2279. }
  2280. resp.setBasicQuery(basicQuery.str());
  2281. StringBuffer s;
  2282. if(notEmpty(req.getECL()))
  2283. resp.setECL(Utils::url_encode(req.getECL(), s).str());
  2284. if(notEmpty(req.getJobname()))
  2285. resp.setJobname(Utils::url_encode(req.getJobname(), s.clear()).str());
  2286. }
  2287. catch(IException* e)
  2288. {
  2289. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2290. }
  2291. return true;
  2292. }
  2293. bool CWsWorkunitsEx::onWULightWeightQuery(IEspContext &context, IEspWULightWeightQueryRequest & req, IEspWULightWeightQueryResponse & resp)
  2294. {
  2295. try
  2296. {
  2297. if (req.getType() && strieq(req.getType(), "archived workunits"))
  2298. doWULightWeightQueryFromArchive(context, sashaServerIp.get(), sashaServerPort, *archivedWuCache, awusCacheMinutes, req, resp);
  2299. else
  2300. doWULightWeightQueryWithSort(context, req, resp);
  2301. }
  2302. catch(IException* e)
  2303. {
  2304. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2305. }
  2306. return true;
  2307. }
  2308. ITypeInfo * containsSingleSimpleFieldBlankXPath(IResultSetMetaData * meta)
  2309. {
  2310. if (meta->getColumnCount() != 1)
  2311. return NULL;
  2312. CResultSetMetaData * castMeta = static_cast<CResultSetMetaData *>(meta);
  2313. const char * xpath = castMeta->queryXPath(0);
  2314. if (xpath && (*xpath == 0))
  2315. {
  2316. return castMeta->queryType(0);
  2317. }
  2318. return NULL;
  2319. }
  2320. void csvSplitXPath(const char *xpath, StringBuffer &s, const char *&name, const char **childname=NULL)
  2321. {
  2322. if (!xpath)
  2323. return;
  2324. const char * slash = strchr(xpath, '/');
  2325. if (!slash)
  2326. {
  2327. name = xpath;
  2328. if (childname)
  2329. *childname = NULL;
  2330. }
  2331. else
  2332. {
  2333. if (!childname || strchr(slash+1, '/')) //output ignores xpaths that are too deep
  2334. return;
  2335. name = s.clear().append(slash-xpath, xpath).str();
  2336. *childname = slash+1;
  2337. }
  2338. }
  2339. void getCSVHeaders(const IResultSetMetaData& metaIn, CommonCSVWriter* writer, unsigned& layer)
  2340. {
  2341. StringBuffer xname;
  2342. const CResultSetMetaData& cMeta = static_cast<const CResultSetMetaData &>(metaIn);
  2343. IFvDataSourceMetaData* meta = cMeta.getMeta();
  2344. int columnCount = metaIn.getColumnCount();
  2345. for (unsigned idx = 0; idx < columnCount; idx++)
  2346. {
  2347. const CResultSetColumnInfo& column = cMeta.getColumn(idx);
  2348. unsigned flag = column.flag;
  2349. const char * name = meta->queryName(idx);
  2350. const char * childname = NULL;
  2351. switch (flag)
  2352. {
  2353. case FVFFbeginif:
  2354. case FVFFendif:
  2355. break;
  2356. case FVFFbeginrecord:
  2357. csvSplitXPath(meta->queryXPath(idx), xname, name);
  2358. writer->outputBeginNested(name, false, true);
  2359. break;
  2360. case FVFFendrecord:
  2361. csvSplitXPath(meta->queryXPath(idx), xname, name);
  2362. writer->outputEndNested(name, true);
  2363. break;
  2364. case FVFFdataset:
  2365. {
  2366. childname = "Row";
  2367. csvSplitXPath(meta->queryXPath(idx), xname, name, &childname);
  2368. ITypeInfo* singleFieldType = (name && *name && childname && *childname)
  2369. ? containsSingleSimpleFieldBlankXPath(column.childMeta.get()) : NULL;
  2370. if (!singleFieldType)
  2371. {
  2372. bool nameValid = (name && *name);
  2373. if (nameValid || (childname && *childname))
  2374. {
  2375. if (nameValid)
  2376. writer->outputBeginNested(name, false, true);
  2377. if (childname && *childname)
  2378. writer->outputBeginNested(childname, false, !nameValid);
  2379. const CResultSetMetaData *childMeta = static_cast<const CResultSetMetaData *>(column.childMeta.get());
  2380. getCSVHeaders(*childMeta, writer, ++layer);
  2381. layer--;
  2382. if (childname && *childname)
  2383. writer->outputEndNested(childname, !nameValid);
  2384. if (nameValid)
  2385. writer->outputEndNested(name, true);
  2386. }
  2387. }
  2388. break;
  2389. }
  2390. case FVFFblob: //for now FileViewer will output the string "[blob]"
  2391. {
  2392. Owned<ITypeInfo> stringType = makeStringType(UNKNOWN_LENGTH, NULL, NULL);
  2393. csvSplitXPath(meta->queryXPath(idx), xname, name);
  2394. StringBuffer eclTypeName;
  2395. stringType->getECLType(eclTypeName);
  2396. writer->outputCSVHeader(name, eclTypeName.str());
  2397. }
  2398. break;
  2399. default:
  2400. {
  2401. ITypeInfo & type = *column.type;
  2402. if (type.getTypeCode() == type_set)
  2403. {
  2404. childname = "Item";
  2405. csvSplitXPath(meta->queryXPath(idx), xname, name, &childname);
  2406. writer->outputBeginNested(name, true, true);
  2407. writer->outputEndNested(name, true);
  2408. }
  2409. else
  2410. {
  2411. csvSplitXPath(meta->queryXPath(idx), xname, name);
  2412. StringBuffer eclTypeName;
  2413. type.getECLType(eclTypeName);
  2414. writer->outputCSVHeader(name, eclTypeName.str());
  2415. }
  2416. break;
  2417. }
  2418. }
  2419. }
  2420. }
  2421. unsigned getResultCSV(IStringVal& ret, INewResultSet* result, const char* name, __int64 start, unsigned& count)
  2422. {
  2423. unsigned headerLayer = 0;
  2424. CSVOptions csvOptions;
  2425. csvOptions.delimiter.set(",");
  2426. csvOptions.terminator.set("\n");
  2427. csvOptions.includeHeader = true;
  2428. Owned<CommonCSVWriter> writer = new CommonCSVWriter(XWFtrim, csvOptions);
  2429. const IResultSetMetaData & meta = result->getMetaData();
  2430. getCSVHeaders(meta, writer, headerLayer);
  2431. writer->finishCSVHeaders();
  2432. Owned<IResultSetCursor> cursor = result->createCursor();
  2433. count = writeResultCursorXml(*writer, cursor, name, start, count, NULL);
  2434. ret.set(writer->str());
  2435. return count;
  2436. }
  2437. void appendResultSet(MemoryBuffer& mb, INewResultSet* result, const char *name, __int64 start, unsigned& count, __int64& total, bool bin, bool xsd, ESPSerializationFormat fmt, const IProperties *xmlns)
  2438. {
  2439. if (!result)
  2440. return;
  2441. total=result->getNumRows();
  2442. if(bin)
  2443. count = getResultBin(mb, result, (unsigned)start, count);
  2444. else
  2445. {
  2446. struct MemoryBuffer2IStringVal : public CInterface, implements IStringVal
  2447. {
  2448. MemoryBuffer2IStringVal(MemoryBuffer & _buffer) : buffer(_buffer) {}
  2449. IMPLEMENT_IINTERFACE;
  2450. virtual const char * str() const { UNIMPLEMENTED; }
  2451. virtual void set(const char *val) { buffer.append(strlen(val),val); }
  2452. virtual void clear() { } // support appending only
  2453. virtual void setLen(const char *val, unsigned length) { buffer.append(length, val); }
  2454. virtual unsigned length() const { return buffer.length(); };
  2455. MemoryBuffer & buffer;
  2456. } adaptor(mb);
  2457. if (fmt==ESPSerializationCSV)
  2458. count = getResultCSV(adaptor, result, name, (unsigned) start, count);
  2459. else if (fmt==ESPSerializationJSON)
  2460. count = getResultJSON(adaptor, result, name, (unsigned) start, count, (xsd) ? "myschema" : NULL);
  2461. else
  2462. count = getResultXml(adaptor, result, name, (unsigned) start, count, (xsd) ? "myschema" : NULL, xmlns);
  2463. }
  2464. }
  2465. INewResultSet* createFilteredResultSet(INewResultSet* result, IArrayOf<IConstNamedValue>* filterBy)
  2466. {
  2467. if (!result || !filterBy || !filterBy->length())
  2468. return NULL;
  2469. Owned<IFilteredResultSet> filter = result->createFiltered();
  2470. const IResultSetMetaData &meta = result->getMetaData();
  2471. unsigned columnCount = meta.getColumnCount();
  2472. ForEachItemIn(i, *filterBy)
  2473. {
  2474. IConstNamedValue &item = filterBy->item(i);
  2475. const char *name = item.getName();
  2476. const char *value = item.getValue();
  2477. if (!name || !*name || !value || !*value)
  2478. continue;
  2479. for(unsigned col = 0; col < columnCount; col++)
  2480. {
  2481. SCMStringBuffer scmbuf;
  2482. meta.getColumnLabel(scmbuf, col);
  2483. if (strieq(scmbuf.str(), name))
  2484. {
  2485. filter->addFilter(col, value);
  2486. break;
  2487. }
  2488. }
  2489. }
  2490. return filter->create();
  2491. }
  2492. void getWsWuResult(IEspContext &context, const char* wuid, const char *name, const char *logical, unsigned index, __int64 start,
  2493. unsigned& count, __int64& total, IStringVal& resname, bool bin, IArrayOf<IConstNamedValue>* filterBy, MemoryBuffer& mb,
  2494. WUState& wuState, bool xsd=true)
  2495. {
  2496. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2497. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  2498. if(!cw)
  2499. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid);
  2500. Owned<IConstWUResult> result;
  2501. if (notEmpty(name))
  2502. result.setown(cw->getResultByName(name));
  2503. else if (notEmpty(logical))
  2504. {
  2505. Owned<IConstWUResultIterator> it = &cw->getResults();
  2506. ForEach(*it)
  2507. {
  2508. IConstWUResult &r = it->query();
  2509. SCMStringBuffer filename;
  2510. if(strieq(r.getResultLogicalName(filename).str(), logical))
  2511. {
  2512. result.setown(LINK(&r));
  2513. break;
  2514. }
  2515. }
  2516. }
  2517. else
  2518. result.setown(cw->getResultBySequence(index));
  2519. if (!result)
  2520. throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT,"Cannot open the workunit result.");
  2521. if (!resname.length())
  2522. result->getResultName(resname);
  2523. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  2524. SCMStringBuffer logicalName;
  2525. result->getResultLogicalName(logicalName);
  2526. Owned<INewResultSet> rs;
  2527. if (logicalName.length())
  2528. {
  2529. rs.setown(resultSetFactory->createNewFileResultSet(logicalName.str(), cw->queryClusterName())); //MORE is this wrong cluster?
  2530. }
  2531. else
  2532. rs.setown(resultSetFactory->createNewResultSet(result, wuid));
  2533. if (!filterBy || !filterBy->length())
  2534. appendResultSet(mb, rs, name, start, count, total, bin, xsd, context.getResponseFormat(), result->queryResultXmlns());
  2535. else
  2536. {
  2537. Owned<INewResultSet> filteredResult = createFilteredResultSet(rs, filterBy);
  2538. appendResultSet(mb, filteredResult, name, start, count, total, bin, xsd, context.getResponseFormat(), result->queryResultXmlns());
  2539. }
  2540. wuState = cw->getState();
  2541. }
  2542. void checkFileSizeLimit(unsigned long xmlSize, unsigned long sizeLimit)
  2543. {
  2544. if ((sizeLimit > 0) && (xmlSize > sizeLimit))
  2545. throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE,
  2546. "The file size (%ld bytes) exceeds the size limit (%ld bytes). You may set 'Option > 1' or use 'Download_XML' link to get compressed file.",
  2547. xmlSize, sizeLimit);
  2548. }
  2549. void openSaveFile(IEspContext &context, int opt, __int64 sizeLimit, const char* filename, const char* origMimeType, MemoryBuffer& buf, IEspWULogFileResponse &resp)
  2550. {
  2551. if (opt < 1)
  2552. {
  2553. checkFileSizeLimit(buf.length(), sizeLimit);
  2554. resp.setThefile(buf);
  2555. resp.setThefile_mimetype(origMimeType);
  2556. }
  2557. else if (opt < 2)
  2558. {
  2559. checkFileSizeLimit(buf.length(), sizeLimit);
  2560. StringBuffer headerStr("attachment;");
  2561. if (filename && *filename)
  2562. {
  2563. const char* pFileName = strrchr(filename, PATHSEPCHAR);
  2564. if (pFileName)
  2565. headerStr.appendf("filename=%s", pFileName+1);
  2566. else
  2567. headerStr.appendf("filename=%s", filename);
  2568. }
  2569. MemoryBuffer buf0;
  2570. unsigned i = 0;
  2571. char* p = (char*) buf.toByteArray();
  2572. while (i < buf.length())
  2573. {
  2574. if (p[0] != 10)
  2575. buf0.append(p[0]);
  2576. else
  2577. buf0.append(0x0d);
  2578. p++;
  2579. i++;
  2580. }
  2581. resp.setThefile(buf);
  2582. resp.setThefile_mimetype(origMimeType);
  2583. context.addCustomerHeader("Content-disposition", headerStr.str());
  2584. }
  2585. else
  2586. {
  2587. #ifndef _USE_ZLIB
  2588. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2589. #else
  2590. StringBuffer fileNameStr, headerStr("attachment;");
  2591. if (notEmpty(filename))
  2592. {
  2593. fileNameStr.append(filename);
  2594. headerStr.append("filename=").append(filename).append((opt>2) ? ".gz" : ".zip");
  2595. }
  2596. else
  2597. fileNameStr.append("file");
  2598. StringBuffer ifname;
  2599. ifname.appendf("%s%sT%xAT%x", TEMPZIPDIR, PATHSEPSTR, (unsigned)(memsize_t)GetCurrentThreadId(), msTick()).append((opt>2)? "" : ".zip");
  2600. IZZIPor* Zipor = createZZIPor();
  2601. int ret = 0;
  2602. if (opt > 2)
  2603. ret = Zipor->gzipToFile(buf.length(), (void*)buf.toByteArray(), ifname.str());
  2604. else
  2605. ret = Zipor->zipToFile(buf.length(), (void*)buf.toByteArray(), fileNameStr.str(), ifname.str());
  2606. releaseIZ(Zipor);
  2607. if (ret < 0)
  2608. {
  2609. Owned<IFile> rFile = createIFile(ifname.str());
  2610. if (rFile->exists())
  2611. rFile->remove();
  2612. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2613. }
  2614. Owned <IFile> rf = createIFile(ifname.str());
  2615. if (!rf->exists())
  2616. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2617. MemoryBuffer out;
  2618. Owned <IFileIO> fio = rf->open(IFOread);
  2619. read(fio, 0, (size32_t) rf->size(), out);
  2620. resp.setThefile(out);
  2621. fio.clear();
  2622. rf->remove();
  2623. resp.setThefile_mimetype((opt > 2) ? "application/x-gzip" : "application/zip");
  2624. context.addCustomerHeader("Content-disposition", headerStr.str());
  2625. #endif
  2626. }
  2627. }
  2628. bool CWsWorkunitsEx::onWUFile(IEspContext &context,IEspWULogFileRequest &req, IEspWULogFileResponse &resp)
  2629. {
  2630. try
  2631. {
  2632. StringBuffer wuidStr(req.getWuid());
  2633. const char* wuidIn = wuidStr.trim().str();
  2634. if (wuidIn && *wuidIn)
  2635. {
  2636. if (!looksLikeAWuid(wuidIn, 'W'))
  2637. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID");
  2638. ensureWsWorkunitAccess(context, wuidIn, SecAccess_Read);
  2639. }
  2640. StringAttr wuid(wuidIn);
  2641. if (wuid.isEmpty() && notEmpty(req.getQuerySet()) && notEmpty(req.getQuery()))
  2642. {
  2643. Owned<IPropertyTree> registry = getQueryRegistry(req.getQuerySet(), false);
  2644. if (!registry)
  2645. throw MakeStringException(ECLWATCH_QUERYSET_NOT_FOUND, "Queryset %s not found", req.getQuerySet());
  2646. Owned<IPropertyTree> query = resolveQueryAlias(registry, req.getQuery());
  2647. if (!query)
  2648. throw MakeStringException(ECLWATCH_QUERYID_NOT_FOUND, "Query %s not found", req.getQuery());
  2649. resp.setQuerySet(req.getQuerySet());
  2650. resp.setQueryName(query->queryProp("@name"));
  2651. resp.setQueryId(query->queryProp("@id"));
  2652. wuid.set(query->queryProp("@wuid"));
  2653. }
  2654. int opt = req.getOption();
  2655. if (!wuid.isEmpty())
  2656. {
  2657. VStringBuffer logMsg("WUFile: %s", wuid.str());
  2658. if (notEmpty(req.getType()))
  2659. logMsg.append(", ").append(req.getType());
  2660. if (opt > 1)
  2661. logMsg.append(", download gzip");
  2662. else if (opt > 0)
  2663. logMsg.append(", download");
  2664. PROGLOG("%s", logMsg.str());
  2665. resp.setWuid(wuid.get());
  2666. MemoryBuffer mb;
  2667. WsWuInfo winfo(context, wuid);
  2668. if (strieq(File_ArchiveQuery, req.getType()))
  2669. {
  2670. winfo.getWorkunitArchiveQuery(mb);
  2671. openSaveFile(context, opt, req.getSizeLimit(), "ArchiveQuery.xml", HTTP_TYPE_APPLICATION_XML, mb, resp);
  2672. }
  2673. else if ((strieq(File_Cpp,req.getType()) || strieq(File_Log,req.getType())) && notEmpty(req.getName()))
  2674. {
  2675. winfo.getWorkunitCpp(req.getName(), req.getDescription(), req.getIPAddress(),mb, opt > 0, nullptr);
  2676. openSaveFile(context, opt, req.getSizeLimit(), req.getName(), HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2677. }
  2678. else if (strieq(File_DLL,req.getType()))
  2679. {
  2680. StringBuffer name;
  2681. winfo.getWorkunitDll(name, mb);
  2682. resp.setFileName(name.str());
  2683. resp.setDaliServer(daliServers.get());
  2684. openSaveFile(context, opt, req.getSizeLimit(), req.getName(), HTTP_TYPE_OCTET_STREAM, mb, resp);
  2685. }
  2686. else if (strieq(File_Res,req.getType()))
  2687. {
  2688. winfo.getWorkunitResTxt(mb);
  2689. openSaveFile(context, opt, req.getSizeLimit(), "res.txt", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2690. }
  2691. else if (strncmp(req.getType(), File_ThorLog, 7) == 0)
  2692. {
  2693. winfo.getWorkunitThorLog(req.getName(), mb, nullptr);
  2694. openSaveFile(context, opt, req.getSizeLimit(), "thormaster.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2695. }
  2696. else if (strieq(File_ThorSlaveLog,req.getType()))
  2697. {
  2698. winfo.getWorkunitThorSlaveLog(directories, req.getProcess(), req.getClusterGroup(), req.getIPAddress(),
  2699. req.getLogDate(), req.getSlaveNumber(), mb, nullptr, false);
  2700. openSaveFile(context, opt, req.getSizeLimit(), "ThorSlave.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2701. }
  2702. else if (strieq(File_EclAgentLog,req.getType()))
  2703. {
  2704. winfo.getWorkunitEclAgentLog(req.getName(), req.getProcess(), mb, nullptr);
  2705. openSaveFile(context, opt, req.getSizeLimit(), "eclagent.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2706. }
  2707. else if (strieq(File_XML,req.getType()) && notEmpty(req.getName()))
  2708. {
  2709. const char* name = req.getName();
  2710. const char* ptr = strrchr(name, '/');
  2711. if (ptr)
  2712. ptr++;
  2713. else
  2714. ptr = name;
  2715. winfo.getWorkunitAssociatedXml(name, req.getIPAddress(), req.getPlainText(), req.getDescription(), opt > 0, true, mb, nullptr);
  2716. openSaveFile(context, opt, req.getSizeLimit(), ptr, HTTP_TYPE_APPLICATION_XML, mb, resp);
  2717. }
  2718. else if (strieq(File_XML,req.getType()) || strieq(File_WUECL,req.getType()))
  2719. {
  2720. StringBuffer mimeType, fileName;
  2721. if (strieq(File_WUECL,req.getType()))
  2722. {
  2723. fileName.setf("%s.ecl", wuid.get());
  2724. winfo.getWorkunitQueryShortText(mb, nullptr);
  2725. mimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2726. }
  2727. else
  2728. {
  2729. fileName.setf("%s.xml", wuid.get());
  2730. winfo.getWorkunitXml(req.getPlainText(), mb);
  2731. if (opt < 2)
  2732. {
  2733. const char* plainText = req.getPlainText();
  2734. if (plainText && (!stricmp(plainText, "yes")))
  2735. mimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2736. else
  2737. mimeType.set(HTTP_TYPE_APPLICATION_XML);
  2738. }
  2739. else
  2740. {
  2741. mimeType.set(HTTP_TYPE_APPLICATION_XML);
  2742. }
  2743. }
  2744. openSaveFile(context, opt, req.getSizeLimit(), fileName.str(), mimeType.str(), mb, resp);
  2745. }
  2746. PROGLOG("%s -- done", logMsg.str());
  2747. }
  2748. }
  2749. catch(IException* e)
  2750. {
  2751. CErrorMessageFormat errorMessageFormat = req.getErrorMessageFormat();
  2752. if (errorMessageFormat == CErrorMessageFormat_XML)
  2753. context.setResponseFormat(ESPSerializationXML);
  2754. else if (errorMessageFormat == CErrorMessageFormat_JSON)
  2755. context.setResponseFormat(ESPSerializationJSON);
  2756. else if (errorMessageFormat == CErrorMessageFormat_Text)
  2757. context.setResponseFormat(ESPSerializationTEXT);
  2758. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2759. }
  2760. return true;
  2761. }
  2762. IPropertyTree *getArchivedWorkUnitProperties(const char *wuid, bool dfuWU)
  2763. {
  2764. SocketEndpoint ep;
  2765. getSashaNode(ep);
  2766. Owned<INode> node = createINode(ep);
  2767. if (!node)
  2768. throw MakeStringException(ECLWATCH_INODE_NOT_FOUND, "INode not found.");
  2769. StringBuffer tmp;
  2770. Owned<ISashaCommand> cmd = createSashaCommand();
  2771. cmd->addId(wuid);
  2772. cmd->setAction(SCA_GET);
  2773. cmd->setArchived(true);
  2774. if (dfuWU)
  2775. cmd->setDFU(true);
  2776. if (!cmd->send(node, 1*60*1000))
  2777. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,
  2778. "Sasha (%s) took too long to respond from: Get workUnit properties for %s.",
  2779. ep.getUrlStr(tmp).str(), wuid);
  2780. if ((cmd->numIds() < 1) || (cmd->numResults() < 1))
  2781. return nullptr;
  2782. cmd->getResult(0, tmp.clear());
  2783. if(tmp.length() < 1)
  2784. return nullptr;
  2785. Owned<IPropertyTree> wu = createPTreeFromXMLString(tmp.str());
  2786. if (!wu)
  2787. return nullptr;
  2788. return wu.getClear();
  2789. }
  2790. void getWorkunitCluster(IEspContext &context, const char *wuid, SCMStringBuffer &cluster, bool checkArchiveWUs)
  2791. {
  2792. if (isEmpty(wuid))
  2793. return;
  2794. if ('W' == wuid[0])
  2795. {
  2796. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2797. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  2798. if (cw)
  2799. cluster.set(cw->queryClusterName());
  2800. else if (checkArchiveWUs)
  2801. {
  2802. Owned<IPropertyTree> wuProps = getArchivedWorkUnitProperties(wuid, false);
  2803. if (wuProps)
  2804. cluster.set(wuProps->queryProp("@clusterName"));
  2805. }
  2806. }
  2807. else
  2808. {
  2809. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2810. Owned<IConstDFUWorkUnit> cw = factory->openWorkUnit(wuid, false);
  2811. if(cw)
  2812. {
  2813. StringBuffer tmp;
  2814. if (cw->getClusterName(tmp).length()!=0)
  2815. cluster.set(tmp.str());
  2816. }
  2817. else if (checkArchiveWUs)
  2818. {
  2819. Owned<IPropertyTree> wuProps = getArchivedWorkUnitProperties(wuid, true);
  2820. if (wuProps)
  2821. cluster.set(wuProps->queryProp("@clusterName"));
  2822. }
  2823. }
  2824. }
  2825. void getFileResults(IEspContext &context, const char *logicalName, const char *cluster, __int64 start, unsigned &count, __int64 &total,
  2826. IStringVal &resname, bool bin, IArrayOf<IConstNamedValue> *filterBy, MemoryBuffer &buf, bool xsd)
  2827. {
  2828. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  2829. Owned<INewResultSet> result(resultSetFactory->createNewFileResultSet(logicalName, cluster));
  2830. if (!filterBy || !filterBy->length())
  2831. appendResultSet(buf, result, resname.str(), start, count, total, bin, xsd, context.getResponseFormat(), NULL);
  2832. else
  2833. {
  2834. Owned<INewResultSet> filteredResult = createFilteredResultSet(result, filterBy);
  2835. appendResultSet(buf, filteredResult, resname.str(), start, count, total, bin, xsd, context.getResponseFormat(), NULL);
  2836. }
  2837. }
  2838. bool CWsWorkunitsEx::onWUResultBin(IEspContext &context,IEspWUResultBinRequest &req, IEspWUResultBinResponse &resp)
  2839. {
  2840. try
  2841. {
  2842. StringBuffer wuidStr(req.getWuid());
  2843. const char* wuidIn = wuidStr.trim().str();
  2844. if (wuidIn && *wuidIn)
  2845. {
  2846. if (!looksLikeAWuid(wuidIn, 'W'))
  2847. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuidIn);
  2848. ensureWsWorkunitAccess(context, wuidIn, SecAccess_Read);
  2849. }
  2850. MemoryBuffer mb;
  2851. __int64 total=0;
  2852. __int64 start = req.getStart() > 0 ? req.getStart() : 0;
  2853. unsigned count = req.getCount(), requested=count;
  2854. IArrayOf<IConstNamedValue>* filterBy = &req.getFilterBy();
  2855. SCMStringBuffer name;
  2856. if(strieq(req.getFormat(),"csv"))
  2857. context.setResponseFormat(ESPSerializationCSV);
  2858. WUState wuState = WUStateUnknown;
  2859. bool bin = (req.getFormat() && strieq(req.getFormat(),"raw"));
  2860. if (notEmpty(wuidIn) && notEmpty(req.getResultName()))
  2861. {
  2862. PROGLOG("WUResultBin: wuid %s, ResultName %s", wuidIn, req.getResultName());
  2863. getWsWuResult(context, wuidIn, req.getResultName(), NULL, 0, start, count, total, name, bin, filterBy, mb, wuState);
  2864. }
  2865. else if (notEmpty(wuidIn) && (req.getSequence() >= 0))
  2866. {
  2867. PROGLOG("WUResultBin: wuid %s, Sequence %d", wuidIn, req.getSequence());
  2868. getWsWuResult(context, wuidIn, NULL, NULL, req.getSequence(), start, count, total, name, bin,filterBy, mb, wuState);
  2869. }
  2870. else if (notEmpty(req.getLogicalName()))
  2871. {
  2872. const char* logicalName = req.getLogicalName();
  2873. const char* clusterIn = req.getCluster();
  2874. if (!isEmptyString(clusterIn))
  2875. getFileResults(context, logicalName, clusterIn, start, count, total, name, false, filterBy, mb, true);
  2876. else
  2877. {
  2878. StringBuffer wuid;
  2879. getWuidFromLogicalFileName(context, logicalName, wuid);
  2880. if (!wuid.length())
  2881. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot find the workunit for file %s.",logicalName);
  2882. SCMStringBuffer cluster;
  2883. getWorkunitCluster(context, wuid.str(), cluster, true);
  2884. if (cluster.length() > 0)
  2885. getFileResults(context, logicalName, cluster.str(), start, count, total, name, false, filterBy, mb, true);
  2886. else
  2887. getWsWuResult(context, wuid.str(), NULL, logicalName, 0, start, count, total, name, bin, filterBy, mb, wuState);
  2888. }
  2889. }
  2890. else
  2891. throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT,"Cannot open the workunit result.");
  2892. if(strieq(req.getFormat(),"csv"))
  2893. {
  2894. resp.setResult(mb);
  2895. resp.setResult_mimetype("text/csv");
  2896. context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.csv");
  2897. }
  2898. else if(stricmp(req.getFormat(),"xls")==0)
  2899. {
  2900. Owned<IProperties> params(createProperties());
  2901. params->setProp("showCount",0);
  2902. StringBuffer xml;
  2903. xml.append("<WUResultExcel><Result>").append(mb.length(), mb.toByteArray()).append("</Result></WUResultExcel>");
  2904. if (xml.length() > MAXXLSTRANSFER)
  2905. throw MakeStringException(ECLWATCH_TOO_BIG_DATA_SET, "The data set is too big to be converted to an Excel file. Please use the gzip link to download a compressed XML data file.");
  2906. StringBuffer xls;
  2907. xsltTransform(xml.str(), StringBuffer(getCFD()).append("./smc_xslt/result.xslt").str(), params, xls);
  2908. MemoryBuffer out;
  2909. out.setBuffer(xls.length(), (void*)xls.str());
  2910. resp.setResult(out);
  2911. resp.setResult_mimetype("application/vnd.ms-excel");
  2912. }
  2913. #ifdef _USE_ZLIB
  2914. else if(strieq(req.getFormat(),"zip") || strieq(req.getFormat(),"gzip"))
  2915. {
  2916. bool gzip = strieq(req.getFormat(),"gzip");
  2917. StringBuffer xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  2918. xml.append("<Result>").append(mb.length(),mb.toByteArray()).append("</Result>");
  2919. VStringBuffer ifname("%s%sT%xAT%x%s", TEMPZIPDIR, PATHSEPSTR, (unsigned)(memsize_t)GetCurrentThreadId(), msTick(), gzip ? "" : ".zip");
  2920. IZZIPor* Zipor = createZZIPor();
  2921. int ret = 0;
  2922. if (gzip)
  2923. ret = Zipor->gzipToFile(xml.length(), (void*)xml.str(), ifname.str());
  2924. else
  2925. ret = Zipor->zipToFile(xml.length(), (void*)xml.str(), "WUResult.xml", ifname.str());
  2926. releaseIZ(Zipor);
  2927. if (ret < 0)
  2928. {
  2929. Owned<IFile> rFile = createIFile(ifname.str());
  2930. if (rFile->exists())
  2931. rFile->remove();
  2932. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA, "The data cannot be compressed.");
  2933. }
  2934. MemoryBuffer out;
  2935. Owned <IFile> rf = createIFile(ifname.str());
  2936. if (rf->exists())
  2937. {
  2938. Owned <IFileIO> fio = rf->open(IFOread);
  2939. read(fio, 0, (size32_t) rf->size(), out);
  2940. resp.setResult(out);
  2941. }
  2942. if (gzip)
  2943. {
  2944. resp.setResult_mimetype("application/x-gzip");
  2945. context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.xml.gz");
  2946. }
  2947. else
  2948. {
  2949. resp.setResult_mimetype("application/zip");
  2950. context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.xml.zip");
  2951. }
  2952. Owned<IFile> rFile = createIFile(ifname.str());
  2953. if (rFile->exists())
  2954. rFile->remove();
  2955. }
  2956. #endif
  2957. else
  2958. {
  2959. resp.setResult(mb);
  2960. }
  2961. resp.setName(name.str());
  2962. resp.setWuid(wuidIn);
  2963. resp.setSequence(req.getSequence());
  2964. resp.setStart(start);
  2965. if (requested > total)
  2966. requested = (unsigned)total;
  2967. resp.setRequested(requested);
  2968. resp.setCount(count);
  2969. resp.setTotal(total);
  2970. resp.setFormat(req.getFormat());
  2971. }
  2972. catch(IException* e)
  2973. {
  2974. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2975. }
  2976. return true;
  2977. }
  2978. bool CWsWorkunitsEx::onWUResultSummary(IEspContext &context, IEspWUResultSummaryRequest &req, IEspWUResultSummaryResponse &resp)
  2979. {
  2980. try
  2981. {
  2982. StringBuffer wuid(req.getWuid());
  2983. WsWuHelpers::checkAndTrimWorkunit("WUResultSummary", wuid);
  2984. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2985. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  2986. if(!cw)
  2987. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  2988. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  2989. PROGLOG("WUResultSummary: %s", wuid.str());
  2990. resp.setWuid(wuid.str());
  2991. resp.setSequence(req.getSequence());
  2992. IArrayOf<IEspECLResult> results;
  2993. Owned<IConstWUResult> r = cw->getResultBySequence(req.getSequence());
  2994. if (r)
  2995. {
  2996. WsWuInfo winfo(context, cw);
  2997. winfo.getResult(*r, results, 0);
  2998. resp.setFormat(r->getResultFormat());
  2999. resp.setResult(results.item(0));
  3000. }
  3001. }
  3002. catch(IException* e)
  3003. {
  3004. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3005. }
  3006. return true;
  3007. }
  3008. bool CWsWorkunitsEx::onWUResult(IEspContext &context, IEspWUResultRequest &req, IEspWUResultResponse &resp)
  3009. {
  3010. try
  3011. {
  3012. StringBuffer wuidStr(req.getWuid());
  3013. const char* wuid = wuidStr.trim().str();
  3014. if (wuid && *wuid)
  3015. {
  3016. if (!looksLikeAWuid(wuid, 'W'))
  3017. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuid);
  3018. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  3019. }
  3020. MemoryBuffer mb;
  3021. SCMStringBuffer name;
  3022. __int64 total=0;
  3023. __int64 start = req.getStart() > 0 ? req.getStart() : 0;
  3024. unsigned count=req.getCount() ? req.getCount() : 100, requested=count;
  3025. unsigned seq = req.getSequence();
  3026. bool inclXsd = !req.getSuppressXmlSchema();
  3027. VStringBuffer filter("start=%" I64F "d;count=%d", start, count);
  3028. addToQueryString(filter, "clusterName", req.getCluster(), ';');
  3029. addToQueryString(filter, "logicalName", req.getLogicalName(), ';');
  3030. if (wuid && *wuid)
  3031. addToQueryString(filter, "wuid", wuid, ';');
  3032. addToQueryString(filter, "resultName", req.getResultName(), ';');
  3033. filter.appendf(";seq=%d;", seq);
  3034. if (inclXsd)
  3035. filter.append("xsd;");
  3036. if (context.getResponseFormat()==ESPSerializationJSON)
  3037. filter.append("json;");
  3038. IArrayOf<IConstNamedValue>* filterBy = &req.getFilterBy();
  3039. ForEachItemIn(i, *filterBy)
  3040. {
  3041. IConstNamedValue &item = filterBy->item(i);
  3042. const char *name = item.getName();
  3043. const char *value = item.getValue();
  3044. if (name && *name && value && *value)
  3045. addToQueryString(filter, name, value, ';');
  3046. }
  3047. const char* logicalName = req.getLogicalName();
  3048. const char* clusterName = req.getCluster();
  3049. const char* resultName = req.getResultName();
  3050. Owned<DataCacheElement> data;
  3051. if (!req.getBypassCachedResult())
  3052. data.setown(dataCache->lookup(context, filter, awusCacheMinutes));
  3053. if (data)
  3054. {
  3055. PROGLOG("Retrieving Cached WUResult: %s", filter.str());
  3056. mb.append(data->m_data.c_str());
  3057. name.set(data->m_name.c_str());
  3058. logicalName = data->m_logicalName.c_str();
  3059. wuid = data->m_wuid.c_str();
  3060. resultName = data->m_resultName.c_str();
  3061. seq = data->m_seq;
  3062. start = data->m_start;
  3063. count = data->m_rowcount;
  3064. requested = (unsigned)data->m_requested;
  3065. total = data->m_total;
  3066. if (notEmpty(logicalName))
  3067. resp.setLogicalName(logicalName);
  3068. else
  3069. {
  3070. if (notEmpty(wuid))
  3071. resp.setWuid(wuid);
  3072. resp.setSequence(seq);
  3073. }
  3074. }
  3075. else
  3076. {
  3077. PROGLOG("Retrieving WUResult: %s", filter.str());
  3078. WUState wuState = WUStateUnknown;
  3079. if(logicalName && *logicalName)
  3080. {
  3081. StringBuffer lwuid;
  3082. getWuidFromLogicalFileName(context, logicalName, lwuid);
  3083. SCMStringBuffer cluster;
  3084. if (lwuid.length())
  3085. getWorkunitCluster(context, lwuid.str(), cluster, true);
  3086. if (cluster.length())
  3087. {
  3088. getFileResults(context, logicalName, cluster.str(), start, count, total, name, false, filterBy, mb, inclXsd);
  3089. resp.setLogicalName(logicalName);
  3090. }
  3091. else if (notEmpty(clusterName))
  3092. {
  3093. getFileResults(context, logicalName, clusterName, start, count, total, name, false, filterBy, mb, inclXsd);
  3094. resp.setLogicalName(logicalName);
  3095. }
  3096. else
  3097. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Need valid target cluster to browse file %s.",logicalName);
  3098. Owned<IWorkUnitFactory> wf = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3099. Owned<IConstWorkUnit> cw = wf->openWorkUnit(lwuid.str());
  3100. if (cw)
  3101. wuState = cw->getState();
  3102. }
  3103. else if (notEmpty(wuid) && notEmpty(resultName))
  3104. {
  3105. name.set(resultName);
  3106. getWsWuResult(context, wuid, resultName, NULL, 0, start, count, total, name, false, filterBy, mb, wuState, inclXsd);
  3107. resp.setWuid(wuid);
  3108. resp.setSequence(seq);
  3109. }
  3110. else
  3111. {
  3112. getWsWuResult(context, wuid, NULL, NULL, seq, start, count, total, name, false, filterBy, mb, wuState, inclXsd);
  3113. resp.setWuid(wuid);
  3114. resp.setSequence(seq);
  3115. }
  3116. mb.append(0);
  3117. if (requested > total)
  3118. requested = (unsigned)total;
  3119. switch (wuState)
  3120. {
  3121. case WUStateCompleted:
  3122. case WUStateAborted:
  3123. case WUStateFailed:
  3124. case WUStateArchived:
  3125. dataCache->add(filter, mb.toByteArray(), name.str(), logicalName, wuid, resultName, seq, start, count, requested, total);
  3126. break;
  3127. }
  3128. }
  3129. resp.setName(name.str());
  3130. resp.setStart(start);
  3131. if (clusterName && *clusterName)
  3132. resp.setCluster(clusterName);
  3133. resp.setRequested(requested);
  3134. resp.setCount(count);
  3135. resp.setTotal(total);
  3136. resp.setResult(mb.toByteArray());
  3137. context.queryXslParameters()->setProp("escapeResults","1");
  3138. }
  3139. catch(IException* e)
  3140. {
  3141. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3142. }
  3143. return true;
  3144. }
  3145. void getScheduledWUs(IEspContext &context, WUShowScheduledFilters *filters, const char *serverName, IArrayOf<IEspScheduledWU> & results)
  3146. {
  3147. double version = context.getClientVersion();
  3148. if (notEmpty(serverName))
  3149. {
  3150. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3151. Owned<IScheduleReader> reader = getScheduleReader(serverName, filters->eventName);
  3152. Owned<IScheduleReaderIterator> it(reader->getIterator());
  3153. while(it->isValidEventName())
  3154. {
  3155. StringBuffer ieventName;
  3156. it->getEventName(ieventName);
  3157. while(it->isValidEventText())
  3158. {
  3159. StringBuffer ieventText;
  3160. it->getEventText(ieventText);
  3161. while(it->isValidWuid())
  3162. {
  3163. StringBuffer wuid;
  3164. it->getWuid(wuid);
  3165. if (wuid.length())
  3166. {
  3167. bool match = true;
  3168. unsigned stateID = WUStateUnknown;
  3169. StringBuffer jobName, owner;
  3170. SCMStringBuffer state;
  3171. try
  3172. {
  3173. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3174. if (cw)
  3175. {
  3176. jobName.set(cw->queryJobName());
  3177. owner.set(cw->queryUser());
  3178. }
  3179. if (!filters->jobName.isEmpty() && (jobName.isEmpty() || !WildMatch(jobName.str(), filters->jobName, true)))
  3180. match = false;
  3181. else if (!filters->owner.isEmpty() && (owner.isEmpty() || !WildMatch(owner, filters->owner, true)))
  3182. match = false;
  3183. else if (!filters->eventText.isEmpty() && (ieventText.isEmpty() || !WildMatch(ieventText, filters->eventText, true)))
  3184. match = false;
  3185. else if (!filters->state.isEmpty())
  3186. {
  3187. if (!cw)
  3188. match = false;
  3189. else
  3190. {
  3191. if ((cw->getState() == WUStateScheduled) && cw->aborting())
  3192. {
  3193. stateID = WUStateAborting;
  3194. state.set("aborting");
  3195. }
  3196. else
  3197. {
  3198. stateID = cw->getState();
  3199. state.set(cw->queryStateDesc());
  3200. }
  3201. if (!strieq(filters->state, state.str()))
  3202. match = false;
  3203. }
  3204. }
  3205. }
  3206. catch (IException *e)
  3207. {
  3208. EXCLOG(e, "Get scheduled WUs");
  3209. e->Release();
  3210. match = false;
  3211. }
  3212. if (!match)
  3213. {
  3214. it->nextWuid();
  3215. continue;
  3216. }
  3217. Owned<IEspScheduledWU> scheduledWU = createScheduledWU("");
  3218. scheduledWU->setWuid(wuid.str());
  3219. scheduledWU->setCluster(serverName);
  3220. if (ieventName.length())
  3221. scheduledWU->setEventName(ieventName.str());
  3222. if (ieventText.str())
  3223. scheduledWU->setEventText(ieventText.str());
  3224. if (jobName.length())
  3225. scheduledWU->setJobName(jobName.str());
  3226. if (version >= 1.51)
  3227. {
  3228. if (owner.length())
  3229. scheduledWU->setOwner(owner.str());
  3230. if (state.length())
  3231. {
  3232. scheduledWU->setStateID(stateID);
  3233. scheduledWU->setState(state.str());
  3234. }
  3235. }
  3236. results.append(*scheduledWU.getLink());
  3237. }
  3238. it->nextWuid();
  3239. }
  3240. it->nextEventText();
  3241. }
  3242. it->nextEventName();
  3243. }
  3244. }
  3245. return;
  3246. }
  3247. bool CWsWorkunitsEx::onWUShowScheduled(IEspContext &context, IEspWUShowScheduledRequest & req, IEspWUShowScheduledResponse & resp)
  3248. {
  3249. try
  3250. {
  3251. WUShowScheduledFilters filters(req.getCluster(), req.getState(), req.getOwner(),
  3252. req.getJobName(), req.getEventName(), req.getEventText());
  3253. IArrayOf<IEspScheduledWU> results;
  3254. if(notEmpty(req.getPushEventName()))
  3255. resp.setPushEventName(req.getPushEventName());
  3256. if(notEmpty(req.getPushEventText()))
  3257. resp.setPushEventText(req.getPushEventText());
  3258. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  3259. Owned<IConstEnvironment> environment = factory->openEnvironment();
  3260. Owned<IPropertyTree> root = &environment->getPTree();
  3261. unsigned i = 0;
  3262. Owned<IPropertyTreeIterator> ic = root->getElements("Software/Topology/Cluster");
  3263. IArrayOf<IEspServerInfo> servers;
  3264. ForEach(*ic)
  3265. {
  3266. IPropertyTree &cluster = ic->query();
  3267. const char *iclusterName = cluster.queryProp("@name");
  3268. if (isEmpty(iclusterName))
  3269. continue;
  3270. if (filters.cluster.isEmpty())
  3271. getScheduledWUs(context, &filters, iclusterName, results);
  3272. else if (strieq(filters.cluster, iclusterName))
  3273. {
  3274. getScheduledWUs(context, &filters, filters.cluster, results);
  3275. resp.setClusterSelected(i+1);
  3276. }
  3277. Owned<IEspServerInfo> server = createServerInfo("");
  3278. server->setName(iclusterName);
  3279. servers.append(*server.getLink());
  3280. i++;
  3281. }
  3282. if (servers.length())
  3283. resp.setClusters(servers);
  3284. if (results.length())
  3285. resp.setWorkunits(results);
  3286. bool first=false;
  3287. StringBuffer Query("PageFrom=Scheduler");
  3288. appendUrlParameter(Query, "EventName", filters.eventName, first);
  3289. appendUrlParameter(Query, "ECluster", filters.cluster, first);
  3290. resp.setQuery(Query.str());
  3291. }
  3292. catch(IException* e)
  3293. {
  3294. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3295. }
  3296. return true;
  3297. }
  3298. bool CWsWorkunitsEx::onWUExport(IEspContext &context, IEspWUExportRequest &req, IEspWUExportResponse &resp)
  3299. {
  3300. try
  3301. {
  3302. if (req.getECL() && *req.getECL())
  3303. throw makeStringException(0, "WUExport no longer supports filtering by ECL text");
  3304. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3305. WsWuSearch ws(context, req.getOwner(), req.getState(), req.getCluster(), req.getStartDate(), req.getEndDate(), req.getJobname());
  3306. StringBuffer xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Workunits>");
  3307. for(WsWuSearch::iterator it=ws.begin(); it!=ws.end(); it++)
  3308. {
  3309. Owned<IConstWorkUnit> cw = factory->openWorkUnit(it->c_str());
  3310. if (cw)
  3311. exportWorkUnitToXML(cw, xml, true, false, true);
  3312. }
  3313. xml.append("</Workunits>");
  3314. MemoryBuffer mb;
  3315. mb.setBuffer(xml.length(),(void*)xml.str());
  3316. resp.setExportData(mb);
  3317. resp.setExportData_mimetype(HTTP_TYPE_APPLICATION_XML);
  3318. }
  3319. catch(IException* e)
  3320. {
  3321. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3322. }
  3323. return true;
  3324. }
  3325. bool CWsWorkunitsEx::onWUListLocalFileRequired(IEspContext& context, IEspWUListLocalFileRequiredRequest& req, IEspWUListLocalFileRequiredResponse& resp)
  3326. {
  3327. try
  3328. {
  3329. StringBuffer wuid(req.getWuid());
  3330. WsWuHelpers::checkAndTrimWorkunit("WUListLocalFileRequired", wuid);
  3331. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  3332. PROGLOG("WUListLocalFileRequired: %s", wuid.str());
  3333. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3334. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3335. if (!cw)
  3336. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Workunit %s not found.", wuid.str());
  3337. IArrayOf<IEspLogicalFileUpload> localFiles;
  3338. Owned<IConstLocalFileUploadIterator> it = cw->getLocalFileUploads();
  3339. ForEach(*it)
  3340. {
  3341. Owned<IConstLocalFileUpload> file = it->get();
  3342. if(!file)
  3343. continue;
  3344. Owned<IEspLogicalFileUpload> up = createLogicalFileUpload();
  3345. SCMStringBuffer s;
  3346. up->setType(file->queryType());
  3347. up->setSource(file->getSource(s).str());
  3348. up->setDestination(file->getDestination(s).str());
  3349. up->setEventTag(file->getEventTag(s).str());
  3350. localFiles.append(*up.getLink());
  3351. }
  3352. resp.setLocalFileUploads(localFiles);
  3353. }
  3354. catch(IException* e)
  3355. {
  3356. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3357. }
  3358. return true;
  3359. }
  3360. typedef enum wsEclTypes_
  3361. {
  3362. wsEclTypeUnknown,
  3363. xsdString,
  3364. xsdBoolean,
  3365. xsdDecimal,
  3366. xsdFloat,
  3367. xsdDouble,
  3368. xsdDuration,
  3369. xsdDateTime,
  3370. xsdTime,
  3371. xsdDate,
  3372. xsdYearMonth,
  3373. xsdYear,
  3374. xsdMonthDay,
  3375. xsdDay,
  3376. xsdMonth,
  3377. xsdHexBinary,
  3378. xsdBase64Binary,
  3379. xsdAnyURI,
  3380. xsdQName,
  3381. xsdNOTATION,
  3382. xsdNormalizedString,
  3383. xsdToken,
  3384. xsdLanguage,
  3385. xsdNMTOKEN,
  3386. xsdNMTOKENS,
  3387. xsdName,
  3388. xsdNCName,
  3389. xsdID,
  3390. xsdIDREF,
  3391. xsdIDREFS,
  3392. xsdENTITY,
  3393. xsdENTITIES,
  3394. xsdInteger,
  3395. xsdNonPositiveInteger,
  3396. xsdNegativeInteger,
  3397. xsdLong,
  3398. xsdInt,
  3399. xsdShort,
  3400. xsdByte,
  3401. xsdNonNegativeInteger,
  3402. xsdUnsignedLong,
  3403. xsdUnsignedInt,
  3404. xsdUnsignedShort,
  3405. xsdUnsignedByte,
  3406. xsdPositiveInteger,
  3407. tnsRawDataFile,
  3408. tnsCsvDataFile,
  3409. tnsEspStringArray,
  3410. tnsEspIntArray,
  3411. tnsXmlDataSet,
  3412. maxWsEclType
  3413. } wsEclType;
  3414. bool CWsWorkunitsEx::onWUAddLocalFileToWorkunit(IEspContext& context, IEspWUAddLocalFileToWorkunitRequest& req, IEspWUAddLocalFileToWorkunitResponse& resp)
  3415. {
  3416. try
  3417. {
  3418. StringBuffer wuid(req.getWuid());
  3419. WsWuHelpers::checkAndTrimWorkunit("WUAddLocalFileToWorkunit", wuid);
  3420. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Write);
  3421. resp.setWuid(wuid.str());
  3422. const char* varname = req.getName();
  3423. if (isEmpty(varname))
  3424. {
  3425. resp.setResult("Name is not defined!");
  3426. return true;
  3427. }
  3428. resp.setName(varname);
  3429. PROGLOG("WUAddLocalFileToWorkunit: %s, name %s", wuid.str(), varname);
  3430. wsEclType type = (wsEclType) req.getType();
  3431. const char *val = req.getVal();
  3432. unsigned len = req.getLength();
  3433. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3434. WorkunitUpdate wu(factory->updateWorkUnit(wuid.str()));
  3435. if (!wu)
  3436. {
  3437. resp.setResult("Workunit not found!");
  3438. return true;
  3439. }
  3440. Owned<IWUResult> wuRslt = wu->updateResultByName(varname);
  3441. if (isEmpty(val))
  3442. val=req.getDefVal();
  3443. if (notEmpty(val))
  3444. {
  3445. switch (type)
  3446. {
  3447. case xsdBoolean:
  3448. wuRslt->setResultBool((strieq(val, "1") || strieq(val, "true") || strieq(val, "on")));
  3449. wuRslt->setResultStatus(ResultStatusSupplied);
  3450. break;
  3451. case xsdDecimal:
  3452. case xsdFloat:
  3453. case xsdDouble:
  3454. wuRslt->setResultReal(atof(val));
  3455. wuRslt->setResultStatus(ResultStatusSupplied);
  3456. break;
  3457. case xsdInteger:
  3458. case xsdNonPositiveInteger:
  3459. case xsdNegativeInteger:
  3460. case xsdLong:
  3461. case xsdInt:
  3462. case xsdShort:
  3463. case xsdByte:
  3464. case xsdNonNegativeInteger:
  3465. case xsdUnsignedLong:
  3466. case xsdUnsignedInt:
  3467. case xsdUnsignedShort:
  3468. case xsdUnsignedByte:
  3469. case xsdPositiveInteger:
  3470. wuRslt->setResultInt(_atoi64(val));
  3471. wuRslt->setResultStatus(ResultStatusSupplied);
  3472. break;
  3473. case tnsEspIntArray:
  3474. case tnsEspStringArray:
  3475. wuRslt->setResultRaw(len, val, ResultFormatXmlSet);
  3476. break;
  3477. case tnsRawDataFile:
  3478. wuRslt->setResultRaw(len, val, ResultFormatRaw);
  3479. break;
  3480. case tnsXmlDataSet:
  3481. wuRslt->setResultRaw(len, val, ResultFormatXml);
  3482. break;
  3483. case tnsCsvDataFile:
  3484. case xsdBase64Binary: //tbd
  3485. case xsdHexBinary:
  3486. break;
  3487. default:
  3488. wuRslt->setResultString(val, len);
  3489. wuRslt->setResultStatus(ResultStatusSupplied);
  3490. break;
  3491. }
  3492. }
  3493. resp.setResult("Result has been set as required!");
  3494. }
  3495. catch(IException* e)
  3496. {
  3497. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3498. }
  3499. return true;
  3500. }
  3501. bool CWsWorkunitsEx::onWUGetGraphNameAndTypes(IEspContext &context,IEspWUGetGraphNameAndTypesRequest &req, IEspWUGetGraphNameAndTypesResponse &resp)
  3502. {
  3503. try
  3504. {
  3505. StringBuffer wuid(req.getWuid());
  3506. WsWuHelpers::checkAndTrimWorkunit("WUGraphQuery", wuid);
  3507. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  3508. PROGLOG("WUGetGraphNameAndTypes: %s", wuid.str());
  3509. StringBuffer type(req.getType());
  3510. WUGraphType graphType = GraphTypeAny;
  3511. if (type.trim().length())
  3512. graphType = getGraphTypeFromString(type.str());
  3513. IArrayOf<IEspNameAndType> graphNameAndTypes;
  3514. WsWuInfo winfo(context, wuid.str());
  3515. winfo.getWUGraphNameAndTypes(graphType, graphNameAndTypes);
  3516. resp.setGraphNameAndTypes(graphNameAndTypes);
  3517. }
  3518. catch(IException* e)
  3519. {
  3520. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3521. }
  3522. return true;
  3523. }
  3524. bool CWsWorkunitsEx::onWUProcessGraph(IEspContext &context,IEspWUProcessGraphRequest &req, IEspWUProcessGraphResponse &resp)
  3525. {
  3526. try
  3527. {
  3528. StringBuffer wuid(req.getWuid());
  3529. WsWuHelpers::checkAndTrimWorkunit("WUProcessGraph", wuid);
  3530. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3531. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3532. if(!cw)
  3533. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3534. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3535. if (isEmpty(req.getName()))
  3536. throw MakeStringException(ECLWATCH_GRAPH_NOT_FOUND, "Please specify a graph name.");
  3537. Owned<IConstWUGraph> graph = cw->getGraph(req.getName());
  3538. if (!graph)
  3539. throw MakeStringException(ECLWATCH_GRAPH_NOT_FOUND, "Invalid graph name: %s for %s", req.getName(), wuid.str());
  3540. PROGLOG("WUProcessGraph: %s, Graph Name %s", wuid.str(), req.getName());
  3541. StringBuffer xml;
  3542. Owned<IPropertyTree> xgmml = graph->getXGMMLTree(true); // merge in graph progress information
  3543. toXML(xgmml.get(), xml);
  3544. resp.setTheGraph(xml.str());
  3545. }
  3546. catch(IException* e)
  3547. {
  3548. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3549. }
  3550. return true;
  3551. }
  3552. bool isRunning(IConstWorkUnit &cw)
  3553. {
  3554. // MORE - move into workunit interface
  3555. switch (cw.getState())
  3556. {
  3557. case WUStateFailed:
  3558. case WUStateAborted:
  3559. case WUStateCompleted:
  3560. return false;
  3561. default:
  3562. return true;
  3563. }
  3564. }
  3565. void CWsWorkunitsEx::readGraph(IEspContext& context, const char* subGraphId, WUGraphIDType& id, bool running,
  3566. IConstWUGraph* graph, IArrayOf<IEspECLGraphEx>& graphs)
  3567. {
  3568. SCMStringBuffer name, label, type;
  3569. graph->getName(name);
  3570. graph->getLabel(label);
  3571. graph->getTypeName(type);
  3572. Owned<IEspECLGraphEx> g = createECLGraphEx("","");
  3573. g->setName(name.str());
  3574. g->setLabel(label.str());
  3575. g->setType(type.str());
  3576. WUGraphState graphState = graph->getState();
  3577. if (running && (WUGraphRunning == graphState))
  3578. {
  3579. g->setRunning(true);
  3580. g->setRunningId(id);
  3581. }
  3582. else if (context.getClientVersion() > 1.20)
  3583. {
  3584. if (WUGraphComplete == graphState)
  3585. g->setComplete(true);
  3586. else if (WUGraphFailed == graphState)
  3587. g->setFailed(true);
  3588. }
  3589. Owned<IPropertyTree> xgmml = graph->getXGMMLTree(true);
  3590. // New functionality, if a subgraph id is specified and we only want to load the xgmml for that subgraph
  3591. // then we need to conditionally pull a propertytree from the xgmml graph one and use that for the xgmml.
  3592. //JCSMORE this should be part of the API and therefore allow *only* the subtree to be pulled from the backend.
  3593. StringBuffer xml;
  3594. if (notEmpty(subGraphId))
  3595. {
  3596. VStringBuffer xpath("//node[@id='%s']", subGraphId);
  3597. toXML(xgmml->queryPropTree(xpath.str()), xml);
  3598. }
  3599. else
  3600. toXML(xgmml, xml);
  3601. g->setGraph(xml.str());
  3602. graphs.append(*g.getClear());
  3603. }
  3604. bool CWsWorkunitsEx::onWUGetGraph(IEspContext& context, IEspWUGetGraphRequest& req, IEspWUGetGraphResponse& resp)
  3605. {
  3606. try
  3607. {
  3608. StringBuffer wuid(req.getWuid());
  3609. WsWuHelpers::checkAndTrimWorkunit("WUGetGraph", wuid);
  3610. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3611. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3612. if(!cw)
  3613. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3614. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3615. WUGraphIDType id;
  3616. SCMStringBuffer runningGraph;
  3617. bool running = (isRunning(*cw) && cw->getRunningGraph(runningGraph,id));
  3618. IArrayOf<IEspECLGraphEx> graphs;
  3619. if (isEmpty(req.getGraphName())) // JCS->GS - is this really required??
  3620. {
  3621. PROGLOG("WUGetGraph: %s", wuid.str());
  3622. Owned<IConstWUGraphIterator> it = &cw->getGraphs(GraphTypeAny);
  3623. ForEach(*it)
  3624. readGraph(context, req.getSubGraphId(), id, running, &it->query(), graphs);
  3625. }
  3626. else
  3627. {
  3628. PROGLOG("WUGetGraph: %s, Graph Name %s", wuid.str(), req.getGraphName());
  3629. Owned<IConstWUGraph> graph = cw->getGraph(req.getGraphName());
  3630. if (graph)
  3631. readGraph(context, req.getSubGraphId(), id, running, graph, graphs);
  3632. }
  3633. resp.setGraphs(graphs);
  3634. }
  3635. catch(IException* e)
  3636. {
  3637. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3638. }
  3639. return true;
  3640. }
  3641. bool CWsWorkunitsEx::onGVCAjaxGraph(IEspContext &context, IEspGVCAjaxGraphRequest &req, IEspGVCAjaxGraphResponse &resp)
  3642. {
  3643. try
  3644. {
  3645. resp.setName(req.getName());
  3646. resp.setGraphName(req.getGraphName());
  3647. resp.setGraphType("eclwatch");
  3648. double version = context.getClientVersion();
  3649. if (version > 1.19)
  3650. resp.setSubGraphId(req.getSubGraphId());
  3651. if (version > 1.20)
  3652. resp.setSubGraphOnly(req.getSubGraphOnly());
  3653. }
  3654. catch(IException* e)
  3655. {
  3656. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3657. }
  3658. return true;
  3659. }
  3660. bool CWsWorkunitsEx::onWUDetails(IEspContext &context, IEspWUDetailsRequest &req, IEspWUDetailsResponse &resp)
  3661. {
  3662. try
  3663. {
  3664. StringBuffer wuid(req.getWUID());
  3665. WsWuHelpers::checkAndTrimWorkunit("WUDetails", wuid);
  3666. PROGLOG("WUDetails: %s", wuid.str());
  3667. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3668. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3669. if(!cw)
  3670. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3671. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3672. WUDetails wuDetails(cw, wuid);
  3673. wuDetails.processRequest(req, resp);
  3674. }
  3675. catch(IException* e)
  3676. {
  3677. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3678. }
  3679. return true;
  3680. }
  3681. static void getWUDetailsMetaProperties(IArrayOf<IEspWUDetailsMetaProperty> & properties)
  3682. {
  3683. for (unsigned sk=StKindAll+1; sk<StMax;++sk)
  3684. {
  3685. const char * s = queryStatisticName((StatisticKind)sk);
  3686. if (s && *s)
  3687. {
  3688. Owned<IEspWUDetailsMetaProperty> property = createWUDetailsMetaProperty("","");
  3689. property->setName(s);
  3690. property->setValueType(CWUDetailsAttrValueType_Single);
  3691. properties.append(*property.getClear());
  3692. }
  3693. }
  3694. for (WuAttr attr=WaKind; attr<WaMax; ++attr)
  3695. {
  3696. Owned<IEspWUDetailsMetaProperty> property = createWUDetailsMetaProperty("","");
  3697. const char * s = queryWuAttributeName(attr);
  3698. assertex(s && *s);
  3699. property->setName(s);
  3700. if (isListAttribute(attr))
  3701. property->setValueType(CWUDetailsAttrValueType_List);
  3702. else if (isMultiAttribute(attr))
  3703. property->setValueType(CWUDetailsAttrValueType_Multi);
  3704. else
  3705. property->setValueType(CWUDetailsAttrValueType_Single);
  3706. properties.append(*property.getClear());
  3707. }
  3708. }
  3709. static void getWUDetailsMetaScopeTypes(StringArray & scopeTypes)
  3710. {
  3711. for (unsigned sst=SSTall+1; sst<SSTmax; ++sst)
  3712. {
  3713. const char * s = queryScopeTypeName((StatisticScopeType)sst);
  3714. if (s && *s)
  3715. scopeTypes.append(s);
  3716. }
  3717. }
  3718. static void getWUDetailsMetaMeasures(StringArray & measures)
  3719. {
  3720. for (unsigned measure=SMeasureAll+1; measure<SMeasureMax; ++measure)
  3721. {
  3722. const char *s = queryMeasureName((StatisticMeasure)measure);
  3723. if (s && *s)
  3724. measures.append(s);
  3725. }
  3726. }
  3727. static void getWUDetailsMetaActivities(IArrayOf<IConstWUDetailsActivityInfo> & activities)
  3728. {
  3729. for (unsigned kind=((unsigned)ThorActivityKind::TAKnone)+1; kind< TAKlast; ++kind)
  3730. {
  3731. Owned<IEspWUDetailsActivityInfo> activity = createWUDetailsActivityInfo("","");
  3732. const char * name = getActivityText(static_cast<ThorActivityKind>(kind));
  3733. assertex(name && *name);
  3734. activity->setKind(kind);
  3735. activity->setName(name);
  3736. activity->setIsSink(isActivitySink(static_cast<ThorActivityKind>(kind)));
  3737. activity->setIsSource(isActivitySource(static_cast<ThorActivityKind>(kind)));
  3738. activities.append(*activity.getClear());
  3739. }
  3740. }
  3741. bool CWsWorkunitsEx::onWUDetailsMeta(IEspContext &context, IEspWUDetailsMetaRequest &req, IEspWUDetailsMetaResponse &resp)
  3742. {
  3743. try
  3744. {
  3745. IArrayOf<IEspWUDetailsMetaProperty> properties;
  3746. getWUDetailsMetaProperties(properties);
  3747. resp.setProperties(properties);
  3748. StringArray scopeTypes;
  3749. getWUDetailsMetaScopeTypes(scopeTypes);
  3750. resp.setScopeTypes(scopeTypes);
  3751. StringArray measures;
  3752. getWUDetailsMetaMeasures(measures);
  3753. resp.setMeasures(measures);
  3754. IArrayOf<IConstWUDetailsActivityInfo> activities;
  3755. getWUDetailsMetaActivities(activities);
  3756. resp.setActivities(activities);
  3757. }
  3758. catch(IException* e)
  3759. {
  3760. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3761. }
  3762. return true;
  3763. }
  3764. #ifdef _USE_CPPUNIT
  3765. #include "unittests.hpp"
  3766. class WUDetailsMetaTest : public CppUnit::TestFixture
  3767. {
  3768. CPPUNIT_TEST_SUITE( WUDetailsMetaTest );
  3769. CPPUNIT_TEST(testWUDetailsMeta);
  3770. CPPUNIT_TEST_SUITE_END();
  3771. void testWUDetailsMeta()
  3772. {
  3773. // These calls also check that all the calls required to build WUDetailsMeta
  3774. // are successful.
  3775. IArrayOf<IEspWUDetailsMetaProperty> properties;
  3776. getWUDetailsMetaProperties(properties);
  3777. unsigned expectedOrdinalityProps = StMax - (StKindAll + 1) + (WaMax-WaKind);
  3778. ASSERT(properties.ordinality()==expectedOrdinalityProps);
  3779. StringArray scopeTypes;
  3780. getWUDetailsMetaScopeTypes(scopeTypes);
  3781. unsigned expectedOrdinalityScopeTypes = SSTmax - (SSTall+1);
  3782. ASSERT(scopeTypes.ordinality()==expectedOrdinalityScopeTypes);
  3783. StringArray measures;
  3784. getWUDetailsMetaMeasures(measures);
  3785. unsigned expectedOrdinalityMeasures = SMeasureMax - (SMeasureAll+1);
  3786. ASSERT(measures.ordinality()==expectedOrdinalityMeasures);
  3787. IArrayOf<IConstWUDetailsActivityInfo> activities;
  3788. getWUDetailsMetaActivities(activities);
  3789. unsigned expectedOrdinalityActivities = TAKlast - (TAKnone+1);
  3790. ASSERT(activities.ordinality()==expectedOrdinalityActivities);
  3791. }
  3792. };
  3793. CPPUNIT_TEST_SUITE_REGISTRATION( WUDetailsMetaTest );
  3794. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( WUDetailsMetaTest, "WUDetailsMetaTest" );
  3795. #endif // _USE_CPPUNIT
  3796. bool CWsWorkunitsEx::onWUGraphInfo(IEspContext &context,IEspWUGraphInfoRequest &req, IEspWUGraphInfoResponse &resp)
  3797. {
  3798. try
  3799. {
  3800. StringBuffer wuid(req.getWuid());
  3801. WsWuHelpers::checkAndTrimWorkunit("WUGraphInfo", wuid);
  3802. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3803. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3804. if(!cw)
  3805. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3806. ensureWsWorkunitAccess(context, *cw, SecAccess_Write);
  3807. resp.setWuid(wuid.str());
  3808. resp.setName(req.getName());
  3809. resp.setRunning(isRunning(*cw));
  3810. if (notEmpty(req.getGID()))
  3811. resp.setGID(req.getGID());
  3812. if(!req.getBatchWU_isNull())
  3813. resp.setBatchWU(req.getBatchWU());
  3814. }
  3815. catch(IException* e)
  3816. {
  3817. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3818. }
  3819. return true;
  3820. }
  3821. bool CWsWorkunitsEx::onWUGVCGraphInfo(IEspContext &context,IEspWUGVCGraphInfoRequest &req, IEspWUGVCGraphInfoResponse &resp)
  3822. {
  3823. try
  3824. {
  3825. StringBuffer wuid(req.getWuid());
  3826. WsWuHelpers::checkAndTrimWorkunit("WUGVCGraphInfo", wuid);
  3827. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3828. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3829. if(!cw)
  3830. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3831. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3832. resp.setWuid(wuid.str());
  3833. resp.setName(req.getName());
  3834. resp.setRunning(isRunning(*cw));
  3835. if (notEmpty(req.getGID()))
  3836. resp.setGID(req.getGID());
  3837. if(!req.getBatchWU_isNull())
  3838. resp.setBatchWU(req.getBatchWU());
  3839. StringBuffer xml("<Control><Endpoint><Query id=\"Gordon.Extractor.0\">");
  3840. xml.appendf("<Graph id=\"%s\">", req.getName());
  3841. if (context.getClientVersion() > 1.17)
  3842. {
  3843. xml.append("<Subgraph>");
  3844. xml.append(req.getSubgraphId_isNull() ? 0 : req.getSubgraphId());
  3845. xml.append("</Subgraph>");
  3846. }
  3847. xml.append("</Graph></Query></Endpoint></Control>");
  3848. resp.setTheGraph(xml.str());
  3849. }
  3850. catch(IException* e)
  3851. {
  3852. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3853. }
  3854. return true;
  3855. }
  3856. bool CWsWorkunitsEx::onWUGraphTiming(IEspContext &context, IEspWUGraphTimingRequest &req, IEspWUGraphTimingResponse &resp)
  3857. {
  3858. try
  3859. {
  3860. StringBuffer wuid(req.getWuid());
  3861. WsWuHelpers::checkAndTrimWorkunit("WUGraphTiming", wuid);
  3862. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3863. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3864. if(!cw)
  3865. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3866. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3867. PROGLOG("WUGraphTiming: %s", wuid.str());
  3868. resp.updateWorkunit().setWuid(wuid.str());
  3869. WsWuInfo winfo(context, cw);
  3870. IArrayOf<IConstECLTimingData> timingData;
  3871. winfo.getGraphTimingData(timingData);
  3872. resp.updateWorkunit().setTimingData(timingData);
  3873. }
  3874. catch(IException* e)
  3875. {
  3876. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3877. }
  3878. return true;
  3879. }
  3880. int CWsWorkunitsSoapBindingEx::onGetForm(IEspContext &context, CHttpRequest* request, CHttpResponse* response, const char *service, const char *method)
  3881. {
  3882. try
  3883. {
  3884. StringBuffer xml;
  3885. StringBuffer xslt;
  3886. if(strieq(method,"WUQuery") || strieq(method,"WUJobList"))
  3887. {
  3888. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  3889. Owned<IConstEnvironment> environment = factory->openEnvironment();
  3890. Owned<IPropertyTree> root = &environment->getPTree();
  3891. if(strieq(method,"WUQuery"))
  3892. {
  3893. SecAccessFlags accessOwn;
  3894. SecAccessFlags accessOthers;
  3895. getUserWuAccessFlags(context, accessOwn, accessOthers, false);
  3896. xml.append("<WUQuery>");
  3897. if ((accessOwn == SecAccess_None) && (accessOthers == SecAccess_None))
  3898. {
  3899. context.setAuthStatus(AUTH_STATUS_NOACCESS);
  3900. xml.appendf("<ErrorMessage>Access to workunit is denied.</ErrorMessage>");
  3901. }
  3902. else
  3903. {
  3904. MapStringTo<bool> added;
  3905. Owned<IPropertyTreeIterator> it = root->getElements("Software/Topology/Cluster");
  3906. ForEach(*it)
  3907. {
  3908. const char *name = it->query().queryProp("@name");
  3909. if (notEmpty(name) && !added.getValue(name))
  3910. {
  3911. added.setValue(name, true);
  3912. appendXMLTag(xml, "Cluster", name);
  3913. }
  3914. }
  3915. }
  3916. xml.append("</WUQuery>");
  3917. xslt.append(getCFD()).append("./smc_xslt/wuid_search.xslt");
  3918. }
  3919. else if (strieq(method,"WUJobList"))
  3920. {
  3921. StringBuffer cluster, defaultProcess, range;
  3922. request->getParameter("Cluster", cluster);
  3923. request->getParameter("Process",defaultProcess);
  3924. request->getParameter("Range",range);
  3925. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(cluster);
  3926. xml.append("<WUJobList>");
  3927. SecAccessFlags accessOwn;
  3928. SecAccessFlags accessOthers;
  3929. getUserWuAccessFlags(context, accessOwn, accessOthers, false);
  3930. if ((accessOwn == SecAccess_None) && (accessOthers == SecAccess_None))
  3931. {
  3932. context.setAuthStatus(AUTH_STATUS_NOACCESS);
  3933. xml.appendf("<ErrorMessage>Access to workunit is denied.</ErrorMessage>");
  3934. }
  3935. else
  3936. {
  3937. if (range.length())
  3938. appendXMLTag(xml, "Range", range.str());
  3939. if (clusterInfo)
  3940. {
  3941. const StringArray &thorInstances = clusterInfo->getThorProcesses();
  3942. ForEachItemIn(i, thorInstances)
  3943. {
  3944. const char* instance = thorInstances.item(i);
  3945. if (defaultProcess.length() && strieq(instance, defaultProcess.str()))
  3946. xml.append("<Cluster selected=\"1\">").append(instance).append("</Cluster>");
  3947. else
  3948. xml.append("<Cluster>").append(instance).append("</Cluster>");
  3949. }
  3950. }
  3951. xml.append("<TargetCluster>").append(cluster).append("</TargetCluster>");
  3952. }
  3953. xml.append("</WUJobList>");
  3954. xslt.append(getCFD()).append("./smc_xslt/jobs_search.xslt");
  3955. response->addHeader("Expires", "0");
  3956. }
  3957. }
  3958. if (xslt.length() && xml.length())
  3959. {
  3960. StringBuffer html;
  3961. xsltTransform(xml.str(), xslt.str(), NULL, html);
  3962. response->setContent(html.str());
  3963. response->setContentType(HTTP_TYPE_TEXT_HTML_UTF8);
  3964. response->send();
  3965. return 0;
  3966. }
  3967. }
  3968. catch(IException* e)
  3969. {
  3970. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3971. }
  3972. return onGetNotFound(context, request, response, service);
  3973. }
  3974. bool isDeploymentTypeCompressed(const char *type)
  3975. {
  3976. if (type && *type)
  3977. return (0==strncmp(type, "compressed_", strlen("compressed_")));
  3978. return false;
  3979. }
  3980. const char *skipCompressedTypeQualifier(const char *type)
  3981. {
  3982. if (isDeploymentTypeCompressed(type))
  3983. type += strlen("compressed_");
  3984. return type;
  3985. }
  3986. void deployEclOrArchive(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp)
  3987. {
  3988. NewWsWorkunit wu(context);
  3989. StringAttr wuid(wu->queryWuid()); // NB queryWuid() not valid after workunit,clear()
  3990. wu->setAction(WUActionCompile);
  3991. StringBuffer name(req.getName());
  3992. if (!name.trim().length() && notEmpty(req.getFileName()))
  3993. splitFilename(req.getFileName(), NULL, NULL, &name, NULL);
  3994. if (name.length())
  3995. wu->setJobName(name.str());
  3996. if (req.getObject().length())
  3997. {
  3998. MemoryBuffer mb;
  3999. const MemoryBuffer *uncompressed = &req.getObject();
  4000. if (isDeploymentTypeCompressed(req.getObjType()))
  4001. {
  4002. fastLZDecompressToBuffer(mb, req.getObject().bufferBase());
  4003. uncompressed = &mb;
  4004. }
  4005. StringBuffer text(uncompressed->length(), uncompressed->toByteArray());
  4006. wu.setQueryText(text.str());
  4007. }
  4008. if (req.getQueryMainDefinition())
  4009. wu.setQueryMain(req.getQueryMainDefinition());
  4010. if (req.getSnapshot())
  4011. wu->setSnapshot(req.getSnapshot());
  4012. if (!req.getResultLimit_isNull())
  4013. wu->setResultLimit(req.getResultLimit());
  4014. wu->commit();
  4015. wu.clear();
  4016. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), NULL, 0, true, false, false, NULL, NULL, &req.getDebugValues());
  4017. waitForWorkUnitToCompile(wuid.str(), req.getWait());
  4018. WsWuInfo winfo(context, wuid.str());
  4019. winfo.getCommon(resp.updateWorkunit(), WUINFO_All);
  4020. winfo.getExceptions(resp.updateWorkunit(), WUINFO_All);
  4021. name.clear();
  4022. if (notEmpty(resp.updateWorkunit().getJobname()))
  4023. origValueChanged(req.getName(), resp.updateWorkunit().getJobname(), name, false);
  4024. if (name.length()) //non generated user specified name, so override #Workunit('name')
  4025. {
  4026. WorkunitUpdate wx(&winfo.cw->lock());
  4027. wx->setJobName(name.str());
  4028. resp.updateWorkunit().setJobname(name.str());
  4029. }
  4030. PROGLOG("WUDeploy generates: %s", wuid.str());
  4031. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  4032. }
  4033. StringBuffer &sharedObjectFileName(StringBuffer &filename, const char *name, const char *ext, unsigned copy)
  4034. {
  4035. filename.append((name && *name) ? name : "workunit");
  4036. if (copy)
  4037. filename.append('_').append(copy);
  4038. if (notEmpty(ext))
  4039. filename.append(ext);
  4040. return filename;
  4041. }
  4042. inline StringBuffer &buildFullDllPath(StringBuffer &dllpath, StringBuffer &dllname, const char *dir, const char *name, const char *ext, unsigned copy)
  4043. {
  4044. return addPathSepChar(dllpath.set(dir)).append(sharedObjectFileName(dllname, name, ext, copy));
  4045. }
  4046. void writeTempSharedObject(const MemoryBuffer &obj, const char *dir, StringBuffer &filename)
  4047. {
  4048. OwnedIFileIO io = createUniqueFile(dir, "query_copy_dll_", NULL, filename);
  4049. io->write(0, obj.length(), obj.toByteArray());
  4050. }
  4051. void writeSharedObject(const char *srcpath, const MemoryBuffer &obj, const char *dir, StringBuffer &dllpath, StringBuffer &dllname)
  4052. {
  4053. StringBuffer name, ext;
  4054. if (srcpath && *srcpath)
  4055. splitFilename(srcpath, NULL, NULL, &name, &ext);
  4056. unsigned copy=0;
  4057. buildFullDllPath(dllpath.clear(), dllname.clear(), dir, name.str(), ext.str(), copy);
  4058. unsigned crc=0;
  4059. StringBuffer tempDllName;
  4060. const unsigned attempts = 3; // max attempts
  4061. for (unsigned i=0; i<attempts; i++)
  4062. {
  4063. while (checkFileExists(dllpath.str()))
  4064. {
  4065. if (crc==0)
  4066. crc = crc32(obj.toByteArray(), obj.length(), 0);
  4067. if (crc == crc_file(dllpath.str()))
  4068. {
  4069. DBGLOG("Workunit dll already exists: %s", dllpath.str());
  4070. if (tempDllName.length())
  4071. removeFileTraceIfFail(tempDllName);
  4072. return;
  4073. }
  4074. buildFullDllPath(dllpath.clear(), dllname.clear(), dir, name.str(), ext.str(), ++copy);
  4075. }
  4076. if (!tempDllName.length())
  4077. writeTempSharedObject(obj, dir, tempDllName);
  4078. try
  4079. {
  4080. renameFile(dllpath, tempDllName, false);
  4081. return;
  4082. }
  4083. catch (IException *e)
  4084. {
  4085. EXCLOG(e, "writeSharedObject"); //pretty small window for another copy of this dll to sneak by
  4086. e->Release();
  4087. }
  4088. }
  4089. throw MakeStringException(ECLWATCH_CANNOT_COPY_DLL, "Failed copying shared object %s", srcpath);
  4090. }
  4091. void deploySharedObject(IEspContext &context, StringBuffer &wuid, const char *filename, const char *cluster, const char *name, const MemoryBuffer &obj, const char *dir, const char *xml)
  4092. {
  4093. StringBuffer dllpath, dllname;
  4094. StringBuffer srcname(filename);
  4095. unsigned crc = 0;
  4096. Owned<IPropertyTree> srcxml;
  4097. if (xml && *xml)
  4098. {
  4099. srcxml.setown(createPTreeFromXMLString(xml));
  4100. if (srcxml && wuid.length())
  4101. {
  4102. crc = srcxml->getPropInt("Query[1]/Associated[1]/File[@type='dll'][1]/@crc", 0);
  4103. if (crc)
  4104. {
  4105. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  4106. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  4107. if (cw)
  4108. {
  4109. //is this a previous copy of same query, or a WUID collision?
  4110. if (cw->getHash() == (unsigned) srcxml->getPropInt64("@hash", 0))
  4111. {
  4112. Owned<IConstWUQuery> query = cw->getQuery();
  4113. if (query && crc == query->getQueryDllCrc())
  4114. return;
  4115. }
  4116. }
  4117. }
  4118. }
  4119. }
  4120. if (!srcname.length())
  4121. srcname.append(name).append(SharedObjectExtension);
  4122. writeSharedObject(srcname.str(), obj, dir, dllpath, dllname);
  4123. NewWsWorkunit wu(context, wuid); //duplicate wuid made unique
  4124. wuid.set(wu->queryWuid());
  4125. wu->setClusterName(cluster);
  4126. wu->commit();
  4127. StringBuffer dllXML;
  4128. if (getWorkunitXMLFromFile(dllpath.str(), dllXML))
  4129. {
  4130. Owned<ILocalWorkUnit> embeddedWU = createLocalWorkUnit(dllXML.str());
  4131. queryExtendedWU(wu)->copyWorkUnit(embeddedWU, true, true);
  4132. }
  4133. wu.associateDll(dllpath.str(), dllname.str());
  4134. if (name && *name)
  4135. wu->setJobName(name);
  4136. //clean slate, copy only select items from processed workunit xml
  4137. if (srcxml)
  4138. {
  4139. if (srcxml->hasProp("@jobName"))
  4140. wu->setJobName(srcxml->queryProp("@jobName"));
  4141. if (srcxml->hasProp("Query/Text"))
  4142. wu.setQueryText(srcxml->queryProp("Query/Text"));
  4143. }
  4144. wu->setState(WUStateCompiled);
  4145. wu->commit();
  4146. wu.clear();
  4147. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  4148. }
  4149. void CWsWorkunitsEx::deploySharedObjectReq(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp, const char *dir, const char *xml)
  4150. {
  4151. if (isEmpty(req.getFileName()))
  4152. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File name required when deploying a shared object.");
  4153. const char *cluster = req.getCluster();
  4154. if (isEmpty(cluster))
  4155. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster name required when deploying a shared object.");
  4156. const MemoryBuffer *uncompressed = &req.getObject();
  4157. MemoryBuffer mb;
  4158. if (isDeploymentTypeCompressed(req.getObjType()))
  4159. {
  4160. fastLZDecompressToBuffer(mb, req.getObject().bufferBase());
  4161. uncompressed = &mb;
  4162. }
  4163. StringBuffer wuid;
  4164. deploySharedObject(context, wuid, req.getFileName(), cluster, req.getName(), *uncompressed, dir, xml);
  4165. WsWuInfo winfo(context, wuid.str());
  4166. winfo.getCommon(resp.updateWorkunit(), WUINFO_All);
  4167. PROGLOG("WUDeploy generates: %s", wuid.str());
  4168. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  4169. }
  4170. bool CWsWorkunitsEx::onWUDeployWorkunit(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp)
  4171. {
  4172. const char *type = skipCompressedTypeQualifier(req.getObjType());
  4173. try
  4174. {
  4175. ensureWsCreateWorkunitAccess(context);
  4176. if (notEmpty(req.getCluster()) && !isValidCluster(req.getCluster()))
  4177. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", req.getCluster());
  4178. if (!type || !*type)
  4179. throw MakeStringExceptionDirect(ECLWATCH_INVALID_INPUT, "WUDeployWorkunit unspecified object type.");
  4180. if (strieq(type, "archive")|| strieq(type, "ecl_text"))
  4181. deployEclOrArchive(context, req, resp);
  4182. else if (strieq(type, "shared_object"))
  4183. deploySharedObjectReq(context, req, resp, queryDirectory.str());
  4184. else
  4185. throw MakeStringException(ECLWATCH_INVALID_INPUT, "WUDeployWorkunit '%s' unknown object type.", type);
  4186. }
  4187. catch(IException* e)
  4188. {
  4189. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4190. }
  4191. return true;
  4192. }
  4193. bool CWsWorkunitsEx::onWUCreateZAPInfo(IEspContext &context, IEspWUCreateZAPInfoRequest &req, IEspWUCreateZAPInfoResponse &resp)
  4194. {
  4195. try
  4196. {
  4197. CWsWuZAPInfoReq zapInfoReq;
  4198. zapInfoReq.wuid = req.getWuid();
  4199. WsWuHelpers::checkAndTrimWorkunit("WUCreateZAPInfo", zapInfoReq.wuid);
  4200. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  4201. Owned<IConstWorkUnit> cwu = factory->openWorkUnit(zapInfoReq.wuid.str());
  4202. if(!cwu.get())
  4203. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Cannot open workunit %s.", zapInfoReq.wuid.str());
  4204. ensureWsWorkunitAccess(context, *cwu, SecAccess_Read);
  4205. PROGLOG("WUCreateZAPInfo(): %s", zapInfoReq.wuid.str());
  4206. zapInfoReq.espIP = req.getESPIPAddress();
  4207. zapInfoReq.thorIP = req.getThorIPAddress();
  4208. zapInfoReq.problemDesc = req.getProblemDescription();
  4209. zapInfoReq.whatChanged = req.getWhatChanged();
  4210. zapInfoReq.whereSlow = req.getWhereSlow();
  4211. zapInfoReq.includeThorSlaveLog = req.getIncludeThorSlaveLog();
  4212. zapInfoReq.zapFileName = req.getZAPFileName();
  4213. zapInfoReq.password = req.getZAPPassword();
  4214. StringBuffer zipFileName, zipFileNameWithPath;
  4215. //CWsWuFileHelper may need ESP's <Directories> settings to locate log files.
  4216. CWsWuFileHelper helper(directories);
  4217. helper.createWUZAPFile(context, cwu, zapInfoReq, zipFileName, zipFileNameWithPath, thorSlaveLogThreadPoolSize);
  4218. //Download ZIP file to user
  4219. Owned<IFile> f = createIFile(zipFileNameWithPath.str());
  4220. Owned<IFileIO> io = f->open(IFOread);
  4221. unsigned zapFileSize = (unsigned) io->size();
  4222. if (zapFileSize > MAX_ZAP_BUFFER_SIZE)
  4223. throw MakeStringException(ECLWATCH_INVALID_INPUT, "WUCreateZAPInfo: ZAP file size is too big (>10M) to be retrieved. Please call /WsWorkunits/WUCreateAndDownloadZAPInfo using HTTP GET.");
  4224. MemoryBuffer mb;
  4225. void * data = mb.reserve(zapFileSize);
  4226. size32_t read = io->read(0, zapFileSize, data);
  4227. mb.setLength(read);
  4228. resp.setThefile(mb);
  4229. resp.setThefile_mimetype(HTTP_TYPE_OCTET_STREAM);
  4230. resp.setZAPFileName(zipFileName.str());
  4231. StringBuffer headerStr("attachment;filename=");
  4232. headerStr.append(zipFileName.str());
  4233. context.addCustomerHeader("Content-disposition", headerStr.str());
  4234. io->close();
  4235. f->remove();
  4236. }
  4237. catch(IException* e)
  4238. {
  4239. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4240. }
  4241. return true;
  4242. }
  4243. bool CWsWorkunitsEx::onWUGetZAPInfo(IEspContext &context, IEspWUGetZAPInfoRequest &req, IEspWUGetZAPInfoResponse &resp)
  4244. {
  4245. try
  4246. {
  4247. StringBuffer wuid(req.getWUID());
  4248. WsWuHelpers::checkAndTrimWorkunit("WUGetZAPInfo", wuid);
  4249. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  4250. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  4251. if(!cw)
  4252. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  4253. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  4254. PROGLOG("WUGetZAPInfo: %s", wuid.str());
  4255. StringBuffer EspIP, ThorIP;
  4256. resp.setWUID(wuid.str());
  4257. resp.setBuildVersion(getBuildVersion());
  4258. IpAddress ipaddr = queryHostIP();
  4259. ipaddr.getIpText(EspIP);
  4260. resp.setESPIPAddress(EspIP.str());
  4261. //Get Archive
  4262. Owned<IConstWUQuery> query = cw->getQuery();
  4263. if(query)
  4264. {
  4265. SCMStringBuffer queryText;
  4266. query->getQueryText(queryText);
  4267. if (queryText.length() && isArchiveQuery(queryText.str()))
  4268. resp.setArchive(queryText.str());
  4269. }
  4270. //Get Thor IP
  4271. BoolHash uniqueProcesses;
  4272. Owned<IStringIterator> thorInstances = cw->getProcesses("Thor");
  4273. ForEach (*thorInstances)
  4274. {
  4275. SCMStringBuffer processName;
  4276. thorInstances->str(processName);
  4277. if (processName.length() < 1)
  4278. continue;
  4279. bool* found = uniqueProcesses.getValue(processName.str());
  4280. if (found && *found)
  4281. continue;
  4282. uniqueProcesses.setValue(processName.str(), true);
  4283. Owned<IStringIterator> thorLogs = cw->getLogs("Thor", processName.str());
  4284. ForEach (*thorLogs)
  4285. {
  4286. SCMStringBuffer logName;
  4287. thorLogs->str(logName);
  4288. if (!logName.length())
  4289. continue;
  4290. const char* thorIPPtr = NULL;
  4291. const char* ptr = logName.str();
  4292. while (ptr)
  4293. {
  4294. if (!thorIPPtr && (*ptr != '/'))
  4295. thorIPPtr = ptr;
  4296. else if (thorIPPtr && (*ptr == '/'))
  4297. break;
  4298. ptr++;
  4299. }
  4300. if (!thorIPPtr)
  4301. continue;
  4302. //Found a thor IP
  4303. if (ThorIP.length())
  4304. ThorIP.append(",");
  4305. if (!*ptr)
  4306. ThorIP.append(thorIPPtr);
  4307. else
  4308. ThorIP.append(ptr-thorIPPtr, thorIPPtr);
  4309. }
  4310. }
  4311. if (ThorIP.length())
  4312. resp.setThorIPAddress(ThorIP.str());
  4313. double version = context.getClientVersion();
  4314. if (version >= 1.73)
  4315. {
  4316. resp.setEmailTo(zapEmailTo.get());
  4317. resp.setEmailFrom(zapEmailFrom.get());
  4318. }
  4319. }
  4320. catch(IException* e)
  4321. {
  4322. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4323. }
  4324. return true;
  4325. }
  4326. bool CWsWorkunitsEx::onWUCheckFeatures(IEspContext &context, IEspWUCheckFeaturesRequest &req, IEspWUCheckFeaturesResponse &resp)
  4327. {
  4328. resp.setBuildVersionMajor(BUILD_VERSION_MAJOR);
  4329. resp.setBuildVersionMinor(BUILD_VERSION_MINOR);
  4330. resp.setBuildVersionPoint(BUILD_VERSION_POINT);
  4331. resp.setMaxRequestEntityLength(maxRequestEntityLength);
  4332. resp.updateDeployment().setUseCompression(true);
  4333. return true;
  4334. }
  4335. static const char * checkGetStatsNullInput(const char * s)
  4336. {
  4337. if (!s || !*s)
  4338. return nullptr;
  4339. return s;
  4340. }
  4341. static const char * checkGetStatsInput(const char * s)
  4342. {
  4343. if (!s || !*s)
  4344. return "*";
  4345. return s;
  4346. }
  4347. bool CWsWorkunitsEx::onWUGetStats(IEspContext &context, IEspWUGetStatsRequest &req, IEspWUGetStatsResponse &resp)
  4348. {
  4349. //This function is deprecated for 7.x and will be removed shortly afterwards.
  4350. //Anything that cannot be implemented with the scope iterator is implemented as a post filter
  4351. try
  4352. {
  4353. const char* creatorType = checkGetStatsNullInput(req.getCreatorType());
  4354. const char* creator = checkGetStatsNullInput(req.getCreator());
  4355. const char* scopeType = checkGetStatsNullInput(req.getScopeType());
  4356. const char* scope = checkGetStatsNullInput(req.getScope());
  4357. const char* kind = checkGetStatsNullInput(req.getKind());
  4358. const char* measure = req.getMeasure();
  4359. WuScopeFilter filter;
  4360. StatisticsFilter statsFilter(creatorType, creator, "*", "*", "*", "*");
  4361. filter.addOutputProperties(PTstatistics);
  4362. if (scopeType)
  4363. filter.addScopeType(scopeType);
  4364. if (scope)
  4365. filter.addScope(scope);
  4366. if (kind)
  4367. filter.addOutputStatistic(kind);
  4368. if (measure)
  4369. filter.setMeasure(measure);
  4370. if (!req.getMinScopeDepth_isNull() && !req.getMaxScopeDepth_isNull())
  4371. filter.setDepth(req.getMinScopeDepth(), req.getMaxScopeDepth());
  4372. else if (!req.getMinScopeDepth_isNull())
  4373. filter.setDepth(req.getMinScopeDepth(), req.getMinScopeDepth());
  4374. if (!req.getMinValue_isNull() || !req.getMaxValue_isNull())
  4375. {
  4376. unsigned __int64 lowValue = 0;
  4377. unsigned __int64 highValue = MaxStatisticValue;
  4378. if (!req.getMinValue_isNull())
  4379. lowValue = (unsigned __int64)req.getMinValue();
  4380. if (!req.getMaxValue_isNull())
  4381. highValue = (unsigned __int64)req.getMaxValue();
  4382. statsFilter.setValueRange(lowValue, highValue);
  4383. }
  4384. const char * textFilter = req.getFilter();
  4385. if (textFilter)
  4386. statsFilter.setFilter(textFilter);
  4387. filter.setIncludeNesting(0).finishedFilter();
  4388. bool createDescriptions = false;
  4389. if (!req.getCreateDescriptions_isNull())
  4390. createDescriptions = req.getCreateDescriptions();
  4391. StringBuffer wuid(req.getWUID());
  4392. PROGLOG("WUGetStats: %s", wuid.str());
  4393. IArrayOf<IEspWUStatisticItem> statistics;
  4394. if (strchr(wuid, '*'))
  4395. {
  4396. WUSortField filters[2];
  4397. MemoryBuffer filterbuf;
  4398. filters[0] = WUSFwildwuid;
  4399. filterbuf.append(wuid.str());
  4400. filters[1] = WUSFterm;
  4401. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  4402. Owned<IConstWorkUnitIterator> iter = factory->getWorkUnitsSorted((WUSortField) (WUSFwuid), filters, filterbuf.bufferBase(), 0, INT_MAX, NULL, NULL);
  4403. ForEach(*iter)
  4404. {
  4405. Owned<IConstWorkUnit> workunit = factory->openWorkUnit(iter->query().queryWuid());
  4406. if (workunit)
  4407. {
  4408. //No need to check for access since the list is already filtered
  4409. WsWuInfo winfo(context, workunit->queryWuid());
  4410. winfo.getStats(filter, statsFilter, createDescriptions, statistics);
  4411. }
  4412. }
  4413. }
  4414. else
  4415. {
  4416. WsWuHelpers::checkAndTrimWorkunit("WUInfo", wuid);
  4417. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  4418. WsWuInfo winfo(context, wuid);
  4419. winfo.getStats(filter, statsFilter, createDescriptions, statistics);
  4420. }
  4421. resp.setStatistics(statistics);
  4422. resp.setWUID(wuid.str());
  4423. }
  4424. catch(IException* e)
  4425. {
  4426. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4427. }
  4428. return true;
  4429. }
  4430. IPropertyTree* CWsWorkunitsEx::getWorkunitArchive(IEspContext &context, WsWuInfo& winfo, const char* wuid, unsigned cacheMinutes)
  4431. {
  4432. Owned<WUArchiveCacheElement> wuArchive = wuArchiveCache->lookup(context, wuid, cacheMinutes);
  4433. if (wuArchive)
  4434. return wuArchive->archive.getLink();
  4435. Owned<IPropertyTree> archive = winfo.getWorkunitArchive();
  4436. if (!archive)
  4437. return NULL;
  4438. wuArchiveCache->add(wuid, archive.getLink());
  4439. return archive.getClear();
  4440. }
  4441. bool CWsWorkunitsEx::onWUListArchiveFiles(IEspContext &context, IEspWUListArchiveFilesRequest &req, IEspWUListArchiveFilesResponse &resp)
  4442. {
  4443. try
  4444. {
  4445. const char* wuid = req.getWUID();
  4446. if (isEmpty(wuid))
  4447. throw MakeStringException(ECLWATCH_NO_WUID_SPECIFIED, "No workunit defined.");
  4448. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  4449. PROGLOG("WUListArchiveFiles: %s", wuid);
  4450. WsWuInfo winfo(context, wuid);
  4451. Owned<IPropertyTree> archive = getWorkunitArchive(context, winfo, wuid, WUARCHIVE_CACHE_MINITES);
  4452. if (!archive)
  4453. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No workunit archive found for %s.", wuid);
  4454. IArrayOf<IEspWUArchiveModule> modules;
  4455. IArrayOf<IEspWUArchiveFile> files;
  4456. winfo.listArchiveFiles(archive, "", modules, files);
  4457. if (modules.length())
  4458. resp.setArchiveModules(modules);
  4459. if (files.length())
  4460. resp.setFiles(files);
  4461. if (!modules.length() && !files.length())
  4462. resp.setMessage("Files not found");
  4463. }
  4464. catch(IException* e)
  4465. {
  4466. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4467. }
  4468. return true;
  4469. }
  4470. bool CWsWorkunitsEx::onWUGetArchiveFile(IEspContext &context, IEspWUGetArchiveFileRequest &req, IEspWUGetArchiveFileResponse &resp)
  4471. {
  4472. try
  4473. {
  4474. const char* wuid = req.getWUID();
  4475. const char* moduleName = req.getModuleName();
  4476. const char* attrName = req.getFileName();
  4477. if (isEmpty(wuid))
  4478. throw MakeStringException(ECLWATCH_NO_WUID_SPECIFIED, "No workunit defined.");
  4479. if (isEmpty(moduleName) && isEmpty(attrName))
  4480. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No file name defined.");
  4481. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  4482. PROGLOG("WUGetArchiveFile: %s", wuid);
  4483. WsWuInfo winfo(context, wuid);
  4484. Owned<IPropertyTree> archive = getWorkunitArchive(context, winfo, wuid, WUARCHIVE_CACHE_MINITES);
  4485. if (!archive)
  4486. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No workunit archive found for %s.", wuid);
  4487. StringBuffer file;
  4488. winfo.getArchiveFile(archive, moduleName, attrName, req.getPath(), file);
  4489. if (file.length())
  4490. resp.setFile(file.str());
  4491. else
  4492. resp.setMessage("File not found");
  4493. }
  4494. catch(IException* e)
  4495. {
  4496. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4497. }
  4498. return true;
  4499. }
  4500. const char *CWsWorkunitsEx::gatherQueryFileCopyErrors(IArrayOf<IConstLogicalFileError> &errors, StringBuffer &errorMsg)
  4501. {
  4502. if (!errors.ordinality())
  4503. return errorMsg.str();
  4504. errorMsg.append("Query File Copy Error(s):");
  4505. ForEachItemIn(i, errors)
  4506. {
  4507. IConstLogicalFileError &error = errors.item(i);
  4508. errorMsg.append(" ").append(error.getLogicalName()).append(": ");
  4509. errorMsg.append(error.getError()).append(";");
  4510. }
  4511. return errorMsg.str();
  4512. }
  4513. const char *CWsWorkunitsEx::gatherExceptionMessage(const IMultiException &me, StringBuffer &exceptionMsg)
  4514. {
  4515. exceptionMsg.append("Exception(s):");
  4516. aindex_t count = me.ordinality();
  4517. for (aindex_t i=0; i<count; i++)
  4518. {
  4519. IException& e = me.item(i);
  4520. StringBuffer errMsg;
  4521. exceptionMsg.append(" ").append(e.errorCode()).append(": ");
  4522. exceptionMsg.append(e.errorMessage(errMsg).str()).append(";");
  4523. }
  4524. exceptionMsg.append("\n");
  4525. return exceptionMsg.str();
  4526. }
  4527. const char *CWsWorkunitsEx::gatherWUException(IConstWUExceptionIterator &it, StringBuffer &exceptionMsg)
  4528. {
  4529. unsigned numErr = 0, numWRN = 0, numInf = 0, numAlert = 0;
  4530. ForEach(it)
  4531. {
  4532. IConstWUException & cur = it.query();
  4533. SCMStringBuffer src, msg, file;
  4534. exceptionMsg.append(" Exception: Code: ").append(cur.getExceptionCode());
  4535. exceptionMsg.append(" Source: ").append(cur.getExceptionSource(src).str());
  4536. exceptionMsg.append(" Message: ").append(cur.getExceptionMessage(msg).str());
  4537. exceptionMsg.append(" FileName: ").append(cur.getExceptionFileName(file).str());
  4538. exceptionMsg.append(" LineNo: ").append(cur.getExceptionLineNo());
  4539. exceptionMsg.append(" Column: ").append(cur.getExceptionColumn());
  4540. if (cur.getActivityId())
  4541. exceptionMsg.append(" ActivityId: ").append(cur.getActivityId());
  4542. if (cur.getPriority())
  4543. exceptionMsg.append(" Priority: ").append(cur.getPriority());
  4544. exceptionMsg.append(" Scope: ").append(cur.queryScope());
  4545. const char * label = "";
  4546. switch (cur.getSeverity())
  4547. {
  4548. default:
  4549. case SeverityError: label = "Error"; numErr++; break;
  4550. case SeverityWarning: label = "Warning"; numWRN++; break;
  4551. case SeverityInformation: label = "Info"; numInf++; break;
  4552. case SeverityAlert: label = "Alert"; numAlert++; break;
  4553. }
  4554. exceptionMsg.append(" Severity: ").append(label);
  4555. }
  4556. exceptionMsg.append(" Total error: ").append(numErr);
  4557. exceptionMsg.append(" warning: ").append(numWRN);
  4558. exceptionMsg.append(" info: ").append(numInf);
  4559. exceptionMsg.append(" alert: ").append(numAlert);
  4560. exceptionMsg.append("\n");
  4561. return exceptionMsg.str();
  4562. }
  4563. const char *CWsWorkunitsEx::gatherECLException(IArrayOf<IConstECLException> &exceptions, StringBuffer &exceptionMsg)
  4564. {
  4565. unsigned errorCount = 0, warningCount = 0;
  4566. ForEachItemIn(i, exceptions)
  4567. {
  4568. IConstECLException &e = exceptions.item(i);
  4569. if (strieq(e.getSeverity(), "warning"))
  4570. {
  4571. warningCount++;
  4572. exceptionMsg.append(" Warning: ");
  4573. }
  4574. else if (strieq(e.getSeverity(), "error"))
  4575. {
  4576. errorCount++;
  4577. exceptionMsg.append(" Error: ");
  4578. }
  4579. if (e.getSource())
  4580. exceptionMsg.append(e.getSource()).append(": ");
  4581. if (e.getFileName())
  4582. exceptionMsg.append(e.getFileName());
  4583. if (!e.getLineNo_isNull() && !e.getColumn_isNull())
  4584. exceptionMsg.appendf("(%d,%d): ", e.getLineNo(), e.getColumn());
  4585. exceptionMsg.appendf("%s C%d: %s;", e.getSeverity(), e.getCode(), e.getMessage());
  4586. }
  4587. exceptionMsg.append(" Total error: ").append(errorCount);
  4588. exceptionMsg.append(" warning: ").append(warningCount);
  4589. exceptionMsg.append("\n");
  4590. return exceptionMsg.str();
  4591. }
  4592. bool CWsWorkunitsEx::readDeployWUResponse(CWUDeployWorkunitResponse* deployResponse, StringBuffer &wuid, StringBuffer &result)
  4593. {
  4594. const IMultiException &me = deployResponse->getExceptions();
  4595. if (me.ordinality())
  4596. gatherExceptionMessage(me, result);
  4597. const char *w = deployResponse->getWorkunit().getWuid();
  4598. if (isEmptyString(w))
  4599. {
  4600. result.appendf("Error: no workunit ID!");
  4601. return false;
  4602. }
  4603. wuid.set(w);
  4604. const char *state = deployResponse->getWorkunit().getState();
  4605. bool isCompiled = (strieq(state, "compiled") || strieq(state, "completed"));
  4606. if (!isCompiled)
  4607. result.appendf("state: %s;", state);
  4608. gatherECLException(deployResponse->getWorkunit().getExceptions(), result);
  4609. return isCompiled;
  4610. }
  4611. void CWsWorkunitsEx::addEclDefinitionActionResult(const char *eclDefinition, const char *result, const char *wuid,
  4612. const char *queryID, const char* strAction, bool logResult, IArrayOf<IConstWUEclDefinitionActionResult> &results)
  4613. {
  4614. Owned<IEspWUEclDefinitionActionResult> res = createWUEclDefinitionActionResult();
  4615. if (!isEmptyString(eclDefinition))
  4616. res->setEclDefinition(eclDefinition);
  4617. res->setAction(strAction);
  4618. res->setResult(result);
  4619. if (!isEmptyString(wuid))
  4620. res->setWUID(wuid);
  4621. if (!isEmptyString(queryID))
  4622. res->setQueryID(queryID);
  4623. results.append(*res.getClear());
  4624. if (logResult)
  4625. PROGLOG("%s", result);
  4626. }
  4627. void CWsWorkunitsEx::checkEclDefinitionSyntax(IEspContext &context, const char *target, const char *eclDefinition,
  4628. int msToWait, IArrayOf<IConstWUEclDefinitionActionResult> &results)
  4629. {
  4630. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  4631. NewWsWorkunit wu(factory, context);
  4632. wu->setAction(WUActionCheck);
  4633. wu.setQueryMain(eclDefinition);
  4634. StringAttr wuid(wu->queryWuid()); // NB queryWuid() not valid after workunit.clear()
  4635. wu->commit();
  4636. wu.clear();
  4637. WsWuHelpers::submitWsWorkunit(context, wuid.str(), target, nullptr, 0, true, false, false);
  4638. waitForWorkUnitToComplete(wuid.str(), msToWait);
  4639. Owned<IConstWorkUnit> cw(factory->openWorkUnit(wuid.str()));
  4640. WUState st = cw->getState();
  4641. bool wuTimeout = (st != WUStateAborted) && (st != WUStateCompleted) && (st != WUStateFailed);
  4642. VStringBuffer result(" WUSyntaxCheckECL for %s:", eclDefinition);
  4643. if (wuTimeout)
  4644. result.append(" timed out.");
  4645. gatherWUException(cw->getExceptions(), result);
  4646. addEclDefinitionActionResult(eclDefinition, result.str(), wuid.str(), nullptr, "SyntaxCheck", true, results);
  4647. cw.clear();
  4648. if (wuTimeout)
  4649. abortWorkUnit(wuid.str(), context.querySecManager(), context.queryUser());
  4650. if (!factory->deleteWorkUnit(wuid.str()))
  4651. {
  4652. result.setf(" Workunit %s cannot be deleted now. You may delete it when its status changes.", wuid.str());
  4653. addEclDefinitionActionResult(eclDefinition, result.str(), wuid.str(), nullptr, "SyntaxCheck", true, results);
  4654. }
  4655. }
  4656. bool CWsWorkunitsEx::deployEclDefinition(IEspContext &context, const char *target, const char *eclDefinition,
  4657. int msToWait, StringBuffer &wuid, StringBuffer &result)
  4658. {
  4659. Owned<CWUDeployWorkunitRequest> deployReq = new CWUDeployWorkunitRequest("WsWorkunits");
  4660. deployReq->setName(eclDefinition);
  4661. deployReq->setQueryMainDefinition(eclDefinition);
  4662. deployReq->setObjType("compressed_ecl_text");
  4663. deployReq->setCluster(target);
  4664. deployReq->setWait(msToWait);
  4665. deployReq->setFileName("");
  4666. Owned<CWUDeployWorkunitResponse> deployResponse = new CWUDeployWorkunitResponse("WsWorkunits");
  4667. onWUDeployWorkunit(context, *deployReq, *deployResponse);
  4668. return readDeployWUResponse(deployResponse, wuid, result);
  4669. }
  4670. void CWsWorkunitsEx::deployEclDefinition(IEspContext &context, const char *target, const char *eclDefinition,
  4671. int msToWait, IArrayOf<IConstWUEclDefinitionActionResult> &results)
  4672. {
  4673. StringBuffer wuid, finalResult;
  4674. deployEclDefinition(context, target, eclDefinition, msToWait, wuid, finalResult);
  4675. addEclDefinitionActionResult(eclDefinition, finalResult.str(), wuid.str(), nullptr, "Deploy", true, results);
  4676. }
  4677. void CWsWorkunitsEx::publishEclDefinition(IEspContext &context, const char *target, const char *eclDefinition,
  4678. int msToWait, IEspWUEclDefinitionActionRequest &req, IArrayOf<IConstWUEclDefinitionActionResult> &results)
  4679. {
  4680. StringBuffer priorityReq(req.getPriority());
  4681. if (priorityReq.trim().length() && !isValidPriorityValue(priorityReq.str()))
  4682. {
  4683. VStringBuffer msg("Invalid Priority: %s", priorityReq.str());
  4684. addEclDefinitionActionResult(eclDefinition, msg.str(), nullptr, nullptr, "Publish", true, results);
  4685. return;
  4686. }
  4687. StringBuffer memoryLimitReq(req.getMemoryLimit());
  4688. if (memoryLimitReq.trim().length() && !isValidMemoryValue(memoryLimitReq.str()))
  4689. {
  4690. VStringBuffer msg("Invalid MemoryLimit: %s", memoryLimitReq.str());
  4691. addEclDefinitionActionResult(eclDefinition, msg.str(), nullptr, nullptr, "Publish", true, results);
  4692. return;
  4693. }
  4694. time_t timenow;
  4695. int startTime = time(&timenow);
  4696. //Do deploy first
  4697. StringBuffer wuid, finalResult;
  4698. if (!deployEclDefinition(context, target, eclDefinition, msToWait, wuid, finalResult))
  4699. {
  4700. addEclDefinitionActionResult(eclDefinition, finalResult.str(), wuid.str(), nullptr, "Publish", true, results);
  4701. return;
  4702. }
  4703. int timeLeft = msToWait - (time(&timenow) - startTime);
  4704. if (timeLeft <= 0)
  4705. {
  4706. addEclDefinitionActionResult(eclDefinition, "Timed out after deployment", wuid.str(), nullptr, "Publish", true, results);
  4707. return;
  4708. }
  4709. //Do publish now
  4710. StringBuffer comment(req.getComment());
  4711. StringBuffer remoteDali(req.getRemoteDali());
  4712. StringBuffer sourceProcess(req.getSourceProcess());
  4713. int timeLimit = req.getTimeLimit();
  4714. int warnTimeLimit = req.getWarnTimeLimit();
  4715. Owned<CWUPublishWorkunitRequest> publishReq = new CWUPublishWorkunitRequest("WsWorkunits");
  4716. publishReq->setWuid(wuid.str());
  4717. publishReq->setCluster(target);
  4718. publishReq->setJobName(eclDefinition);
  4719. if (!remoteDali.trim().isEmpty())
  4720. publishReq->setRemoteDali(remoteDali.str());
  4721. if (!sourceProcess.trim().isEmpty())
  4722. publishReq->setSourceProcess(sourceProcess.str());
  4723. if (!priorityReq.isEmpty())
  4724. publishReq->setPriority(priorityReq.str());
  4725. if (comment.str()) //allow empty
  4726. publishReq->setComment(comment.str());
  4727. if (req.getDeletePrevious())
  4728. publishReq->setActivate(CWUQueryActivationMode_ActivateDeletePrevious);
  4729. else if (req.getSuspendPrevious())
  4730. publishReq->setActivate(CWUQueryActivationMode_ActivateSuspendPrevious);
  4731. else
  4732. publishReq->setActivate(req.getNoActivate() ? CWUQueryActivationMode_NoActivate : CWUQueryActivationMode_Activate);
  4733. publishReq->setWait(timeLeft);
  4734. publishReq->setNoReload(req.getNoReload());
  4735. publishReq->setDontCopyFiles(req.getDontCopyFiles());
  4736. publishReq->setAllowForeignFiles(req.getAllowForeign());
  4737. publishReq->setUpdateDfs(req.getUpdateDfs());
  4738. publishReq->setUpdateSuperFiles(req.getUpdateSuperfiles());
  4739. publishReq->setUpdateCloneFrom(req.getUpdateCloneFrom());
  4740. publishReq->setAppendCluster(!req.getDontAppendCluster());
  4741. publishReq->setIncludeFileErrors(true);
  4742. if (timeLimit != -1)
  4743. publishReq->setTimeLimit(timeLimit);
  4744. if (warnTimeLimit != (unsigned) -1)
  4745. publishReq->setWarnTimeLimit(warnTimeLimit);
  4746. if (!memoryLimitReq.isEmpty())
  4747. publishReq->setMemoryLimit(memoryLimitReq.str());
  4748. Owned<CWUPublishWorkunitResponse> publishResponse = new CWUPublishWorkunitResponse("WsWorkunits");
  4749. onWUPublishWorkunit(context, *publishReq, *publishResponse);
  4750. const char *id = publishResponse->getQueryId();
  4751. if (!isEmptyString(id))
  4752. {
  4753. const char *qs = publishResponse->getQuerySet();
  4754. finalResult.append(" ").append(qs ? qs : "").append('/').append(id).append(" published. ");
  4755. }
  4756. if (publishResponse->getReloadFailed())
  4757. finalResult.append(" Added to target, but request to reload queries on cluster failed.");
  4758. const IMultiException &me = publishResponse->getExceptions();
  4759. if (me.ordinality())
  4760. gatherExceptionMessage(me, finalResult);
  4761. gatherQueryFileCopyErrors(publishResponse->getFileErrors(), finalResult);
  4762. addEclDefinitionActionResult(eclDefinition, finalResult.str(), wuid.str(), id, "Publish", true, results);
  4763. }
  4764. bool CWsWorkunitsEx::onWUEclDefinitionAction(IEspContext &context, IEspWUEclDefinitionActionRequest &req, IEspWUEclDefinitionActionResponse &resp)
  4765. {
  4766. try
  4767. {
  4768. CEclDefinitionActions action = req.getActionType();
  4769. if (action == EclDefinitionActions_Undefined)
  4770. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Action not defined in onWUEclDefinitionAction.");
  4771. ensureWsCreateWorkunitAccess(context);
  4772. StringBuffer target(req.getTarget());
  4773. if (target.trim().isEmpty())
  4774. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Target not defined in onWUEclDefinitionAction.");
  4775. IArrayOf<IConstWUEclDefinitionActionResult> results;
  4776. StringArray &eclDefinitions = req.getEclDefinitions();
  4777. int msToWait = req.getMsToWait();
  4778. for (aindex_t i = 0; i < eclDefinitions.length(); i++)
  4779. {
  4780. StringBuffer eclDefinitionName(eclDefinitions.item(i));
  4781. if (eclDefinitionName.trim().isEmpty())
  4782. UWARNLOG("Empty ECL Definition name in WUEclDefinitionAction request");
  4783. else if (action == CEclDefinitionActions_SyntaxCheck)
  4784. checkEclDefinitionSyntax(context, target.str(), eclDefinitionName.str(), msToWait, results);
  4785. else if (action == CEclDefinitionActions_Deploy)
  4786. deployEclDefinition(context, target.str(), eclDefinitionName.str(), msToWait, results);
  4787. else
  4788. publishEclDefinition(context, target.str(), eclDefinitionName.str(), msToWait, req, results);
  4789. }
  4790. resp.setActionResults(results);
  4791. }
  4792. catch(IException* e)
  4793. {
  4794. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4795. }
  4796. return true;
  4797. }