workflow.js 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134
  1. // Licensed to Cloudera, Inc. under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. Cloudera, Inc. licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. // adding missing .filter for IE8
  17. if (!('filter' in Array.prototype)) {
  18. Array.prototype.filter= function(filter, that /*opt*/) {
  19. var other= [], v;
  20. for (var i=0, n= this.length; i<n; i++)
  21. if (i in this && filter.call(that, v= this[i], i, this))
  22. other.push(v);
  23. return other;
  24. };
  25. }
  26. // Since knockout maps arrays without calling "update" nor "create"
  27. // Provide a JSON string that will be parsed in custom 'create' and 'update' functions.
  28. var normalize_model_fields = (function() {
  29. var FIELDS = ['parameters', 'job_properties', 'files', 'archives', 'prepares', 'params'];
  30. function fn(node_model) {
  31. $.each(FIELDS, function(index, field) {
  32. if (field in node_model && $.isArray(node_model[field])) {
  33. node_model[field] = JSON.stringify(node_model[field]);
  34. }
  35. });
  36. }
  37. return fn;
  38. })();
  39. /**
  40. * Registry of models
  41. * - Each model should have an ID attribute.
  42. */
  43. var RegistryModule = function($) {
  44. var module = function() {
  45. var self = this;
  46. self.nodes = {};
  47. module.prototype.initialize.apply(self, arguments);
  48. return self;
  49. };
  50. $.extend(module.prototype, {
  51. // Normal stuff
  52. initialize: function() {},
  53. toString: function() {
  54. var self = this;
  55. var s = $.map(self.nodes, function(node) {
  56. return node.id();
  57. }).join();
  58. return s;
  59. },
  60. add: function(id, node) {
  61. var self = this;
  62. $(self).trigger('registry:add');
  63. self.nodes[String(id)] = node;
  64. },
  65. remove: function(id) {
  66. var self = this;
  67. $(self).trigger('registry:remove');
  68. delete self.nodes[String(id)];
  69. },
  70. get: function(id) {
  71. var self = this;
  72. return self.nodes[id];
  73. },
  74. clear: function() {
  75. var self = this;
  76. delete self.nodes;
  77. self.nodes = {};
  78. }
  79. });
  80. return module;
  81. };
  82. var Registry = RegistryModule($);
  83. /**
  84. * Modal Control
  85. * Displays a single node in a modal window of your choosing.
  86. * Make sure to update the 'context' member and 'template' members.
  87. * IMPORTANT: Use 'setTemplate', then 'show'.
  88. */
  89. var ModalModule = function($, ko) {
  90. var module = function(modal, template) {
  91. var self = this;
  92. self.el = self.modal = $(modal);
  93. self.context = ko.observable();
  94. self.template = ko.observable(template || '');
  95. self.bound = false;
  96. };
  97. module.prototype.show = function(context) {
  98. var self = this;
  99. if (context) {
  100. self.context(context);
  101. }
  102. ko.applyBindings(self, self.modal[0]);
  103. self.modal.modal('show');
  104. };
  105. module.prototype.hide = function(context) {
  106. var self = this;
  107. self.el.modal('hide');
  108. };
  109. module.prototype.setTemplate = function(template) {
  110. var self = this;
  111. ko.cleanNode(self.modal[0]);
  112. self.template( template );
  113. };
  114. module.prototype.recenter = function(offset_x, offset_y) {
  115. var self = this;
  116. var top = ( ($(window).height() - self.modal.outerHeight(false)) / 2 );
  117. var left = ( ($(window).width() - self.modal.outerWidth(false)) / 2 );
  118. if (top < 0) {
  119. top = 0;
  120. }
  121. if (left < 0) {
  122. left = 0;
  123. }
  124. top += offset_y || 0;
  125. left += offset_x || 0;
  126. self.modal.css({top: top +'px', left: left+'px'});
  127. };
  128. module.prototype.addDecorations = function () {
  129. $(".popover").remove();
  130. $("input[name='job_xml']:not(.pathChooser)").addClass("pathChooser").after(getFileBrowseButton($("input[name='job_xml']:not(.pathChooser)")));
  131. $("input[name='jar_path']").addClass("pathChooser").after(getFileBrowseButton($("input[name='jar_path']")));
  132. $("input[name='script_path']").addClass("pathChooser").after(getFileBrowseButton($("input[name='script_path']")));
  133. $("input[name='command']").addClass("pathChooser").after(getFileBrowseButton($("input[name='command']")));
  134. $("*[rel=popover]").popover({
  135. placement:'left',
  136. trigger:'hover'
  137. });
  138. }
  139. return module;
  140. };
  141. var Modal = ModalModule($, ko);
  142. /**
  143. * ID Generator
  144. * Generate a new ID starting from 1.
  145. * - Accepts a prefix that will be prepended like so: <prefix>:<id number>
  146. */
  147. var IdGeneratorModule = function($) {
  148. return function(options) {
  149. var self = this;
  150. $.extend(self, options);
  151. self.counter = 1;
  152. self.nextId = function() {
  153. return ((self.prefix) ? self.prefix + ':' : '') + self.counter++;
  154. };
  155. };
  156. };
  157. var IdGenerator = IdGeneratorModule($);
  158. var ModelModule = function($) {
  159. var module = function(attrs) {
  160. var self = this;
  161. $.extend(self, attrs);
  162. module.prototype.initialize.apply(self, arguments);
  163. return self;
  164. };
  165. $.extend(module.prototype, {
  166. // Normal stuff
  167. initialize: function(){},
  168. toString: function() {
  169. var self = this;
  170. return JSON.stringify(self, null, '\t');
  171. }
  172. });
  173. return module;
  174. };
  175. var WorkflowModel = ModelModule($);
  176. $.extend(WorkflowModel.prototype, {
  177. id: 0,
  178. name: '',
  179. description: '',
  180. start: 0,
  181. end: 0,
  182. schema_version: 0.4,
  183. deployment_dir: '',
  184. is_shared: true,
  185. parameters: '[]',
  186. job_xml: ''
  187. });
  188. var NodeModel = ModelModule($);
  189. $.extend(NodeModel.prototype, {
  190. id: 0,
  191. name: '',
  192. description: '',
  193. node_type: '',
  194. workflow: 0,
  195. child_links: []
  196. });
  197. var ForkModel = ModelModule($);
  198. $.extend(ForkModel.prototype, {
  199. id: 0,
  200. name: '',
  201. description: '',
  202. node_type: 'fork',
  203. workflow: 0,
  204. child_links: []
  205. });
  206. var DecisionModel = ModelModule($);
  207. $.extend(DecisionModel.prototype, {
  208. id: 0,
  209. name: '',
  210. description: '',
  211. node_type: 'decision',
  212. workflow: 0,
  213. child_links: []
  214. });
  215. var DistCPModel = ModelModule($);
  216. $.extend(DistCPModel.prototype, {
  217. id: 0,
  218. name: '',
  219. description: '',
  220. node_type: 'distcp',
  221. workflow: 0,
  222. job_properties: [],
  223. prepares: [],
  224. job_xml: '',
  225. params: [],
  226. child_links: []
  227. });
  228. var MapReduceModel = ModelModule($);
  229. $.extend(MapReduceModel.prototype, {
  230. id: 0,
  231. name: '',
  232. description: '',
  233. node_type: 'mapreduce',
  234. workflow: 0,
  235. files: [],
  236. archives: [],
  237. job_properties: [],
  238. jar_path: '',
  239. prepares: [],
  240. job_xml: '',
  241. child_links: []
  242. });
  243. var StreamingModel = ModelModule($);
  244. $.extend(StreamingModel.prototype, {
  245. id: 0,
  246. name: '',
  247. description: '',
  248. node_type: 'streaming',
  249. workflow: 0,
  250. files: [],
  251. archives: [],
  252. job_properties: [],
  253. mapper: '',
  254. reducer: '',
  255. child_links: []
  256. });
  257. var JavaModel = ModelModule($);
  258. $.extend(JavaModel.prototype, {
  259. id: 0,
  260. name: '',
  261. description: '',
  262. node_type: 'java',
  263. workflow: 0,
  264. files: [],
  265. archives: [],
  266. job_properties: [],
  267. jar_path: '',
  268. prepares: [],
  269. job_xml: '',
  270. main_class: '',
  271. args: '',
  272. java_opts: '',
  273. child_links: []
  274. });
  275. var PigModel = ModelModule($);
  276. $.extend(PigModel.prototype, {
  277. id: 0,
  278. name: '',
  279. description: '',
  280. node_type: 'pig',
  281. workflow: 0,
  282. files: [],
  283. archives: [],
  284. job_properties: [],
  285. prepares: [],
  286. job_xml: '',
  287. params: [],
  288. script_path: '',
  289. child_links: []
  290. });
  291. var HiveModel = ModelModule($);
  292. $.extend(HiveModel.prototype, {
  293. id: 0,
  294. name: '',
  295. description: '',
  296. node_type: 'hive',
  297. workflow: 0,
  298. files: [],
  299. archives: [],
  300. job_properties: [],
  301. prepares: [],
  302. job_xml: '',
  303. params: [],
  304. script_path: '',
  305. child_links: []
  306. });
  307. var SqoopModel = ModelModule($);
  308. $.extend(SqoopModel.prototype, {
  309. id: 0,
  310. name: '',
  311. description: '',
  312. node_type: 'sqoop',
  313. workflow: 0,
  314. files: [],
  315. archives: [],
  316. job_properties: [],
  317. prepares: [],
  318. job_xml: '',
  319. params: [],
  320. script_path: '',
  321. child_links: []
  322. });
  323. var ShellModel = ModelModule($);
  324. $.extend(ShellModel.prototype, {
  325. id: 0,
  326. name: '',
  327. description: '',
  328. node_type: 'shell',
  329. workflow: 0,
  330. files: [],
  331. archives: [],
  332. job_properties: [],
  333. prepares: [],
  334. job_xml: '',
  335. params: [],
  336. command: '',
  337. capture_output: false,
  338. child_links: []
  339. });
  340. var SshModel = ModelModule($);
  341. $.extend(SshModel.prototype, {
  342. id: 0,
  343. name: '',
  344. description: '',
  345. node_type: 'ssh',
  346. workflow: 0,
  347. user: '',
  348. host: '',
  349. params: [],
  350. command: '',
  351. capture_output: false,
  352. child_links: []
  353. });
  354. function nodeModelChooser(node_type) {
  355. switch(node_type) {
  356. case 'mapreduce':
  357. return MapReduceModel;
  358. case 'streaming':
  359. return StreamingModel;
  360. case 'java':
  361. return JavaModel;
  362. case 'pig':
  363. return PigModel;
  364. case 'hive':
  365. return HiveModel;
  366. case 'sqoop':
  367. return SqoopModel;
  368. case 'shell':
  369. return ShellModel;
  370. case 'ssh':
  371. return SshModel;
  372. case 'distcp':
  373. return DistCPModel;
  374. case 'fork':
  375. return ForkModel;
  376. case 'decision':
  377. return DecisionModel;
  378. default:
  379. return NodeModel;
  380. }
  381. }
  382. var IdGeneratorTable = {
  383. mapreduce: new IdGenerator({prefix: 'mapreduce'}),
  384. streaming: new IdGenerator({prefix: 'streaming'}),
  385. java: new IdGenerator({prefix: 'java'}),
  386. pig: new IdGenerator({prefix: 'pig'}),
  387. hive: new IdGenerator({prefix: 'hive'}),
  388. sqoop: new IdGenerator({prefix: 'sqoop'}),
  389. shell: new IdGenerator({prefix: 'shell'}),
  390. ssh: new IdGenerator({prefix: 'ssh'}),
  391. distcp: new IdGenerator({prefix: 'distcp'}),
  392. fork: new IdGenerator({prefix: 'fork'}),
  393. decision: new IdGenerator({prefix: 'decision'}),
  394. join: new IdGenerator({prefix: 'join'}),
  395. kill: new IdGenerator({prefix: 'kill'})
  396. };
  397. var NodeModule = function($, IdGeneratorTable) {
  398. var META_LINKS = ['related', 'default', 'error'];
  399. var linkTypeChooser = function(parent, child) {
  400. if (child.node_type() == 'kill') {
  401. return 'error';
  402. }
  403. switch(parent.node_type()) {
  404. case 'start':
  405. return (child.node_type() == 'end') ? 'related' : 'to';
  406. case 'fork':
  407. return (child.node_type() == 'join') ? 'related' : 'start';
  408. case 'decision':
  409. return 'start';
  410. case 'join':
  411. return 'to';
  412. default:
  413. return 'ok';
  414. };
  415. };
  416. var module = function(workflow, model, registry) {
  417. var self = this;
  418. self.map(model);
  419. self.links = ko.computed(function() {
  420. var links = self.child_links().filter(function(element, index, arr) {
  421. return $.inArray(element.name(), META_LINKS) == -1;
  422. });
  423. return links;
  424. });
  425. self.meta_links = ko.computed(function() {
  426. var links = self.child_links().filter(function(element, index, arr) {
  427. return $.inArray(element.name(), META_LINKS) != -1;
  428. });
  429. return links;
  430. });
  431. self._workflow = workflow;
  432. self.registry = registry;
  433. self.children = ko.observableArray([]);
  434. self.model = model;
  435. var errors = {};
  436. for(var key in model) {
  437. switch(key) {
  438. case 'child_links':
  439. case 'node_ptr':
  440. case 'initialize':
  441. case 'toString':
  442. break;
  443. default:
  444. errors[key] = [];
  445. break;
  446. }
  447. }
  448. self.errors = ko.mapping.fromJS(errors);
  449. self.edit_template = model.node_type + 'EditTemplate';
  450. switch(model.node_type) {
  451. case 'start':
  452. self.view_template = ko.observable('startTemplate');
  453. break;
  454. case 'kill':
  455. case 'end':
  456. self.view_template = ko.observable('emptyTemplate');
  457. break;
  458. case 'fork':
  459. self.view_template = ko.observable('forkTemplate');
  460. break;
  461. case 'decision':
  462. self.view_template = ko.observable('decisionTemplate');
  463. break;
  464. case 'join':
  465. self.view_template = ko.observable('joinTemplate');
  466. break;
  467. default:
  468. self.view_template = ko.observable('nodeTemplate');
  469. break;
  470. }
  471. // Data manipulation
  472. if ('job_properties' in model) {
  473. self.addProp = function() {
  474. var prop = { name: ko.observable(""), value: ko.observable("") };
  475. prop.name.subscribe(function(value) {
  476. self.job_properties.valueHasMutated();
  477. });
  478. prop.value.subscribe(function(value) {
  479. self.job_properties.valueHasMutated();
  480. });
  481. self.job_properties.push(prop);
  482. // $(".propKey:last").each(addAutoComplete);
  483. };
  484. self.removeProp = function(val) {
  485. self.job_properties.remove(val);
  486. };
  487. }
  488. if ('files' in model) {
  489. self.addFile = function() {
  490. var prop = { name: ko.observable(""), dummy: ko.observable("") };
  491. prop.name.subscribe(function(value) {
  492. self.files.valueHasMutated();
  493. });
  494. prop.dummy.subscribe(function(value) {
  495. self.files.valueHasMutated();
  496. });
  497. self.files.push(prop);
  498. };
  499. self.removeFile = function(val) {
  500. self.files.remove(val);
  501. };
  502. }
  503. if ('archives' in model) {
  504. self.addArchive = function() {
  505. var prop = { name: ko.observable(""), dummy: ko.observable("") };
  506. prop.name.subscribe(function(value) {
  507. self.archives.valueHasMutated();
  508. });
  509. prop.dummy.subscribe(function(value) {
  510. self.archives.valueHasMutated();
  511. });
  512. self.archives.push(prop);
  513. };
  514. self.removeArchive = function(val) {
  515. self.archives.remove(val);
  516. };
  517. }
  518. if ('params' in model) {
  519. self.addParam = function() {
  520. var prop = { value: ko.observable(""), type: ko.observable("param") };
  521. prop.value.subscribe(function(value) {
  522. self.params.valueHasMutated();
  523. });
  524. prop.type.subscribe(function(value) {
  525. self.params.valueHasMutated();
  526. });
  527. self.params.push(prop);
  528. };
  529. self.addArgument = function() {
  530. var prop = { value: ko.observable(""), type: ko.observable("argument") };
  531. prop.value.subscribe(function(value) {
  532. self.params.valueHasMutated();
  533. });
  534. prop.type.subscribe(function(value) {
  535. self.params.valueHasMutated();
  536. });
  537. self.params.push(prop);
  538. };
  539. self.addArg = function() {
  540. var prop = { value: ko.observable(""), type: ko.observable("arg") };
  541. prop.value.subscribe(function(value) {
  542. self.params.valueHasMutated();
  543. });
  544. prop.type.subscribe(function(value) {
  545. self.params.valueHasMutated();
  546. });
  547. self.params.push(prop);
  548. };
  549. self.addEnvVar = function() {
  550. var prop = { value: ko.observable(""), type: ko.observable("env-var") };
  551. prop.value.subscribe(function(value) {
  552. self.params.valueHasMutated();
  553. });
  554. prop.type.subscribe(function(value) {
  555. self.params.valueHasMutated();
  556. });
  557. self.params.push(prop);
  558. };
  559. self.removeParam = function(val) {
  560. self.params.remove(val);
  561. };
  562. }
  563. if ('prepares' in model) {
  564. self.addPrepareDelete = function() {
  565. var prop = { value: ko.observable(""), type: ko.observable("delete") };
  566. prop.value.subscribe(function(value) {
  567. self.prepares.valueHasMutated();
  568. });
  569. prop.type.subscribe(function(value) {
  570. self.prepares.valueHasMutated();
  571. });
  572. self.prepares.push(prop);
  573. };
  574. self.addPrepareMkdir = function() {
  575. var prop = { value: ko.observable(""), type: ko.observable("mkdir") };
  576. prop.value.subscribe(function(value) {
  577. self.prepares.valueHasMutated();
  578. });
  579. prop.type.subscribe(function(value) {
  580. self.prepares.valueHasMutated();
  581. });
  582. self.prepares.push(prop);
  583. };
  584. self.removePrepare = function(val) {
  585. self.prepares.remove(val);
  586. };
  587. }
  588. self.initialize.apply(self, arguments);
  589. return self;
  590. };
  591. $.extend(module.prototype, {
  592. // Data.
  593. children: null,
  594. model: null,
  595. // Normal stuff
  596. /**
  597. * Called when creating a new node
  598. */
  599. initialize: function(workflow, model, registry) {},
  600. toString: function() {
  601. return '';
  602. },
  603. /**
  604. * Fetches registry
  605. */
  606. getRegistry: function() {
  607. return registry;
  608. },
  609. /**
  610. * Maps a model to self
  611. * Called when creating a new node before any thing else
  612. */
  613. map: function(model) {
  614. var self = this;
  615. var map_params = function(options, subscribe) {
  616. options.data = ($.type(options.data) == "string") ? $.parseJSON(options.data) : options.data;
  617. if ($.isArray(options.data)) {
  618. var mapping = ko.mapping.fromJS(options.data);
  619. $.each(mapping(), function(index, value) {
  620. subscribe(value);
  621. });
  622. return mapping;
  623. } else {
  624. var mapping = ko.mapping.fromJS(options.data, {});
  625. subscribe(mapping);
  626. return mapping;
  627. }
  628. };
  629. // @see http://knockoutjs.com/documentation/plugins-mapping.html
  630. var mapping = ko.mapping.fromJS(model, {
  631. ignore: ['initialize','toString'],
  632. job_properties: {
  633. create: function(options) {
  634. var parent = options.parent;
  635. var subscribe = function(mapping) {
  636. mapping.name.subscribe(function(value) {
  637. parent.job_properties.valueHasMutated();
  638. });
  639. mapping.value.subscribe(function(value) {
  640. parent.job_properties.valueHasMutated();
  641. });
  642. };
  643. return map_params(options, subscribe);
  644. },
  645. update: function(options) {
  646. var parent = options.parent;
  647. var subscribe = function(mapping) {
  648. mapping.name.subscribe(function(value) {
  649. parent.job_properties.valueHasMutated();
  650. });
  651. mapping.value.subscribe(function(value) {
  652. parent.job_properties.valueHasMutated();
  653. });
  654. };
  655. return map_params(options, subscribe);
  656. }
  657. },
  658. files: {
  659. create: function(options) {
  660. return map_params(options, function() {});
  661. },
  662. update: function(options) {
  663. return map_params(options, function() {});
  664. }
  665. },
  666. archives: {
  667. create: function(options) {
  668. var parent = options.parent;
  669. var subscribe = function(mapping) {
  670. mapping.name.subscribe(function(value) {
  671. parent.archives.valueHasMutated();
  672. });
  673. mapping.dummy.subscribe(function(value) {
  674. parent.archives.valueHasMutated();
  675. });
  676. };
  677. return map_params(options, subscribe);
  678. },
  679. update: function(options) {
  680. var parent = options.parent;
  681. var subscribe = function(mapping) {
  682. mapping.name.subscribe(function(value) {
  683. parent.archives.valueHasMutated();
  684. });
  685. mapping.dummy.subscribe(function(value) {
  686. parent.archives.valueHasMutated();
  687. });
  688. };
  689. return map_params(options, subscribe);
  690. }
  691. },
  692. params: {
  693. create: function(options) {
  694. var parent = options.parent;
  695. var subscribe = function(mapping) {
  696. mapping.value.subscribe(function(value) {
  697. parent.params.valueHasMutated();
  698. });
  699. mapping.type.subscribe(function(value) {
  700. parent.params.valueHasMutated();
  701. });
  702. };
  703. return map_params(options, subscribe);
  704. },
  705. update: function(options) {
  706. var parent = options.parent;
  707. var subscribe = function(mapping) {
  708. mapping.value.subscribe(function(value) {
  709. parent.params.valueHasMutated();
  710. });
  711. mapping.type.subscribe(function(value) {
  712. parent.params.valueHasMutated();
  713. });
  714. };
  715. return map_params(options, subscribe);
  716. }
  717. },
  718. prepares: {
  719. create: function(options) {
  720. var parent = options.parent;
  721. var subscribe = function(mapping) {
  722. mapping.value.subscribe(function(value) {
  723. parent.prepares.valueHasMutated();
  724. });
  725. mapping.type.subscribe(function(value) {
  726. parent.prepares.valueHasMutated();
  727. });
  728. };
  729. return map_params(options, subscribe);
  730. },
  731. update: function(options) {
  732. var parent = options.parent;
  733. var subscribe = function(mapping) {
  734. mapping.value.subscribe(function(value) {
  735. parent.prepares.valueHasMutated();
  736. });
  737. mapping.type.subscribe(function(value) {
  738. parent.prepares.valueHasMutated();
  739. });
  740. };
  741. return map_params(options, subscribe);
  742. }
  743. }
  744. });
  745. $.extend(self, mapping);
  746. $.each(mapping, function(key, value) {
  747. var key = key;
  748. if (ko.isObservable(self[key])) {
  749. self[key].subscribe(function(value) {
  750. model[key] = ko.mapping.toJS(value);
  751. });
  752. }
  753. });
  754. $.each(self.child_links(), function(index, link) {
  755. var $index = index;
  756. link.comment.subscribe(function(value) {
  757. self.model.child_links[$index].comment = value;
  758. });
  759. link.child.subscribe(function(value) {
  760. self.model.child_links[$index].child = value;
  761. });
  762. });
  763. },
  764. validate: function( ) {
  765. var self = this;
  766. var options = {};
  767. data = $.extend(true, {}, self.model);
  768. var success = false;
  769. var request = $.extend({
  770. url: '/oozie/workflows/' + self._workflow.id() + '/actions/' + self.node_type() + '/validate',
  771. type: 'POST',
  772. data: { node: JSON.stringify(data) },
  773. success: function(data) {
  774. ko.mapping.fromJS(data.data, self.errors);
  775. success = data.status == 0;
  776. },
  777. async: false,
  778. }, options);
  779. $.ajax(request);
  780. return success;
  781. },
  782. // Hierarchy manipulation.
  783. /**
  784. * Append node to self
  785. * Does not support multiple children.
  786. * Ensures single child.
  787. * Ensures no cycles.
  788. * 1. Finds all children and attaches them to node (cleans node first).
  789. * 2. Remove all children from self.
  790. * 3. Attach node to self.
  791. */
  792. append: function(node) {
  793. var self = this;
  794. // Not fork nor decision nor self
  795. if ($.inArray(self.node_type(), ['fork', 'decision']) == -1 && node.id() != self.id()) {
  796. node.removeAllChildren();
  797. $.each(self.links(), function(index, link) {
  798. node.addChild(registry.get(link.child()));
  799. });
  800. self.removeAllChildren();
  801. self.addChild(node);
  802. }
  803. },
  804. /**
  805. * Find all parents of current node
  806. */
  807. findParents: function() {
  808. var self = this;
  809. var parents = [];
  810. $.each(registry.nodes, function(id, node) {
  811. $.each(node.links(), function(index, link) {
  812. if (link.child() == self.id()) {
  813. parents.push(node);
  814. }
  815. });
  816. });
  817. return parents;
  818. },
  819. /**
  820. * Find all children of current node
  821. */
  822. findChildren: function() {
  823. var self = this;
  824. var children = [];
  825. $.each(self.links(), function(index, link) {
  826. children.push(registry.get(link.child()));
  827. });
  828. return children;
  829. },
  830. /**
  831. * Detach current node from the graph
  832. * 1. Takes children of self node, removes them from self node, and adds them to each parent of self node.
  833. * 2. The self node is then removed from every parent.
  834. * 3. Does not support multiple children since we do not automatically fork.
  835. */
  836. detach: function() {
  837. var self = this;
  838. $.each(self.findParents(), function(index, parent) {
  839. $.each(self.links(), function(index, link) {
  840. var node = registry.get(link.child());
  841. parent.replaceChild(self, node);
  842. });
  843. });
  844. $(self).trigger('detached');
  845. self.removeAllChildren();
  846. },
  847. /**
  848. * Add child
  849. * Update child links for this node.
  850. */
  851. addChild: function(node) {
  852. var self = this;
  853. var link = {
  854. parent: ko.observable(self.id()),
  855. child: ko.observable(node.id()),
  856. name: ko.observable(linkTypeChooser(self, node)),
  857. comment: ko.observable('')
  858. };
  859. self.child_links.unshift(link);
  860. },
  861. /**
  862. * Remove child node
  863. * 1. Find child node link
  864. * 2. Remove child node link
  865. */
  866. removeChild: function(node) {
  867. var self = this;
  868. var spliceIndex = -1;
  869. $.each(self.child_links(), function(index, link) {
  870. if (link.child() == node.id()) {
  871. spliceIndex = index;
  872. }
  873. });
  874. if (spliceIndex > -1) {
  875. self.child_links.splice(spliceIndex, 1);
  876. }
  877. return spliceIndex != -1;
  878. },
  879. /**
  880. * Remove all children
  881. * Removes all children except for related, default, and error links
  882. * Note: we hold on to related, default, and error links because
  883. * we have to.
  884. */
  885. removeAllChildren: function() {
  886. var self = this;
  887. var keep_links = [];
  888. $.each(self.child_links(), function(index, link) {
  889. if ($.inArray(link.name(), META_LINKS) > -1) {
  890. keep_links.push(link);
  891. }
  892. });
  893. self.child_links.removeAll();
  894. $.each(keep_links, function(index, link) {
  895. self.child_links.push(link);
  896. });
  897. },
  898. /**
  899. * Replace child node with another node in the following way:
  900. * 1. Find child index
  901. * 2. Remove child index
  902. * 3. Remove and remember every element after child
  903. * 4. Add replacement node
  904. * 5. Add every child that was remembered
  905. */
  906. replaceChild: function(child, replacement) {
  907. var self = this;
  908. var index = -1;
  909. $.each(self.child_links(), function(i, link) {
  910. if (link.child() == child.id()) {
  911. index = i;
  912. }
  913. });
  914. if (index > -1) {
  915. self.child_links.splice(index, 1);
  916. var links = self.child_links.splice(index);
  917. var link = {
  918. parent: ko.observable(self.id()),
  919. child: ko.observable(replacement.id()),
  920. name: ko.observable(linkTypeChooser(self, replacement)),
  921. comment: ko.observable(''),
  922. };
  923. self.child_links.push(link);
  924. $.each(links, function(index, link) {
  925. self.child_links.push(link);
  926. });
  927. }
  928. return index != -1;
  929. },
  930. isChild: function(node) {
  931. var self = this;
  932. var res = false;
  933. $.each(self.links(), function(index, link) {
  934. if (link.child() == node.id()) {
  935. res = true;
  936. }
  937. });
  938. return res;
  939. },
  940. erase: function() {
  941. var self = this;
  942. self.registry.remove(self.id());
  943. }
  944. });
  945. return module;
  946. };
  947. var Node = NodeModule($, IdGeneratorTable);
  948. var StartNode = NodeModule($, IdGeneratorTable);
  949. $.extend(StartNode.prototype, Node.prototype, {
  950. /**
  951. * Same as addChild for nodes, except if we reach the end,
  952. * we add the end node to our child_links in the form of a
  953. * 'related' link and 'start' link.
  954. * We should always have a start link in an empty workflow!
  955. */
  956. replaceChild: function(child, replacement) {
  957. var self = this;
  958. var index = -1;
  959. $.each(self.child_links(), function(i, link) {
  960. if (link.child() == child.id()) {
  961. index = i;
  962. }
  963. });
  964. if (index > -1) {
  965. self.child_links.splice(index, 1);
  966. var links = self.child_links.splice(index);
  967. var link = {
  968. parent: ko.observable(self.id()),
  969. child: ko.observable(replacement.id()),
  970. name: ko.observable('to'),
  971. comment: ko.observable(''),
  972. };
  973. self.child_links.push(link);
  974. $.each(links, function(index, link) {
  975. self.child_links.push(link);
  976. });
  977. }
  978. return index != -1;
  979. },
  980. });
  981. var ForkNode = NodeModule($, IdGeneratorTable);
  982. $.extend(ForkNode.prototype, Node.prototype, {
  983. // Join nodes are connected through 'related' links
  984. join: function() {
  985. var self = this;
  986. var join = null;
  987. $.each(self.child_links(), function(index, link) {
  988. if (link.name() == 'related') {
  989. join = self.registry.get(link.child());
  990. }
  991. });
  992. return join;
  993. },
  994. /**
  995. * Append a node to the current fork
  996. * Also adds join node to node.
  997. * When adding the join node, append will remove all the children from the join!
  998. * We need to make sure the join remembers its children.
  999. * NOTE: Cannot append a fork! Use addChild or replaceChild instead!
  1000. */
  1001. append: function(node) {
  1002. var self = this;
  1003. if (node.node_type() != 'fork') {
  1004. var join = self.join();
  1005. if (join.id() != node.id()) {
  1006. var children = join.findChildren();
  1007. self.addChild(node);
  1008. node.append(join);
  1009. // remember children
  1010. $.each(children, function(index, child) {
  1011. join.addChild(child);
  1012. });
  1013. }
  1014. }
  1015. },
  1016. /**
  1017. * Replace child node with another node
  1018. * 1. Remove child if the replacement is related join
  1019. * 2. Apply Node.replaceChild for all other causes
  1020. * NOTE: can assume the only join this fork will ever see is the related join!
  1021. * This is because the related will always be the closest join for children.
  1022. * Also, the operations allowed that would make this all possible: detach, append;
  1023. * are inherently going to remove any other joins if they exist.
  1024. * This is also easier given nodes are contained within Forks!
  1025. */
  1026. replaceChild: function(child, replacement) {
  1027. var self = this;
  1028. var ret = true;
  1029. if (self.join().id() == replacement.id()) {
  1030. ret = self.removeChild(child);
  1031. } else {
  1032. ret = Node.prototype.replaceChild.apply(self, arguments);
  1033. }
  1034. var links = self.links().filter(function(element, index, arr) {
  1035. return self.registry.get(element.child()).node_type() != 'join';
  1036. });
  1037. if (links.length < 2) {
  1038. self.detach();
  1039. self.join().detach();
  1040. self.erase();
  1041. self.join().erase();
  1042. }
  1043. return ret;
  1044. },
  1045. /**
  1046. * Converts fork node into decision node in the following way:
  1047. * 1. Copies contents of current fork node into a new decision node
  1048. * 2. Detach fork node
  1049. * 3. Erase fork node
  1050. * 4. Append decision node to parent
  1051. */
  1052. convertToDecision: function() {
  1053. var self = this;
  1054. var join = self.join();
  1055. var end = null;
  1056. var child = join.findChildren()[0];
  1057. if (child.findParents().length == 1) {
  1058. end = child;
  1059. }
  1060. // Attaches child of join to parents of join
  1061. join.detach();
  1062. var decision_model = new DecisionModel({
  1063. id: IdGeneratorTable['decision'].nextId(),
  1064. name: self.name(),
  1065. description: self.description(),
  1066. node_type: 'decision',
  1067. workflow: self.workflow(),
  1068. child_links: self.model.child_links
  1069. });
  1070. var default_link = {
  1071. parent: decision_model.id,
  1072. child: self._workflow.end(),
  1073. name: 'default',
  1074. comment: ''
  1075. };
  1076. decision_model.child_links.push(default_link);
  1077. $.each(decision_model.child_links, function(index, link) {
  1078. link.parent = decision_model.id;
  1079. });
  1080. var decision_node = new DecisionNode(self._workflow, decision_model, self.registry);
  1081. if (end) {
  1082. decision_node.addEnd(end);
  1083. }
  1084. var parents = self.findParents();
  1085. decision_node.removeChild(join);
  1086. join.erase();
  1087. self.erase();
  1088. self.registry.add(decision_node.id(), decision_node);
  1089. $.each(parents, function(index, parent) {
  1090. parent.replaceChild(self, decision_node);
  1091. });
  1092. }
  1093. });
  1094. var DecisionNode = NodeModule($, IdGeneratorTable);
  1095. $.extend(DecisionNode.prototype, ForkNode.prototype, {
  1096. initialize: function(workflow, model, registry) {
  1097. var self = this;
  1098. var registry = registry;
  1099. var end = null;
  1100. $.each(self.child_links(), function(index, link) {
  1101. if (link.name() == 'related') {
  1102. $(registry).bind('registry:add', function(e) {
  1103. var end = self.end();
  1104. if (end) {
  1105. self.removeEnd();
  1106. self.addEnd(end);
  1107. $(registry).unbind(e);
  1108. }
  1109. });
  1110. }
  1111. });
  1112. },
  1113. // Only a single end allowed for now!
  1114. // Finds end for branch
  1115. findEnd: function( ) {
  1116. var self = this;
  1117. var end = self.end();
  1118. if (!end) {
  1119. return self._findEnd( self, 0 );
  1120. }
  1121. return end;
  1122. },
  1123. _findEnd: function( node, count ) {
  1124. var self = this;
  1125. var end = null;
  1126. if (node.findParents().length > 1 && --count == 0) {
  1127. return node;
  1128. }
  1129. if (node.node_type() == 'decision' || node.node_type() == 'fork') {
  1130. count++;
  1131. }
  1132. $.each(node.findChildren(), function(index, node) {
  1133. if (end == null) {
  1134. end = self._findEnd(node, count);
  1135. }
  1136. });
  1137. return end;
  1138. },
  1139. end: function() {
  1140. var self = this;
  1141. var end = null;
  1142. $.each(self.child_links(), function(index, link) {
  1143. if (link.name() == 'related') {
  1144. end = self.registry.get(link.child());
  1145. }
  1146. });
  1147. return end;
  1148. },
  1149. addEnd: function(node) {
  1150. var self = this;
  1151. self.child_links.push({
  1152. parent: ko.observable(self.id()),
  1153. child: ko.observable(node.id()),
  1154. name: ko.observable('related'),
  1155. comment: ko.observable(''),
  1156. });
  1157. $(node).one('detached', function(e) {
  1158. var end = self.end();
  1159. if (end.links().length == 1) {
  1160. self.removeEnd();
  1161. var new_end = self.findEnd();
  1162. self.addEnd(new_end);
  1163. } else {
  1164. // Should never hit this case.
  1165. self.removeEnd();
  1166. }
  1167. });
  1168. },
  1169. removeEnd: function() {
  1170. var self = this;
  1171. var spliceIndex = -1;
  1172. $.each(self.child_links(), function(index, link) {
  1173. if (link.name() == 'related') {
  1174. spliceIndex = index;
  1175. }
  1176. });
  1177. if (spliceIndex > -1) {
  1178. var end = registry.get(self.child_links()[spliceIndex].child());
  1179. self.child_links.splice(spliceIndex, 1);
  1180. return true;
  1181. }
  1182. return false;
  1183. },
  1184. isChild: function(node) {
  1185. var self = this;
  1186. return self._isChild(node, self, 0);
  1187. },
  1188. _isChild: function( test_child, node, count ) {
  1189. var self = this;
  1190. var result = node.id() == test_child.id();
  1191. if (node.findParents().length > 1 && --count == 0) {
  1192. return result;
  1193. }
  1194. if (node.node_type() == 'decision' || node.node_type() == 'fork') {
  1195. count++;
  1196. }
  1197. $.each(node.findChildren(), function(index, node) {
  1198. if (!result) {
  1199. result = self._isChild(test_child, node, count);
  1200. }
  1201. });
  1202. return result;
  1203. },
  1204. /**
  1205. * Append a node to the current decision
  1206. * Also appends end node to node.
  1207. * NOTE: Cannot append a decision! Use addChild or replaceChild instead!
  1208. */
  1209. append: function(node) {
  1210. var self = this;
  1211. var end = self.findEnd();
  1212. if (end.id() == node.id()) {
  1213. return false;
  1214. }
  1215. self.addChild(node);
  1216. node.append(end);
  1217. return true;
  1218. },
  1219. /**
  1220. * Replace child node with another node
  1221. * 1. Remove child if the replacement is end
  1222. * 2. Apply Node.replaceChild for all other causes
  1223. */
  1224. replaceChild: function(child, replacement) {
  1225. var self = this;
  1226. var ret = true;
  1227. var end = self.findEnd();
  1228. if (end && end.id() == replacement.id()) {
  1229. ret = self.removeChild(child);
  1230. } else {
  1231. ret = Node.prototype.replaceChild.apply(self, arguments);
  1232. }
  1233. if (self.links().length < 2) {
  1234. self.detach();
  1235. self.erase();
  1236. }
  1237. return ret;
  1238. }
  1239. });
  1240. /**
  1241. * Workflow module
  1242. */
  1243. var WorkflowModule = function($, NodeModelChooser, Node, ForkNode, DecisionNode, IdGeneratorTable) {
  1244. var module = function(options) {
  1245. var self = this;
  1246. // @see http://knockoutjs.com/documentation/plugins-mapping.html
  1247. var mapping = ko.mapping.fromJS(options.model, {
  1248. ignore: ['initialize','toString'],
  1249. job_properties: {
  1250. create: function(options) {
  1251. var mapping = ko.mapping.fromJS($.parseJSON(options.data) || options.data);
  1252. var parent = options.parent;
  1253. mapping.name.subscribe(function(value) {
  1254. parent.job_properties.valueHasMutated();
  1255. });
  1256. mapping.value.subscribe(function(value) {
  1257. parent.job_properties.valueHasMutated();
  1258. });
  1259. return mapping;
  1260. },
  1261. update: function(options) {
  1262. var mapping = ko.mapping.fromJS($.parseJSON(options.data) || options.data);
  1263. var parent = options.parent;
  1264. mapping.name.subscribe(function(value) {
  1265. parent.job_properties.valueHasMutated();
  1266. });
  1267. mapping.value.subscribe(function(value) {
  1268. parent.job_properties.valueHasMutated();
  1269. });
  1270. return mapping;
  1271. }
  1272. },
  1273. parameters: {
  1274. // Will receive individual objects to subscribe.
  1275. // Containing array is mapped automagically
  1276. create: function(options) {
  1277. var mapping = ko.mapping.fromJS($.parseJSON(options.data) || options.data);
  1278. var parent = options.parent;
  1279. mapping.name.subscribe(function(value) {
  1280. parent.parameters.valueHasMutated();
  1281. });
  1282. mapping.value.subscribe(function(value) {
  1283. parent.parameters.valueHasMutated();
  1284. });
  1285. return mapping;
  1286. },
  1287. update: function(options) {
  1288. var mapping = ko.mapping.fromJS($.parseJSON(options.data) || options.data);
  1289. var parent = options.parent;
  1290. mapping.name.subscribe(function(value) {
  1291. parent.parameters.valueHasMutated();
  1292. });
  1293. mapping.value.subscribe(function(value) {
  1294. parent.parameters.valueHasMutated();
  1295. });
  1296. return mapping;
  1297. },
  1298. }
  1299. });
  1300. $.extend(self, mapping);
  1301. $.each(mapping['__ko_mapping__'].mappedProperties, function(key, value) {
  1302. var key = key;
  1303. self[key].subscribe(function(value) {
  1304. workflow.is_dirty = true;
  1305. self.model[key] = ko.mapping.toJS(value);
  1306. });
  1307. });
  1308. self.model = options.model;
  1309. self.registry = options.registry;
  1310. self.options = options;
  1311. self.el = $('#workflow');
  1312. self.nodes = ko.observableArray([]);
  1313. self.kill = null;
  1314. self.url = ko.computed(function() {
  1315. return '/oozie/workflows/' + self.id()
  1316. });
  1317. // Events
  1318. self.el.on('workflow:rebuild', function() {
  1319. self.rebuild();
  1320. });
  1321. self.el.on('workflow:events:load', function() {
  1322. self.dragAndDropEvents();
  1323. });
  1324. self.el.on('workflow:droppables:load', function() {
  1325. self.droppables();
  1326. });
  1327. self.el.on('workflow:draggables:load', function() {
  1328. self.draggables();
  1329. });
  1330. self.dragAndDropEvents();
  1331. self.el.trigger('workflow:events:loaded');
  1332. module.prototype.initialize.apply(self, arguments);
  1333. return self;
  1334. };
  1335. $.extend(module.prototype, {
  1336. // Normal stuff
  1337. initialize: function(options) {
  1338. var self = this;
  1339. if ('data' in options) {
  1340. // Initialize nodes
  1341. if (options.data.nodes) {
  1342. self.registry.clear();
  1343. $.each(options.data.nodes, function(index, node) {
  1344. var NodeModel = NodeModelChooser(node.node_type);
  1345. var model = new NodeModel(node);
  1346. var temp = null;
  1347. switch(node.node_type) {
  1348. case 'start':
  1349. temp = new StartNode(self, model, self.registry);
  1350. break;
  1351. case 'fork':
  1352. temp = new ForkNode(self, model, self.registry);
  1353. break;
  1354. case 'decision':
  1355. temp = new DecisionNode(self, model, self.registry);
  1356. break;
  1357. case 'kill':
  1358. temp = self.kill = new Node(self, model, self.registry);
  1359. break;
  1360. default:
  1361. temp = new Node(self, model, self.registry);
  1362. break;
  1363. }
  1364. self.registry.add(temp.id(), temp);
  1365. });
  1366. }
  1367. // Update data
  1368. $.each(options.data, function (key, value) {
  1369. if (key in self) {
  1370. switch(key) {
  1371. case 'job_properties':
  1372. case 'parameters':
  1373. // These may be serialized JSON data since that is how they are stored
  1374. self[key].removeAll();
  1375. var arr = $.parseJSON(value) || value;
  1376. $.each(arr, function(index, obj) {
  1377. var mapping = ko.mapping.fromJS(obj);
  1378. mapping.name.subscribe(function(value) {
  1379. self[key].valueHasMutated();
  1380. });
  1381. mapping.value.subscribe(function(value) {
  1382. self[key].valueHasMutated();
  1383. });
  1384. self[key].push(mapping);
  1385. });
  1386. break;
  1387. case 'nodes':
  1388. break;
  1389. default:
  1390. self[key](value);
  1391. break;
  1392. }
  1393. }
  1394. });
  1395. workflow.is_dirty = false;
  1396. }
  1397. if (!self.kill) {
  1398. var kill_json = {
  1399. "description": "",
  1400. "workflow": self.id(),
  1401. "child_links": [],
  1402. "node_type": "kill",
  1403. "message": "Action failed, error message[${wf:errorMessage(wf:lastErrorNode())}]",
  1404. "name": "kill",
  1405. "id": IdGeneratorTable['kill'].nextId()
  1406. };
  1407. var NodeModel = NodeModelChooser(kill_json.node_type);
  1408. var model = new NodeModel(kill_json);
  1409. self.kill = new Node(self, model, self.registry);
  1410. self.registry.add(self.kill.id(), self.kill);
  1411. }
  1412. },
  1413. toString: function() {
  1414. return '';
  1415. var s = '[';
  1416. $.each(self.registry.nodes, function(key, node) {
  1417. s += node.model.toString() + ",\n";
  1418. });
  1419. return s + ']';
  1420. },
  1421. // Data manipulation
  1422. cloneNode: function(node, event) {
  1423. var self = this;
  1424. var model_copy = $.extend(true, {}, node.model);
  1425. var template = model_copy.node_type + 'EditTemplate';
  1426. var NodeModel = NodeModelChooser(node.node_type());
  1427. model_copy.id = IdGeneratorTable[model_copy.node_type].nextId();
  1428. model_copy.name += '-copy';
  1429. model_copy.child_links = [];
  1430. var model = new NodeModel(model_copy);
  1431. var new_node = new Node(self, model, self.registry);
  1432. self.registry.add(new_node.id(), new_node);
  1433. new_node.addChild(self.kill);
  1434. node.append(new_node);
  1435. self.rebuild();
  1436. modal.setTemplate(template);
  1437. modal.show(new_node);
  1438. modal.recenter(280, 250);
  1439. modal.addDecorations();
  1440. // $(".propKey").each(addAutoComplete);
  1441. workflow.is_dirty = true;
  1442. },
  1443. removeNode: function(node, event) {
  1444. var self = this;
  1445. node.detach();
  1446. node.erase();
  1447. self.rebuild();
  1448. workflow.is_dirty = true;
  1449. },
  1450. save: function( options ) {},
  1451. load: function() {
  1452. var self = this;
  1453. $.getJSON(self.url(), function(data) {
  1454. if (data.status == 0) {
  1455. self.reload(data.data);
  1456. } else {
  1457. $.jHueNotify.error("${ _('Received invalid response from server: ') }" + JSON.stringify(data));
  1458. }
  1459. });
  1460. },
  1461. reload: function(data) {
  1462. var self = this;
  1463. // Clear all children
  1464. $.each(self.registry.nodes, function(index, node) {
  1465. node.children.removeAll();
  1466. });
  1467. self.nodes.removeAll();
  1468. self.initialize({data: data});
  1469. self.rebuild();
  1470. self.el.trigger('workflow:loaded');
  1471. },
  1472. addParameter: function(data, event) {
  1473. var self = this;
  1474. var prop = { name: ko.observable(""), value: ko.observable("") };
  1475. // force bubble up to containing observable array.
  1476. prop.name.subscribe(function(){
  1477. self.parameters.valueHasMutated();
  1478. });
  1479. prop.value.subscribe(function(){
  1480. self.parameters.valueHasMutated();
  1481. });
  1482. self.parameters.push(prop);
  1483. },
  1484. removeParameter: function(data, event) {
  1485. var self = this;
  1486. self.parameters.remove(data);
  1487. },
  1488. addJobProperty: function(data, event) {
  1489. var self = this;
  1490. var prop = { name: ko.observable(""), value: ko.observable("") };
  1491. // force bubble up to containing observable array.
  1492. prop.name.subscribe(function(){
  1493. self.parameters.valueHasMutated();
  1494. });
  1495. prop.value.subscribe(function(){
  1496. self.parameters.valueHasMutated();
  1497. });
  1498. self.job_properties.push(prop);
  1499. },
  1500. removeJobProperty: function(data, event) {
  1501. var self = this;
  1502. self.job_properties.remove(data);
  1503. },
  1504. // Workflow UI
  1505. // Function to build nodes... recursively.
  1506. build: function() {
  1507. var self = this;
  1508. var maximum = 50;
  1509. var count = 0;
  1510. var methodChooser = function(node, collection, skip_parents_check) {
  1511. if (count++ >= maximum) {
  1512. if (window.error) {
  1513. console.error('Hit maximum number of node recursion: ' + maximum);
  1514. }
  1515. return null;
  1516. }
  1517. if (!node) {
  1518. return node;
  1519. }
  1520. var parents = node.findParents();
  1521. // Found end of decision node or found join!
  1522. if (parents.length > 1 && !skip_parents_check) {
  1523. return node;
  1524. }
  1525. switch(node.node_type()) {
  1526. case 'start':
  1527. case 'end':
  1528. case 'kill':
  1529. case 'fork':
  1530. case 'decision':
  1531. case 'join':
  1532. return control(node, collection);
  1533. default:
  1534. return normal(node, collection);
  1535. }
  1536. };
  1537. var normal = function(node, collection) {
  1538. collection.push(node);
  1539. var retNode = null;
  1540. $.each(node.links(), function(index, link) {
  1541. var next_node = self.registry.get(link.child());
  1542. retNode = methodChooser(next_node, collection, false, true);
  1543. });
  1544. return retNode;
  1545. };
  1546. var control = function(node, collection, skip_parents_check) {
  1547. switch(node.node_type()) {
  1548. case 'start':
  1549. case 'end':
  1550. case 'kill':
  1551. case 'join':
  1552. return normal(node, collection, false, true);
  1553. case 'fork':
  1554. collection.push(node);
  1555. // Wait for join.
  1556. // Iterate through all children and add them to child collection.
  1557. var join = null;
  1558. $.each(node.links(), function(index, link) {
  1559. var next_node = self.registry.get(link.child());
  1560. var collection = ko.observableArray([]);
  1561. node.children.push(collection);
  1562. join = methodChooser(next_node, collection, false, true);
  1563. });
  1564. // Add join to collection, then find its single child.
  1565. return methodChooser(join, collection, true, true);
  1566. case 'decision':
  1567. collection.push(node);
  1568. // Waits for end, then runs through children of end node
  1569. var end = null;
  1570. $.each(node.links(), function(index, link) {
  1571. var next_node = self.registry.get(link.child());
  1572. var collection = ko.observableArray([]);
  1573. node.children.push(collection);
  1574. end = methodChooser(next_node, collection, true, true);
  1575. });
  1576. // Add end
  1577. if (node.end() && end.id() == node.end().id()) {
  1578. return methodChooser(end, collection, true, true);
  1579. } else {
  1580. return end;
  1581. }
  1582. default:
  1583. // Should never get here.
  1584. return node;
  1585. }
  1586. };
  1587. methodChooser(self.registry.get(self.start()), self.nodes, false, true);
  1588. },
  1589. rebuild: function() {
  1590. var self = this;
  1591. // Clear all children
  1592. $.each(self.registry.nodes, function(index, node) {
  1593. node.children.removeAll();
  1594. });
  1595. self.nodes.removeAll();
  1596. // Rebuild
  1597. self.build();
  1598. self.draggables();
  1599. self.droppables();
  1600. self.el.trigger('workflow:rebuilt');
  1601. },
  1602. draggables: function() {
  1603. var self = this;
  1604. self.el.find('.node-action').each(function(index, el) {
  1605. if (!$(el).hasClass('ui-draggable')) {
  1606. $(el).draggable({
  1607. containment: [ self.el.offset().left - 10, self.el.offset().top - 10,
  1608. self.el.offset().left + self.el.outerWidth(), self.el.offset().top + self.el.outerHeight() ],
  1609. handle: '.node',
  1610. refreshPositions: true,
  1611. revert: true
  1612. });
  1613. }
  1614. });
  1615. },
  1616. droppables: function() {
  1617. var self = this;
  1618. self.el.find('.node-link').each(function(index, el) {
  1619. $(el).droppable({
  1620. 'hoverClass': 'node-link-hover',
  1621. 'greedy': true,
  1622. 'accept': '.node-action',
  1623. 'tolerance': 'pointer'
  1624. });
  1625. });
  1626. self.el.find('.node-decision-end').each(function(index, el) {
  1627. $(el).droppable({
  1628. 'hoverClass': 'node-link-hover',
  1629. 'greedy': true,
  1630. 'accept': '.node-action',
  1631. 'tolerance': 'pointer'
  1632. });
  1633. });
  1634. self.el.find('.node-fork .action').each(function(index, el) {
  1635. $(el).droppable({
  1636. 'hoverClass': 'node-fork-hover',
  1637. 'greedy': true,
  1638. 'accept': '.node-action',
  1639. 'tolerance': 'pointer'
  1640. });
  1641. });
  1642. self.el.find('.node-decision .action').each(function(index, el) {
  1643. $(el).droppable({
  1644. 'hoverClass': 'node-fork-hover',
  1645. 'greedy': true,
  1646. 'accept': '.node-action',
  1647. 'tolerance': 'pointer'
  1648. });
  1649. });
  1650. self.el.find('.node-action .action').each(function(index, el) {
  1651. $(el).droppable({
  1652. 'hoverClass': 'node-action-hover',
  1653. 'greedy': true,
  1654. 'accept': '.node-action',
  1655. 'tolerance': 'pointer'
  1656. });
  1657. });
  1658. },
  1659. dragAndDropEvents: function() {
  1660. var self = this;
  1661. // Build event delegations.
  1662. // Drop on node link
  1663. self.el.on('drop', '.node-link', function(e, ui) {
  1664. // draggable should be a node.
  1665. // droppable should be a link.
  1666. var draggable = ko.contextFor(ui.draggable[0]).$data;
  1667. var droppable = ko.contextFor(this).$data;
  1668. // If newParent is fork, prepend to child instead.
  1669. // This will make it so that we can drop and drop to the top of a node list within a fork.
  1670. var newParent = self.registry.get(droppable.parent());
  1671. if (newParent.id() != draggable.id()) {
  1672. if (newParent.isChild(draggable)) {
  1673. if (draggable.findParents().length > 1) {
  1674. // End of decision tree is being dragged to the bottom of a branch
  1675. draggable.detach();
  1676. newParent.append(draggable);
  1677. workflow.is_dirty = true;
  1678. self.rebuild();
  1679. }
  1680. } else {
  1681. switch(newParent.node_type()) {
  1682. case 'fork':
  1683. case 'decision':
  1684. draggable.detach();
  1685. var child = self.registry.get(droppable.child());
  1686. newParent.replaceChild(child, draggable);
  1687. draggable.addChild(child);
  1688. break;
  1689. case 'join':
  1690. // Join may disappear when we detach...
  1691. // Remember its children and append to child.
  1692. var parents = newParent.findParents();
  1693. draggable.detach();
  1694. if (newParent.findParents().length < 2) {
  1695. $.each(parents, function(index, parent) {
  1696. parent.append(draggable);
  1697. });
  1698. } else {
  1699. newParent.append(draggable);
  1700. }
  1701. break;
  1702. default:
  1703. draggable.detach();
  1704. newParent.append(draggable);
  1705. break;
  1706. }
  1707. workflow.is_dirty = true;
  1708. self.rebuild();
  1709. }
  1710. }
  1711. // Prevent bubbling events
  1712. return false;
  1713. });
  1714. // Drop on fork
  1715. self.el.on('drop', '.node-fork', function(e, ui) {
  1716. // draggable should be a node.
  1717. // droppable should be a fork.
  1718. var draggable = ko.contextFor(ui.draggable[0]).$data;
  1719. var droppable = ko.contextFor(this).$data;
  1720. if (!droppable.isChild(draggable) && droppable.id() != draggable.id()) {
  1721. draggable.detach();
  1722. droppable.append(draggable);
  1723. self.rebuild();
  1724. }
  1725. // Prevent bubbling events
  1726. return false;
  1727. });
  1728. // Drop on decision
  1729. self.el.on('drop', '.node-decision', function(e, ui) {
  1730. // draggable should be a node.
  1731. // droppable should be a fork.
  1732. var draggable = ko.contextFor(ui.draggable[0]).$data;
  1733. var droppable = ko.contextFor(this).$data;
  1734. if (!droppable.isChild(draggable) && droppable.id() != draggable.id()) {
  1735. draggable.detach();
  1736. droppable.append(draggable);
  1737. self.rebuild();
  1738. }
  1739. // Prevent bubbling events
  1740. return false;
  1741. });
  1742. // Drop on decision end link
  1743. self.el.on('drop', '.node-decision-end', function(e, ui) {
  1744. // draggable should be a node.
  1745. // droppable should be a decision end link... which should give us the decision node.
  1746. var draggable = ko.contextFor(ui.draggable[0]).$data;
  1747. var droppable = ko.contextFor(this).$data;
  1748. var end = droppable.findEnd(droppable);
  1749. if (end.id() != draggable.id()) {
  1750. draggable.detach();
  1751. $.each(end.findParents(), function(index, parent) {
  1752. if (droppable.isChild(parent)) {
  1753. parent.append(draggable);
  1754. }
  1755. });
  1756. droppable.removeEnd();
  1757. droppable.addEnd(draggable);
  1758. self.rebuild();
  1759. }
  1760. // Prevent bubbling events
  1761. return false;
  1762. });
  1763. // Drop on action
  1764. self.el.on('drop', '.node-action', function(e, ui) {
  1765. // draggable should be a node.
  1766. // droppable should be a node.
  1767. var draggable = ko.contextFor(ui.draggable[0]).$data;
  1768. var droppable = ko.contextFor(this).$data;
  1769. // Create a fork and join programatically.
  1770. var newParents = droppable.findParents();
  1771. // skip forking beneathe a decision node
  1772. if (droppable.id() != draggable.id() && newParents.length == 1 && draggable.findParents().length == 1) {
  1773. var ForkModel = NodeModelChooser('fork');
  1774. var JoinModel = NodeModelChooser('join');
  1775. var fork = new ForkModel({
  1776. id: IdGeneratorTable['fork'].nextId(),
  1777. description: "",
  1778. workflow: self.id,
  1779. node_type: "fork",
  1780. child_links: []
  1781. });
  1782. var forkNode = new ForkNode(self, fork, self.registry);
  1783. var join = new JoinModel({
  1784. id: IdGeneratorTable['join'].nextId(),
  1785. description: "",
  1786. workflow: self.id,
  1787. node_type: "join",
  1788. child_links: []
  1789. });
  1790. var joinNode = new Node(self, join, self.registry);
  1791. self.registry.add(forkNode.id(), forkNode);
  1792. self.registry.add(joinNode.id(), joinNode);
  1793. forkNode.addChild(joinNode);
  1794. // Handles fork creation.
  1795. $.each(newParents, function(index, parent) {
  1796. parent.replaceChild(droppable, forkNode);
  1797. });
  1798. draggable.detach();
  1799. forkNode.append(draggable);
  1800. forkNode.append(droppable);
  1801. self.rebuild();
  1802. }
  1803. // Prevent bubbling events.
  1804. return false;
  1805. });
  1806. }
  1807. });
  1808. return module;
  1809. };
  1810. var Workflow = WorkflowModule($, nodeModelChooser, Node, ForkNode, DecisionNode, IdGeneratorTable);