workflow.cpp 36 KB

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