ws_workunitsService.cpp 199 KB

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