workflow.cpp 38 KB

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