ws_workunitsService.cpp 200 KB

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