ws_workunitsService.cpp 196 KB

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