workflow.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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 "jlib.hpp"
  14. #include "workunit.hpp"
  15. #include "jptree.hpp"
  16. #include "jlog.hpp"
  17. #include "jregexp.hpp"
  18. #include "workflow.hpp"
  19. //------------------------------------------------------------------------------------------
  20. // Workflow
  21. mapEnums wftypes[] =
  22. {
  23. { WFTypeNormal, "normal" },
  24. { WFTypeSuccess, "success" },
  25. { WFTypeFailure, "failure" },
  26. { WFTypeRecovery, "recovery" },
  27. { WFTypeWait, "wait" },
  28. { WFTypeSize, NULL }
  29. };
  30. mapEnums wfmodes[] =
  31. {
  32. { WFModeNormal, "normal" },
  33. { WFModeCondition, "condition" },
  34. { WFModeSequential, "sequential" },
  35. { WFModeParallel, "parallel" },
  36. { WFModePersist, "persist" },
  37. { WFModeBeginWait, "bwait" },
  38. { WFModeWait, "wait" },
  39. { WFModeOnce, "once" },
  40. { WFModeSize, NULL}
  41. };
  42. mapEnums wfstates[] =
  43. {
  44. { WFStateNull, "null" },
  45. { WFStateReqd, "reqd" },
  46. { WFStateDone, "done" },
  47. { WFStateFail, "fail" },
  48. { WFStateSkip, "skip" },
  49. { WFStateWait, "wait" },
  50. { WFStateBlocked, "block" },
  51. { WFStateSize, NULL }
  52. };
  53. static void setEnum(IPropertyTree *p, const char *propname, int value, mapEnums *map)
  54. {
  55. const char *defval = map->str;
  56. while (map->str)
  57. {
  58. if (value==map->val)
  59. {
  60. p->setProp(propname, map->str);
  61. return;
  62. }
  63. map++;
  64. }
  65. assertex(!"Unexpected value in setEnum");
  66. p->setProp(propname, defval);
  67. }
  68. static int getEnum(IPropertyTree *p, const char *propname, mapEnums *map)
  69. {
  70. const char *v = p->queryProp(propname);
  71. if (v)
  72. {
  73. while (map->str)
  74. {
  75. if (stricmp(v, map->str)==0)
  76. return map->val;
  77. map++;
  78. }
  79. assertex(!"Unexpected value in getEnum");
  80. }
  81. return 0;
  82. }
  83. class CWorkflowDependencyIterator : public CInterface, implements IWorkflowDependencyIterator
  84. {
  85. public:
  86. CWorkflowDependencyIterator(IPropertyTree * tree) { iter.setown(tree->getElements("Dependency")); }
  87. IMPLEMENT_IINTERFACE;
  88. bool first() { return iter->first(); }
  89. bool isValid() { return iter->isValid(); }
  90. bool next() { return iter->next(); }
  91. unsigned query() const { return iter->query().getPropInt("@wfid"); }
  92. private:
  93. Owned<IPropertyTreeIterator> iter;
  94. };
  95. class CWorkflowEvent : public CInterface, implements IWorkflowEvent
  96. {
  97. public:
  98. CWorkflowEvent(char const * _name, char const * _text) : name(_name), text(_text) {}
  99. IMPLEMENT_IINTERFACE;
  100. virtual char const * queryName() const { return name.get(); }
  101. virtual char const * queryText() const { return text.get(); }
  102. virtual bool matches(char const * trialName, char const * trialText) const { return((strcmp(trialName, name.get()) == 0) && WildMatch(trialText, text.get(), true)); }
  103. private:
  104. StringAttr name;
  105. StringAttr text;
  106. };
  107. class CWorkflowItem : public CInterface, implements IWorkflowItem
  108. {
  109. public:
  110. CWorkflowItem(IPropertyTree & _tree) { tree.setown(&_tree); }
  111. CWorkflowItem(IPropertyTree * ptree, unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  112. {
  113. tree.setown(LINK(ptree->addPropTree("Item", createPTree())));
  114. tree->setPropInt("@wfid", wfid);
  115. setEnum(tree, "@type", type, wftypes);
  116. setEnum(tree, "@mode", mode, wfmodes);
  117. if(success) tree->setPropInt("@success", success);
  118. if(failure) tree->setPropInt("@failure", failure);
  119. if(recovery && retriesAllowed)
  120. {
  121. tree->setPropInt("@recovery", recovery);
  122. tree->setPropInt("@retriesAllowed", retriesAllowed);
  123. tree->addPropTree("Dependency", createPTree())->setPropInt("@wfid", recovery);
  124. }
  125. if(contingencyFor) tree->setPropInt("@contingencyFor", contingencyFor);
  126. reset();
  127. }
  128. IMPLEMENT_IINTERFACE;
  129. //info set at compile time
  130. virtual unsigned queryWfid() const { return tree->getPropInt("@wfid"); }
  131. virtual bool isScheduled() const { return tree->hasProp("Schedule"); }
  132. virtual bool isScheduledNow() const { return (tree->hasProp("Schedule") && !tree->hasProp("Schedule/Event")); }
  133. virtual IWorkflowEvent * getScheduleEvent() const { if(tree->hasProp("Schedule/Event")) return new CWorkflowEvent(tree->queryProp("Schedule/Event/@name"), tree->queryProp("Schedule/Event/@text")); else return NULL; }
  134. virtual unsigned querySchedulePriority() const { return (tree->hasProp("Schedule") ? tree->getPropInt("Schedule/@priority", 0) : 0); }
  135. virtual bool hasScheduleCount() const { return tree->hasProp("Schedule/@count"); }
  136. virtual unsigned queryScheduleCount() const { assertex(tree->hasProp("Schedule/@count")); return tree->getPropInt("Schedule/@count"); }
  137. virtual IWorkflowDependencyIterator * getDependencies() const { return new CWorkflowDependencyIterator(tree); }
  138. virtual WFType queryType() const { return static_cast<WFType>(getEnum(tree, "@type", wftypes)); }
  139. virtual WFMode queryMode() const { return static_cast<WFMode>(getEnum(tree, "@mode", wfmodes)); }
  140. virtual unsigned querySuccess() const { return tree->getPropInt("@success", 0); }
  141. virtual unsigned queryFailure() const { return tree->getPropInt("@failure", 0); }
  142. virtual unsigned queryRecovery() const { return tree->getPropInt("@recovery", 0); }
  143. virtual unsigned queryRetriesAllowed() const { return tree->getPropInt("@retriesAllowed", 0); }
  144. virtual unsigned queryContingencyFor() const { return tree->getPropInt("@contingencyFor", 0); }
  145. virtual IStringVal & getPersistName(IStringVal & val) const { val.set(tree->queryProp("@persistName")); return val; }
  146. virtual unsigned queryPersistWfid() const { return tree->getPropInt("@persistWfid", 0); }
  147. virtual int queryPersistCopies() const { return tree->getPropInt("@persistCopies", 0); }
  148. virtual IStringVal & queryCluster(IStringVal & val) const { val.set(tree->queryProp("@cluster")); return val; }
  149. virtual void setScheduledNow() { tree->setPropTree("Schedule", createPTree()); setEnum(tree, "@state", WFStateReqd, wfstates); }
  150. virtual void setScheduledOn(char const * name, char const * text) { IPropertyTree * stree = createPTree(); stree->setProp("@name", name); stree->setProp("@text", text); tree->setPropTree("Schedule", createPTree())->setPropTree("Event", stree); setEnum(tree, "@state", WFStateWait, wfstates); }
  151. virtual void setSchedulePriority(unsigned priority) { assertex(tree->hasProp("Schedule")); tree->setPropInt("Schedule/@priority", priority); }
  152. virtual void setScheduleCount(unsigned count) { assertex(tree->hasProp("Schedule")); tree->setPropInt("Schedule/@count", count); tree->setPropInt("Schedule/@countRemaining", count); }
  153. virtual void addDependency(unsigned wfid) { tree->addPropTree("Dependency", createPTree())->setPropInt("@wfid", wfid); }
  154. virtual void setPersistInfo(char const * name, unsigned wfid, int numPersistInstances)
  155. {
  156. tree->setProp("@persistName", name);
  157. tree->setPropInt("@persistWfid", wfid);
  158. if (numPersistInstances != 0)
  159. tree->setPropInt("@persistCopies", (int)numPersistInstances);
  160. }
  161. virtual void setCluster(const char * cluster) { tree->setProp("@cluster", cluster); }
  162. //info set at run time
  163. virtual unsigned queryScheduleCountRemaining() const { assertex(tree->hasProp("Schedule")); return tree->getPropInt("Schedule/@countRemaining"); }
  164. virtual WFState queryState() const { return static_cast<WFState>(getEnum(tree, "@state", wfstates)); }
  165. virtual unsigned queryRetriesRemaining() const { return tree->getPropInt("@retriesRemaining"); }
  166. virtual int queryFailCode() const { return tree->getPropInt("@failcode"); }
  167. virtual char const * queryFailMessage() const { return tree->queryProp("@failmsg"); }
  168. virtual char const * queryEventName() const { return tree->queryProp("@eventname"); }
  169. virtual char const * queryEventExtra() const { return tree->queryProp("@eventextra"); }
  170. virtual void setState(WFState state) { setEnum(tree, "@state", state, wfstates); }
  171. virtual unsigned queryScheduledWfid() const { return tree->getPropInt("@swfid", 0); }
  172. virtual void setScheduledWfid(unsigned wfid) { tree->setPropInt("@swfid", wfid); }
  173. virtual bool testAndDecRetries()
  174. {
  175. assertex(tree->hasProp("@retriesAllowed"));
  176. unsigned rem = tree->getPropInt("@retriesRemaining", 0);
  177. if(rem==0)
  178. return false;
  179. tree->setPropInt("@retriesRemaining", rem-1);
  180. return true;
  181. }
  182. virtual bool decAndTestScheduleCountRemaining()
  183. {
  184. if(!tree->hasProp("Schedule/@count"))
  185. return true;
  186. unsigned rem = tree->getPropInt("Schedule/@countRemaining");
  187. assertex(rem>0);
  188. tree->setPropInt("Schedule/@countRemaining", rem-1);
  189. return (rem>1);
  190. }
  191. virtual void incScheduleCount()
  192. {
  193. unsigned rem = tree->getPropInt("Schedule/@countRemaining");
  194. tree->setPropInt("Schedule/@countRemaining", rem+1);
  195. }
  196. virtual void setFailInfo(int code, char const * message)
  197. {
  198. tree->setPropInt("@failcode", code);
  199. tree->setProp("@failmsg", message);
  200. }
  201. virtual void setEvent(const char * name, const char * extra)
  202. {
  203. if (name)
  204. tree->setProp("@eventname", name);
  205. if (extra)
  206. tree->setProp("@eventextra", extra);
  207. }
  208. virtual void reset()
  209. {
  210. if(tree->hasProp("@retriesAllowed"))
  211. tree->setPropInt("@retriesRemaining", tree->getPropInt("@retriesAllowed"));
  212. if(tree->hasProp("Schedule/@count"))
  213. tree->setPropInt("Schedule/@countRemaining", tree->getPropInt("Schedule/@count"));
  214. tree->removeProp("@failcode");
  215. tree->removeProp("@failmsg");
  216. tree->removeProp("@eventname");
  217. tree->removeProp("@eventtext");
  218. if(isScheduled())
  219. {
  220. if(isScheduledNow())
  221. setState(WFStateReqd);
  222. else if (hasScheduleCount() && (queryScheduleCountRemaining() == 0))
  223. setState(WFStateDone);
  224. else
  225. setState(WFStateWait);
  226. }
  227. else if(queryType() == WFTypeRecovery)
  228. setState(WFStateSkip);
  229. else
  230. setState(WFStateNull);
  231. }
  232. virtual void syncRuntimeData(IConstWorkflowItem const & other)
  233. {
  234. WFState state = other.queryState();
  235. setState(state);
  236. if(tree->hasProp("@retriesAllowed"))
  237. tree->setPropInt("@retriesRemaining", other.queryRetriesRemaining());
  238. if(tree->hasProp("Schedule/@count"))
  239. tree->setPropInt("Schedule/@countRemaining", other.queryScheduleCountRemaining());
  240. if(state == WFStateFail)
  241. {
  242. tree->setPropInt("@failcode", other.queryFailCode());
  243. tree->setProp("@failmsg", other.queryFailMessage());
  244. }
  245. setEvent(other.queryEventName(), other.queryEventExtra());
  246. }
  247. private:
  248. Owned<IPropertyTree> tree;
  249. };
  250. class CCloneWorkflowItem : public CInterface, implements IRuntimeWorkflowItem
  251. {
  252. private:
  253. class CCloneSchedule : public CInterface
  254. {
  255. private:
  256. bool now;
  257. unsigned priority;
  258. bool counting;
  259. unsigned count;
  260. unsigned countRemaining;
  261. Owned<IWorkflowEvent> event;
  262. public:
  263. CCloneSchedule(IConstWorkflowItem const * other)
  264. {
  265. now = other->isScheduledNow();
  266. priority = other->querySchedulePriority();
  267. counting = other->hasScheduleCount();
  268. if(counting)
  269. {
  270. count = other->queryScheduleCount();
  271. countRemaining = other->queryScheduleCountRemaining();
  272. }
  273. else
  274. {
  275. count = 0;
  276. countRemaining = 0;
  277. }
  278. event.setown(other->getScheduleEvent());
  279. }
  280. bool isNow() const { return now; }
  281. unsigned queryPriority() const { return priority; }
  282. bool hasCount() const { return counting; }
  283. unsigned queryCount() const { return count; }
  284. unsigned queryCountRemaining() const { return countRemaining; }
  285. bool decAndTestCountRemaining()
  286. {
  287. if(!counting)
  288. return true;
  289. if(countRemaining)
  290. countRemaining--;
  291. return (countRemaining>0);
  292. }
  293. void incCountRemaining()
  294. {
  295. if(counting)
  296. countRemaining++;
  297. }
  298. void resetCount() { if(counting) countRemaining = count; }
  299. IWorkflowEvent * getEvent() const { return event.getLink(); }
  300. };
  301. class CCloneIterator : public CInterface, public IWorkflowDependencyIterator
  302. {
  303. public:
  304. CCloneIterator(IntArray const & _array) : array(_array), idx(0) {}
  305. IMPLEMENT_IINTERFACE;
  306. virtual bool first() { idx = 0; return isValid(); }
  307. virtual bool isValid() { return array.isItem(idx); }
  308. virtual bool next() { idx++; return isValid(); }
  309. virtual unsigned query() const { return array.item(idx); }
  310. private:
  311. IntArray const & array;
  312. aindex_t idx;
  313. };
  314. unsigned wfid;
  315. Owned<CCloneSchedule> schedule;
  316. IntArray dependencies;
  317. WFType type;
  318. WFMode mode;
  319. unsigned success;
  320. unsigned failure;
  321. unsigned recovery;
  322. unsigned retriesAllowed;
  323. unsigned contingencyFor;
  324. unsigned scheduledWfid;
  325. WFState state;
  326. unsigned retriesRemaining;
  327. int failcode;
  328. StringAttr failmsg;
  329. SCMStringBuffer persistName;
  330. SCMStringBuffer clusterName;
  331. unsigned persistWfid;
  332. int persistCopies;
  333. StringAttr eventName;
  334. StringAttr eventExtra;
  335. public:
  336. CCloneWorkflowItem() {}
  337. IMPLEMENT_IINTERFACE;
  338. void copy(IConstWorkflowItem const * other)
  339. {
  340. wfid = other->queryWfid();
  341. if(other->isScheduled())
  342. schedule.setown(new CCloneSchedule(other));
  343. Owned<IWorkflowDependencyIterator> iter = other->getDependencies();
  344. for(iter->first(); iter->isValid(); iter->next())
  345. dependencies.append(iter->query());
  346. type = other->queryType();
  347. mode = other->queryMode();
  348. success = other->querySuccess();
  349. failure = other->queryFailure();
  350. recovery = other->queryRecovery();
  351. retriesAllowed = other->queryRetriesAllowed();
  352. contingencyFor = other->queryContingencyFor();
  353. state = other->queryState();
  354. retriesRemaining = other->queryRetriesRemaining();
  355. if(state == WFStateFail)
  356. {
  357. failcode = other->queryFailCode();
  358. failmsg.set(other->queryFailMessage());
  359. }
  360. eventName.set(other->queryEventName());
  361. eventExtra.set(other->queryEventExtra());
  362. other->getPersistName(persistName);
  363. persistWfid = other->queryPersistWfid();
  364. scheduledWfid = other->queryScheduledWfid();
  365. persistCopies = other->queryPersistCopies();
  366. other->queryCluster(clusterName);
  367. }
  368. //info set at compile time
  369. virtual unsigned queryWfid() const { return wfid; }
  370. virtual bool isScheduled() const { return schedule.get() != 0; }
  371. virtual bool isScheduledNow() const { return schedule && schedule->isNow(); }
  372. virtual IWorkflowEvent * getScheduleEvent() const { if(schedule) return schedule->getEvent(); else return NULL; }
  373. virtual unsigned querySchedulePriority() const { return schedule ? schedule->queryPriority() : 0; }
  374. virtual bool hasScheduleCount() const { return schedule ? schedule->hasCount() : false; }
  375. virtual unsigned queryScheduleCount() const { return schedule ? schedule->queryCount() : 0; }
  376. virtual IWorkflowDependencyIterator * getDependencies() const { return new CCloneIterator(dependencies); }
  377. virtual WFType queryType() const { return type; }
  378. virtual WFMode queryMode() const { return mode; }
  379. virtual unsigned querySuccess() const { return success; }
  380. virtual unsigned queryFailure() const { return failure; }
  381. virtual unsigned queryRecovery() const { return recovery; }
  382. virtual unsigned queryRetriesAllowed() const { return retriesAllowed; }
  383. virtual unsigned queryContingencyFor() const { return contingencyFor; }
  384. virtual IStringVal & getPersistName(IStringVal & val) const { val.set(persistName.str()); return val; }
  385. virtual unsigned queryPersistWfid() const { return persistWfid; }
  386. virtual int queryPersistCopies() const { return persistCopies; }
  387. virtual IStringVal & queryCluster(IStringVal & val) const { val.set(clusterName.str()); return val; }
  388. //info set at run time
  389. virtual unsigned queryScheduleCountRemaining() const { return schedule ? schedule->queryCountRemaining() : 0; }
  390. virtual WFState queryState() const { return state; }
  391. virtual unsigned queryRetriesRemaining() const { return retriesRemaining; }
  392. virtual int queryFailCode() const { return failcode; }
  393. virtual char const * queryFailMessage() const { return failmsg.get(); }
  394. virtual char const * queryEventName() const { return eventName; }
  395. virtual char const * queryEventExtra() const { return eventExtra; }
  396. virtual unsigned queryScheduledWfid() const { return scheduledWfid; }
  397. virtual void setState(WFState _state) { state = _state; }
  398. virtual bool testAndDecRetries()
  399. {
  400. if(retriesRemaining == 0)
  401. return false;
  402. retriesRemaining--;
  403. return true;
  404. }
  405. virtual bool decAndTestScheduleCountRemaining()
  406. {
  407. if(!schedule)
  408. return true;
  409. return schedule->decAndTestCountRemaining();
  410. }
  411. virtual void incScheduleCount()
  412. {
  413. if(schedule)
  414. schedule->incCountRemaining();
  415. }
  416. virtual void setFailInfo(int code, char const * message)
  417. {
  418. failcode = code;
  419. failmsg.set(message);
  420. }
  421. virtual void setEvent(const char * name, const char * extra)
  422. {
  423. eventName.set(name);
  424. eventExtra.set(extra);
  425. }
  426. virtual void reset()
  427. {
  428. retriesRemaining = retriesAllowed;
  429. if(schedule) schedule->resetCount();
  430. if(isScheduled())
  431. {
  432. if(isScheduledNow())
  433. setState(WFStateReqd);
  434. else if (hasScheduleCount() && (queryScheduleCountRemaining() == 0))
  435. setState(WFStateDone);
  436. else
  437. setState(WFStateWait);
  438. }
  439. else if(queryType() == WFTypeRecovery)
  440. setState(WFStateSkip);
  441. else
  442. setState(WFStateNull);
  443. }
  444. };
  445. class CWorkflowItemIterator : public CInterface, implements IWorkflowItemIterator
  446. {
  447. public:
  448. CWorkflowItemIterator(IPropertyTree * tree) { iter.setown(tree->getElements("Item")); }
  449. IMPLEMENT_IINTERFACE;
  450. bool first() { item.clear(); return iter->first(); }
  451. bool isValid() { return iter->isValid(); }
  452. bool next() { item.clear(); return iter->next(); }
  453. IConstWorkflowItem * query() const { if(!item) item.setown(new CWorkflowItem(iter->get())); return item.get(); }
  454. IWorkflowItem * get() const { if(!item) item.setown(new CWorkflowItem(iter->get())); return item.getLink(); }
  455. private:
  456. Owned<IPropertyTreeIterator> iter;
  457. mutable Owned<CWorkflowItem> item;
  458. };
  459. class CCloneWorkflowItemArray : public CInterface, implements IWorkflowItemArray
  460. {
  461. private:
  462. class ListItem
  463. {
  464. public:
  465. ListItem(ListItem * _next, IRuntimeWorkflowItem * _item) : next(_next), item(_item) {}
  466. ListItem * next;
  467. IRuntimeWorkflowItem * item;
  468. };
  469. class ListItemPtr : public CInterface, implements IRuntimeWorkflowItemIterator
  470. {
  471. public:
  472. ListItemPtr(ListItem * _start) : start(_start) { ptr = NULL; }
  473. IMPLEMENT_IINTERFACE;
  474. virtual bool first() { ptr = start; return isValid(); }
  475. virtual bool isValid() { return ptr != NULL; }
  476. virtual bool next() { ptr = ptr->next; return isValid(); }
  477. virtual IConstWorkflowItem * query() const { return ptr->item; }
  478. virtual IRuntimeWorkflowItem * get() const { return LINK(ptr->item); }
  479. private:
  480. ListItem * start;
  481. ListItem * ptr;
  482. };
  483. void insert(CCloneWorkflowItem * item)
  484. {
  485. if(!item->isScheduled())
  486. return;
  487. if(!head)
  488. head = tail = new ListItem(NULL, item);
  489. else if(item->querySchedulePriority() > head->item->querySchedulePriority())
  490. head = new ListItem(head, item);
  491. else if(item->querySchedulePriority() <= tail->item->querySchedulePriority())
  492. {
  493. tail->next = new ListItem(NULL, item);
  494. tail = tail->next;
  495. }
  496. else
  497. {
  498. ListItem * finger = head;
  499. while(item->querySchedulePriority() <= finger->next->item->querySchedulePriority())
  500. finger = finger->next;
  501. finger->next = new ListItem(finger->next, item);
  502. }
  503. }
  504. public:
  505. CCloneWorkflowItemArray(unsigned _capacity) : capacity(_capacity), head(NULL), tail(NULL)
  506. {
  507. array = _capacity ? new CCloneWorkflowItem[_capacity] : NULL;
  508. }
  509. ~CCloneWorkflowItemArray()
  510. {
  511. ListItem * finger = head;
  512. while(finger)
  513. {
  514. ListItem * del = finger;
  515. finger = finger->next;
  516. delete del;
  517. }
  518. if (array)
  519. delete [] array;
  520. }
  521. IMPLEMENT_IINTERFACE;
  522. virtual void addClone(IConstWorkflowItem const * other)
  523. {
  524. unsigned wfid = other->queryWfid();
  525. assertex((wfid > 0) && (wfid <= capacity));
  526. array[wfid-1].copy(other);
  527. insert(&array[wfid-1]);
  528. }
  529. virtual IRuntimeWorkflowItem & queryWfid(unsigned wfid)
  530. {
  531. assertex((wfid > 0) && (wfid <= capacity));
  532. return array[wfid-1];
  533. }
  534. virtual unsigned count() const
  535. {
  536. return capacity;
  537. }
  538. virtual IRuntimeWorkflowItemIterator * getSequenceIterator() { return new ListItemPtr(head); }
  539. virtual bool hasScheduling() const
  540. {
  541. ListItem * finger = head;
  542. while(finger)
  543. {
  544. if(!finger->item->isScheduledNow())
  545. return true;
  546. finger = finger->next;
  547. }
  548. return false;
  549. }
  550. private:
  551. unsigned capacity;
  552. CCloneWorkflowItem * array;
  553. ListItem * head;
  554. ListItem * tail;
  555. };
  556. //-------------------------------------------------------------------------------------------------
  557. #ifdef TRACE_WORKFLOW
  558. const LogMsgCategory MCworkflow = MCprogress(50); // Category used to inform enqueue/start/finish of workflow item
  559. #endif
  560. WorkflowMachine::WorkflowMachine()
  561. : ctx(NULL), process(NULL), currentWfid(0), currentScheduledWfid(0), itemsWaiting(0), itemsUnblocked(0), condition(false), logctx(queryDummyContextLogger())
  562. {
  563. }
  564. WorkflowMachine::WorkflowMachine(const IContextLogger &_logctx)
  565. : ctx(NULL), process(NULL), currentWfid(0), currentScheduledWfid(0), itemsWaiting(0), itemsUnblocked(0), condition(false), logctx(_logctx)
  566. {
  567. }
  568. void WorkflowMachine::perform(IGlobalCodeContext *_ctx, IEclProcess *_process)
  569. {
  570. ctx = _ctx;
  571. process = _process;
  572. Owned<WorkflowException> error;
  573. begin();
  574. bool scheduling = workflow->hasScheduling();
  575. if(scheduling)
  576. schedulingStart();
  577. bool more = false;
  578. do
  579. {
  580. Owned<IRuntimeWorkflowItem> item;
  581. Owned<IRuntimeWorkflowItemIterator> iter = workflow->getSequenceIterator();
  582. itemsWaiting = 0;
  583. itemsUnblocked = 0;
  584. if (iter->first())
  585. {
  586. while (iter->isValid())
  587. {
  588. try
  589. {
  590. item.setown(iter->get());
  591. switch(item->queryState())
  592. {
  593. case WFStateReqd:
  594. case WFStateFail:
  595. if(!error)
  596. {
  597. unsigned wfid = item->queryWfid();
  598. executeItem(wfid, wfid);
  599. }
  600. break;
  601. }
  602. }
  603. catch(WorkflowException * e)
  604. {
  605. error.setown(e);
  606. }
  607. if(item->queryState() == WFStateWait) itemsWaiting++;
  608. if(error) break; //MORE: will not want to break in situations where there might be pending contingency clauses
  609. if(scheduling && schedulingPull())
  610. {
  611. itemsWaiting = 0;
  612. iter.setown(workflow->getSequenceIterator());
  613. if(!iter->first()) break;
  614. }
  615. else
  616. if(!iter->next()) break;
  617. }
  618. }
  619. if(error) break; //MORE: will not want to break in situations where there might be pending contingency clauses
  620. if(scheduling)
  621. more = schedulingPullStop();
  622. } while(more || itemsUnblocked);
  623. end();
  624. if(error)
  625. throw error.getLink();
  626. }
  627. bool WorkflowMachine::executeItem(unsigned wfid, unsigned scheduledWfid)
  628. {
  629. #ifdef TRACE_WORKFLOW
  630. LOG(MCworkflow, "Beginning workflow item %u", wfid);
  631. #endif
  632. IRuntimeWorkflowItem & item = workflow->queryWfid(wfid);
  633. switch(item.queryState())
  634. {
  635. case WFStateDone:
  636. if (item.queryMode() == WFModePersist)
  637. {
  638. #ifdef TRACE_WORKFLOW
  639. LOG(MCworkflow, "Recheck persist %u", wfid);
  640. #endif
  641. break;
  642. }
  643. #ifdef TRACE_WORKFLOW
  644. LOG(MCworkflow, "Nothing to be done for workflow item %u", wfid);
  645. #endif
  646. return true;
  647. case WFStateSkip:
  648. #ifdef TRACE_WORKFLOW
  649. LOG(MCworkflow, "Nothing to be done for workflow item %u", wfid);
  650. #endif
  651. return true;
  652. case WFStateWait:
  653. throw new WorkflowException(0, "INTERNAL ERROR: attempting to execute workflow item in wait state", wfid, WorkflowException::SYSTEM, MSGAUD_user);
  654. case WFStateBlocked:
  655. throw new WorkflowException(0, "INTERNAL ERROR: attempting to execute workflow item in blocked state", wfid, WorkflowException::SYSTEM, MSGAUD_user);
  656. case WFStateFail:
  657. item.reset();
  658. break;
  659. }
  660. switch(item.queryMode())
  661. {
  662. case WFModeNormal:
  663. case WFModeOnce:
  664. if (!doExecuteItemDependencies(item, wfid))
  665. return false;
  666. doExecuteItem(item, scheduledWfid);
  667. break;
  668. case WFModeCondition:
  669. if (!doExecuteConditionItem(item, scheduledWfid))
  670. return false;
  671. break;
  672. case WFModeSequential:
  673. case WFModeParallel:
  674. if (!doExecuteItemDependencies(item, scheduledWfid))
  675. return false;
  676. break;
  677. case WFModePersist:
  678. doExecutePersistItem(item);
  679. break;
  680. case WFModeBeginWait:
  681. doExecuteBeginWaitItem(item, scheduledWfid);
  682. item.setState(WFStateDone);
  683. return false;
  684. case WFModeWait:
  685. doExecuteEndWaitItem(item);
  686. break;
  687. default:
  688. throwUnexpected();
  689. }
  690. switch(item.queryType())
  691. {
  692. case WFTypeNormal:
  693. if(item.isScheduled() && !item.isScheduledNow() && item.decAndTestScheduleCountRemaining())
  694. item.setState(WFStateWait);
  695. else
  696. item.setState(WFStateDone);
  697. break;
  698. case WFTypeSuccess:
  699. case WFTypeFailure:
  700. item.setState(WFStateNull);
  701. break;
  702. case WFTypeRecovery:
  703. item.setState(WFStateSkip);
  704. break;
  705. }
  706. if(item.querySuccess())
  707. {
  708. try
  709. {
  710. executeItem(item.querySuccess(), scheduledWfid);
  711. }
  712. catch(WorkflowException * ce)
  713. {
  714. if(ce->queryType() == WorkflowException::ABORT)
  715. throw;
  716. reportContingencyFailure("SUCCESS", ce);
  717. ce->Release();
  718. }
  719. }
  720. #ifdef TRACE_WORKFLOW
  721. LOG(MCworkflow, "Done workflow item %u", wfid);
  722. #endif
  723. return true;
  724. }
  725. bool WorkflowMachine::doExecuteItemDependencies(IRuntimeWorkflowItem & item, unsigned scheduledWfid)
  726. {
  727. Owned<IWorkflowDependencyIterator> iter = item.getDependencies();
  728. for(iter->first(); iter->isValid(); iter->next())
  729. {
  730. if (!doExecuteItemDependency(item, iter->query(), scheduledWfid, false))
  731. return false;
  732. }
  733. return true;
  734. }
  735. bool WorkflowMachine::doExecuteItemDependency(IRuntimeWorkflowItem & item, unsigned wfid, unsigned scheduledWfid, bool alwaysEvaluate)
  736. {
  737. try
  738. {
  739. if (alwaysEvaluate)
  740. workflow->queryWfid(wfid).setState(WFStateNull);
  741. return executeItem(wfid, scheduledWfid);
  742. }
  743. catch(WorkflowException * e)
  744. {
  745. if(e->queryType() == WorkflowException::ABORT)
  746. throw;
  747. if(!attemptRetry(item, wfid, scheduledWfid))
  748. {
  749. handleFailure(item, e, true);
  750. throw;
  751. }
  752. e->Release();
  753. }
  754. return true;//more!
  755. }
  756. void WorkflowMachine::doExecuteItem(IRuntimeWorkflowItem & item, unsigned scheduledWfid)
  757. {
  758. try
  759. {
  760. performItem(item.queryWfid(), scheduledWfid);
  761. }
  762. catch(WorkflowException * ein)
  763. {
  764. if(ein->queryType() == WorkflowException::ABORT)
  765. throw;
  766. if(!attemptRetry(item, 0, scheduledWfid))
  767. {
  768. handleFailure(item, ein, true);
  769. throw;
  770. }
  771. ein->Release();
  772. }
  773. catch(IException * ein)
  774. {
  775. checkForAbort(item.queryWfid(), ein);
  776. if(!attemptRetry(item, 0, scheduledWfid))
  777. {
  778. StringBuffer msg;
  779. ein->errorMessage(msg);
  780. WorkflowException::Type type = ((dynamic_cast<IUserException *>(ein) != NULL) ? WorkflowException::USER : WorkflowException::SYSTEM);
  781. WorkflowException * eout = new WorkflowException(ein->errorCode(), msg.str(), item.queryWfid(), type, ein->errorAudience());
  782. ein->Release();
  783. handleFailure(item, eout, false);
  784. throw eout;
  785. }
  786. ein->Release();
  787. }
  788. }
  789. bool WorkflowMachine::doExecuteConditionItem(IRuntimeWorkflowItem & item, unsigned scheduledWfid)
  790. {
  791. Owned<IWorkflowDependencyIterator> iter = item.getDependencies();
  792. if(!iter->first()) throwUnexpected();
  793. unsigned wfidCondition = iter->query();
  794. if(!iter->next()) throwUnexpected();
  795. unsigned wfidTrue = iter->query();
  796. unsigned wfidFalse = 0;
  797. if(iter->next()) wfidFalse = iter->query();
  798. if(iter->next()) throwUnexpected();
  799. if (!doExecuteItemDependency(item, wfidCondition, scheduledWfid, true))
  800. return false;
  801. if(condition)
  802. return doExecuteItemDependency(item, wfidTrue, scheduledWfid, false);
  803. else if (wfidFalse)
  804. return doExecuteItemDependency(item, wfidFalse, scheduledWfid, false);
  805. return true;
  806. }
  807. void WorkflowMachine::doExecuteBeginWaitItem(IRuntimeWorkflowItem & item, unsigned scheduledWfid)
  808. {
  809. #ifdef TRACE_WORKFLOW
  810. LOG(MCworkflow, "Begin wait for workflow item %u sched %u", item.queryWfid(), scheduledWfid);
  811. #endif
  812. //Block execution of the currently executing scheduled item
  813. IRuntimeWorkflowItem & scheduledItem = workflow->queryWfid(scheduledWfid);
  814. assertex(scheduledItem.queryState() == WFStateReqd);
  815. scheduledItem.setState(WFStateBlocked);
  816. //And increment the count on the wait wf item so it becomes active
  817. Owned<IWorkflowDependencyIterator> iter = item.getDependencies();
  818. if(!iter->first()) throwUnexpected();
  819. unsigned waitWfid = iter->query();
  820. if(iter->next()) throwUnexpected();
  821. IRuntimeWorkflowItem & waitItem = workflow->queryWfid(waitWfid);
  822. assertex(waitItem.queryState() == WFStateDone);
  823. waitItem.incScheduleCount();
  824. waitItem.setState(WFStateWait);
  825. itemsWaiting++;
  826. }
  827. void WorkflowMachine::doExecuteEndWaitItem(IRuntimeWorkflowItem & item)
  828. {
  829. //Unblock the scheduled workflow item, which should mean execution continues.
  830. unsigned scheduledWfid = item.queryScheduledWfid();
  831. #ifdef TRACE_WORKFLOW
  832. LOG(MCworkflow, "Finished wait for workflow sched %u", scheduledWfid);
  833. #endif
  834. IRuntimeWorkflowItem & scheduledItem = workflow->queryWfid(scheduledWfid);
  835. assertex(scheduledItem.queryState() == WFStateBlocked);
  836. scheduledItem.setState(WFStateReqd);
  837. itemsUnblocked++;
  838. //Note this would be more efficient implemented more like a state machine
  839. //(with next processing rather than walking from the top down),
  840. //but that will require some more work.
  841. }
  842. bool WorkflowMachine::isOlderThanPersist(time_t when, IRuntimeWorkflowItem & item)
  843. {
  844. time_t thisTime;
  845. if (!getPersistTime(thisTime, item))
  846. return false; // if no time must be older than the persist
  847. return when < thisTime;
  848. }
  849. bool WorkflowMachine::isOlderThanInputPersists(time_t when, IRuntimeWorkflowItem & item)
  850. {
  851. Owned<IWorkflowDependencyIterator> iter = item.getDependencies();
  852. ForEach(*iter)
  853. {
  854. unsigned cur = iter->query();
  855. IRuntimeWorkflowItem & other = workflow->queryWfid(cur);
  856. if (isPersist(other))
  857. {
  858. if (isOlderThanPersist(when, other))
  859. return true;
  860. }
  861. else
  862. {
  863. if (isOlderThanInputPersists(when, other))
  864. return true;
  865. }
  866. }
  867. return false;
  868. }
  869. bool WorkflowMachine::isItemOlderThanInputPersists(IRuntimeWorkflowItem & item)
  870. {
  871. time_t curWhen;
  872. if (!getPersistTime(curWhen, item))
  873. return false; // if no time then old and can't tell
  874. return isOlderThanInputPersists(curWhen, item);
  875. }
  876. void WorkflowMachine::performItem(unsigned wfid, unsigned scheduledWfid)
  877. {
  878. #ifdef TRACE_WORKFLOW
  879. if(currentWfid)
  880. LOG(MCworkflow, "Branching from workflow item %u", currentWfid);
  881. LOG(MCworkflow, "Performing workflow item %u", wfid);
  882. #endif
  883. wfidStack.append(currentWfid);
  884. wfidStack.append(scheduledWfid);
  885. currentWfid = wfid;
  886. currentScheduledWfid = scheduledWfid;
  887. process->perform(ctx, wfid);
  888. scheduledWfid = wfidStack.popGet();
  889. currentWfid = wfidStack.popGet();
  890. if(currentWfid)
  891. {
  892. #ifdef TRACE_WORKFLOW
  893. LOG(MCworkflow, "Returning to workflow item %u", currentWfid);
  894. #endif
  895. }
  896. }
  897. bool WorkflowMachine::attemptRetry(IRuntimeWorkflowItem & item, unsigned dep, unsigned scheduledWfid)
  898. {
  899. unsigned wfid = item.queryWfid();
  900. unsigned recovery = item.queryRecovery();
  901. if(!recovery)
  902. return false;
  903. while(item.testAndDecRetries())
  904. {
  905. bool okay = true;
  906. try
  907. {
  908. workflow->queryWfid(recovery).setState(WFStateNull);
  909. executeItem(recovery, recovery);
  910. if(dep)
  911. executeItem(dep, scheduledWfid);
  912. else
  913. performItem(wfid, scheduledWfid);
  914. }
  915. catch(WorkflowException * ce)
  916. {
  917. okay = false;
  918. if(ce->queryType() == WorkflowException::ABORT)
  919. throw;
  920. reportContingencyFailure("RECOVERY", ce);
  921. ce->Release();
  922. }
  923. catch(IException * ce)
  924. {
  925. okay = false;
  926. checkForAbort(wfid, ce);
  927. reportContingencyFailure("RECOVERY", ce);
  928. ce->Release();
  929. }
  930. if(okay)
  931. return true;
  932. }
  933. return false;
  934. }
  935. void WorkflowMachine::handleFailure(IRuntimeWorkflowItem & item, WorkflowException const * e, bool isDep)
  936. {
  937. StringBuffer msg;
  938. e->errorMessage(msg).append(" (in item ").append(e->queryWfid()).append(")");
  939. if(isDep)
  940. logctx.logOperatorException(NULL, NULL, 0, "Dependency failure for workflow item %u: %d: %s", item.queryWfid(), e->errorCode(), msg.str());
  941. else
  942. logctx.logOperatorException(NULL, NULL, 0, "%d: %s", e->errorCode(), msg.str());
  943. item.setFailInfo(e->errorCode(), msg.str());
  944. switch(item.queryType())
  945. {
  946. case WFTypeNormal:
  947. item.setState(WFStateFail);
  948. break;
  949. case WFTypeSuccess:
  950. case WFTypeFailure:
  951. item.setState(WFStateNull);
  952. break;
  953. case WFTypeRecovery:
  954. item.setState(WFStateSkip);
  955. break;
  956. }
  957. unsigned failureWfid = item.queryFailure();
  958. if(failureWfid)
  959. {
  960. try
  961. {
  962. executeItem(failureWfid, failureWfid);
  963. }
  964. catch(WorkflowException * ce)
  965. {
  966. if(ce->queryType() == WorkflowException::ABORT)
  967. throw;
  968. reportContingencyFailure("FAILURE", ce);
  969. ce->Release();
  970. }
  971. }
  972. }
  973. int WorkflowMachine::queryLastFailCode() const
  974. {
  975. unsigned wfidFor = workflow->queryWfid(currentWfid).queryContingencyFor();
  976. if(!wfidFor)
  977. return 0;
  978. return workflow->queryWfid(wfidFor).queryFailCode();
  979. }
  980. char const * WorkflowMachine::queryLastFailMessage() const
  981. {
  982. unsigned wfidFor = workflow->queryWfid(currentWfid).queryContingencyFor();
  983. if(!wfidFor)
  984. return "";
  985. char const * ret = workflow->queryWfid(wfidFor).queryFailMessage();
  986. return ret ? ret : "";
  987. }
  988. const char * WorkflowMachine::queryEventName() const
  989. {
  990. //MORE: This doesn't work so well once we've done SEQUENTIAL transforms if they split a wf item into 2
  991. return workflow->queryWfid(currentWfid).queryEventName();
  992. }
  993. const char * WorkflowMachine::queryEventExtra() const
  994. {
  995. //MORE: This doesn't work so well once we've done SEQUENTIAL transforms if they split a wf item into 2
  996. return workflow->queryWfid(currentWfid).queryEventExtra();
  997. }
  998. IWorkflowItemIterator *createWorkflowItemIterator(IPropertyTree *p)
  999. {
  1000. return new CWorkflowItemIterator(p);
  1001. }
  1002. IWorkflowItemArray *createWorkflowItemArray(unsigned size)
  1003. {
  1004. return new CCloneWorkflowItemArray(size);
  1005. }
  1006. IWorkflowItem *createWorkflowItem(IPropertyTree * ptree, unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  1007. {
  1008. return new CWorkflowItem(ptree, wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor);
  1009. }