ws_workunitsService.cpp 198 KB

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