workflow.cpp 39 KB

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