spark.vm.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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. var Result = function (snippet, result) {
  17. var self = this;
  18. self.id = ko.observable(typeof result.id != "undefined" && result.id != null ? result.id : UUID());
  19. self.type = ko.observable(typeof result.type != "undefined" && result.type != null ? result.type : 'table');
  20. self.handle = ko.observable({});
  21. self.meta = ko.observableArray(typeof result.meta != "undefined" && result.meta != null ? result.meta : []);
  22. self.meta.extend({ rateLimit: 50 });
  23. self.cleanedMeta = ko.computed(function(){
  24. return ko.utils.arrayFilter(self.meta(), function(item) {
  25. return item.name != ''
  26. });
  27. });
  28. self.data = ko.observableArray(typeof result.data != "undefined" && result.data != null ? result.data : []);
  29. self.data.extend({ rateLimit: 50 });
  30. self.logs = ko.observable('');
  31. self.errors = ko.observable('');
  32. if (typeof result.handle != "undefined" && result.handle != null) {
  33. $.each(result.handle, function(key, val) {
  34. self.handle()[key] = val;
  35. });
  36. }
  37. self.clear = function() {
  38. $.each(self.handle, function(key, val) {
  39. delete self.handle()[key];
  40. });
  41. self.meta.removeAll();
  42. self.data.removeAll();
  43. self.logs('');
  44. self.errors('');
  45. };
  46. }
  47. var TYPE_EDITOR_MAP = {
  48. 'hive': 'text/x-hiveql',
  49. 'impala': 'text/x-impalaql',
  50. 'python': 'text/x-python',
  51. 'scala': 'text/x-scala',
  52. 'pig': 'text/x-pig'
  53. }
  54. var Snippet = function (notebook, snippet) {
  55. var self = this;
  56. self.id = ko.observable(typeof snippet.id != "undefined" && snippet.id != null ? snippet.id : UUID());
  57. self.name = ko.observable(typeof snippet.name != "undefined" && snippet.name != null ? snippet.name : '');
  58. self.type = ko.observable(typeof snippet.type != "undefined" && snippet.type != null ? snippet.type : "hive");
  59. self.editorMode = ko.observable(TYPE_EDITOR_MAP[self.type()]);
  60. self.statement_raw = ko.observable(typeof snippet.statement_raw != "undefined" && snippet.statement_raw != null ? snippet.statement_raw : '');
  61. self.status = ko.observable(typeof snippet.status != "undefined" && snippet.status != null ? snippet.status : 'loading');
  62. self.settings = ko.mapping.fromJS(typeof snippet.settings != "undefined" && snippet.settings != null ? snippet.settings : {});
  63. self.variables = ko.observableArray([]);
  64. self.variableNames = ko.computed(function() {
  65. var matches = [];
  66. var myRegexp = /(?:[^\\]\$)([^\d'" ]\w*)/g;
  67. var match = myRegexp.exec(self.statement_raw());
  68. while (match != null) {
  69. matches.push(match[1]);
  70. match = myRegexp.exec(self.statement());
  71. }
  72. return matches;
  73. });
  74. self.variableNames.subscribe(function(newVal){
  75. var toDelete = [];
  76. var toAdd = [];
  77. $.each(newVal, function(key, name) {
  78. var match = ko.utils.arrayFirst(self.variables(), function(_var) {
  79. return _var.name() == name;
  80. });
  81. if (! match) {
  82. toAdd.push(name);
  83. }
  84. });
  85. $.each(self.variables(), function(key, _var) {
  86. var match = ko.utils.arrayFirst(newVal, function(name) {
  87. return _var.name() == name;
  88. });
  89. if (! match) {
  90. toDelete.push(_var);
  91. }
  92. });
  93. $.each(toDelete, function(index, item) {
  94. self.variables.remove(item);
  95. });
  96. $.each(toAdd, function(index, item) {
  97. self.variables.push(ko.mapping.fromJS({'name': item, 'value': ''}));
  98. });
  99. self.variables.sort(function(left, right) {
  100. var leftIndex = newVal.indexOf(left.name());
  101. var rightIndex = newVal.indexOf(right.name());
  102. return leftIndex == rightIndex ? 0 : (leftIndex < rightIndex ? -1 : 1);
  103. });
  104. });
  105. self.statement = ko.computed(function() {
  106. var statement = self.statement_raw();
  107. $.each(self.variables(), function(index, variable) {
  108. statement = statement.replace(RegExp("([^\\\\])\\$" + variable.name(), "g"), "$1" + variable.value());
  109. });
  110. return statement;
  111. });
  112. self.result = new Result(snippet, snippet.result);
  113. self.showGrid = ko.observable(typeof snippet.showGrid != "undefined" && snippet.showGrid != null ? snippet.showGrid : true);
  114. self.showChart = ko.observable(typeof snippet.showChart != "undefined" && snippet.showChart != null ? snippet.showChart : false);
  115. self.showLogs = ko.observable(typeof snippet.showLogs != "undefined" && snippet.showLogs != null ? snippet.showLogs : false);
  116. self.showDownload = ko.observable(typeof snippet.showDownload != "undefined" && snippet.showDownload != null ? snippet.showDownload : false);
  117. self.progress = ko.observable(typeof snippet.progress != "undefined" && snippet.progress != null ? snippet.progress : 0);
  118. self.progress.subscribe(function (val){
  119. $(document).trigger("progress", {data: val, snippet: self});
  120. });
  121. self.showGrid.subscribe(function (val){
  122. if (val){
  123. self.showChart(false);
  124. }
  125. });
  126. self.showChart.subscribe(function (val){
  127. if (val){
  128. self.showGrid(false);
  129. }
  130. });
  131. self.showLogs.subscribe(function (val){
  132. if (val){
  133. self.getLogs();
  134. }
  135. });
  136. self.size = ko.observable(typeof snippet.size != "undefined" && snippet.size != null ? snippet.size : 12).extend({ numeric: 0 });
  137. self.offset = ko.observable(typeof snippet.offset != "undefined" && snippet.offset != null ? snippet.offset : 0).extend({ numeric: 0 });
  138. self.isLoading = ko.computed(function(){
  139. return self.status() == "loading";
  140. });
  141. self.klass = ko.computed(function () {
  142. return "snippet card card-widget";
  143. });
  144. self.editorKlass = ko.computed(function(){
  145. return "editor span" + self.size() + (self.offset() * 1 > 0 ? " offset" + self.offset() : "");
  146. });
  147. self.resultsKlass = ko.computed(function(){
  148. return "results " + self.type();
  149. });
  150. self.chartType = ko.observable(typeof snippet.chartType != "undefined" && snippet.chartType != null ? snippet.chartType : '');
  151. self.chartSorting = ko.observable(typeof snippet.chartSorting != "undefined" && snippet.chartSorting != null ? snippet.chartSorting : "none");
  152. self.chartX = ko.observable(typeof snippet.chartX != "undefined" && snippet.chartX != null ? snippet.chartX : null);
  153. self.chartYSingle = ko.observable(typeof snippet.chartYSingle != "undefined" && snippet.chartYSingle != null ? snippet.chartYSingle : null);
  154. self.chartYMulti = ko.observableArray(typeof snippet.chartYMulti != "undefined" && snippet.chartYMulti != null ? snippet.chartYMulti : []);
  155. self.chartData = ko.observableArray(typeof snippet.chartData != "undefined" && snippet.chartData != null ? snippet.chartData : []);
  156. self.chartMapLabel = ko.observable(typeof snippet.chartMapLabel != "undefined" && snippet.chartMapLabel != null ? snippet.chartMapLabel : null);
  157. self.chartType.subscribe(function(){
  158. $(document).trigger("forceChartDraw", self);
  159. });
  160. self.expand = function () {
  161. self.size(self.size() + 1);
  162. $("#snippet_" + self.id()).trigger("resize");
  163. }
  164. self.compress = function () {
  165. self.size(self.size() - 1);
  166. $("#snippet_" + self.id()).trigger("resize");
  167. }
  168. self.moveLeft = function () {
  169. self.offset(self.offset() - 1);
  170. }
  171. self.moveRight = function () {
  172. self.offset(self.offset() + 1);
  173. }
  174. self.remove = function (notebook, snippet) {
  175. notebook.snippets.remove(snippet);
  176. }
  177. self.checkStatusTimeout = null;
  178. self._ajax_error = function(data) {
  179. if (data.status == -2) {
  180. self.create_session();
  181. }
  182. else if (data.status == -3) {
  183. self.status('expired');
  184. }
  185. else if (data.status == 1) {
  186. self.status('failed');
  187. self.result.errors(data.message);
  188. } else {
  189. $(document).trigger("error", data.message);
  190. self.status('failed');
  191. }
  192. };
  193. self.create_session = function() {
  194. $.post("/spark/api/create_session", {
  195. notebook: ko.mapping.toJSON(notebook),
  196. snippet: ko.mapping.toJSON(self)
  197. }, function (data) {
  198. if (data.status == 0) {
  199. notebook.addSession(ko.mapping.fromJS(data.session));
  200. self.status('ready');
  201. }
  202. else {
  203. $(document).trigger("error", data.message);
  204. }
  205. }).fail(function (xhr, textStatus, errorThrown) {
  206. $(document).trigger("error", xhr.responseText);
  207. });
  208. };
  209. self.execute = function() {
  210. $(document).trigger("executeStarted", self);
  211. $(".jHueNotify").hide();
  212. logGA('/execute/' + self.type());
  213. self.result.clear();
  214. self.progress(0);
  215. self.status('running');
  216. $.post("/spark/api/execute", {
  217. notebook: ko.mapping.toJSON(notebook),
  218. snippet: ko.mapping.toJSON(self)
  219. }, function (data) {
  220. if (data.status == 0) {
  221. $.each(data.handle, function(key, val) {
  222. self.result.handle()[key] = val;
  223. });
  224. self.checkStatus();
  225. } else {
  226. self._ajax_error(data);
  227. }
  228. }).fail(function (xhr, textStatus, errorThrown) {
  229. $(document).trigger("error", xhr.responseText);
  230. self.status('failed');
  231. });
  232. };
  233. self.fetchResult = function(rows, startOver) {
  234. if (typeof startOver == "undefined") {
  235. startOver = true;
  236. }
  237. self.fetchResultData(rows, startOver);
  238. //self.fetchResultMetadata(rows);
  239. };
  240. self.fetchResultData = function(rows, startOver) {
  241. $.post("/spark/api/fetch_result_data", {
  242. notebook: ko.mapping.toJSON(notebook),
  243. snippet: ko.mapping.toJSON(self),
  244. rows: rows,
  245. startOver: startOver
  246. }, function (data) {
  247. if (data.status == 0) {
  248. rows -= data.result.data.length;
  249. if (self.result.meta().length == 0) {
  250. data.result.meta.unshift({type: "INT_TYPE", name: "", comment: null});
  251. self.result.meta(data.result.meta);
  252. }
  253. var _initialIndex = self.result.data().length;
  254. var _tempData = [];
  255. $.each(data.result.data, function (index, row) {
  256. row.unshift(_initialIndex + index);
  257. self.result.data.push(row);
  258. _tempData.push(row);
  259. });
  260. $(document).trigger("renderData", {data: _tempData, snippet: self, initial: _initialIndex == 0});
  261. if (data.result.has_more && rows > 0) {
  262. setTimeout(function () {
  263. self.fetchResultData(rows, false);
  264. }, 500);
  265. }
  266. } else {
  267. self._ajax_error(data);
  268. }
  269. }).fail(function (xhr, textStatus, errorThrown) {
  270. $(document).trigger("error", xhr.responseText);
  271. });
  272. };
  273. self.fetchResultMetadata = function () {
  274. $.post("/spark/api/fetch_result_metadata", {
  275. notebook: ko.mapping.toJSON(notebook),
  276. snippet: ko.mapping.toJSON(self),
  277. }, function (data) {
  278. if (data.status == 0) {
  279. self.result.meta(data.result.meta);
  280. } else {
  281. $(document).trigger("error", data.message);
  282. }
  283. }).fail(function (xhr, textStatus, errorThrown) {
  284. $(document).trigger("error", xhr.responseText);
  285. self.status('failed');
  286. });
  287. };
  288. self.checkStatus = function() {
  289. $.post("/spark/api/check_status", {
  290. notebook: ko.mapping.toJSON(notebook),
  291. snippet: ko.mapping.toJSON(self)
  292. }, function (data) {
  293. if (data.status == 0) {
  294. self.status(data.query_status.status);
  295. if (self.status() == 'running') {
  296. self.checkStatusTimeout = setTimeout(self.checkStatus, 1000);
  297. self.getLogs();
  298. }
  299. else if (self.status() == 'available') {
  300. self.fetchResult(100);
  301. self.progress(100);
  302. }
  303. } else {
  304. self._ajax_error(data);
  305. }
  306. }).fail(function (xhr, textStatus, errorThrown) {
  307. $(document).trigger("error", xhr.responseText);
  308. self.status('failed');
  309. });
  310. };
  311. self.cancel = function() {
  312. if (self.checkStatusTimeout != null) {
  313. clearTimeout(self.checkStatusTimeout);
  314. self.checkStatusTimeout = null;
  315. }
  316. $.post("/spark/api/cancel_statement", {
  317. notebook: ko.mapping.toJSON(notebook),
  318. snippet: ko.mapping.toJSON(self)
  319. }, function (data) {
  320. if (data.status == 0) {
  321. self.status('canceled');
  322. } else {
  323. self._ajax_error(data);
  324. }
  325. }).fail(function (xhr, textStatus, errorThrown) {
  326. $(document).trigger("error", xhr.responseText);
  327. self.status('failed');
  328. });
  329. };
  330. self.getLogs = function() {
  331. $.post("/spark/api/get_logs", {
  332. notebook: ko.mapping.toJSON(notebook),
  333. snippet: ko.mapping.toJSON(self)
  334. }, function (data) {
  335. if (data.status == 0) {
  336. self.result.logs(data.logs); // Way to append?
  337. self.progress(data.progress);
  338. } else {
  339. self._ajax_error(data);
  340. }
  341. }).fail(function (xhr, textStatus, errorThrown) {
  342. $(document).trigger("error", xhr.responseText);
  343. self.status('failed');
  344. });
  345. };
  346. self.init = function() {
  347. if (self.status() == 'running') {
  348. self.checkStatus();
  349. }
  350. if (self.status() != 'loading' && self.status() != 'ready') {
  351. self.getLogs();
  352. }
  353. };
  354. }
  355. var Notebook = function (vm, notebook) {
  356. var self = this;
  357. self.id = ko.observable(typeof notebook.id != "undefined" && notebook.id != null ? notebook.id : null);
  358. self.uuid = ko.observable(typeof notebook.uuid != "undefined" && notebook.uuid != null ? notebook.uuid : UUID());
  359. self.name = ko.observable(typeof notebook.name != "undefined" && notebook.name != null ? notebook.name : 'My Notebook');
  360. self.snippets = ko.observableArray();
  361. self.selectedSnippet = ko.observable('scala');
  362. self.availableSnippets = ko.observableArray(['impala', 'hive', 'scala', 'spark sql', 'python', 'text', 'pig']); // presto, mysql, oracle, sqlite, postgres, phoenix
  363. self.sessions = ko.mapping.fromJS(typeof notebook.sessions != "undefined" && notebook.sessions != null ? notebook.sessions : []);
  364. self.getSession = function(session_type) {
  365. var _s = null;
  366. $.each(self.sessions(), function (index, s) {
  367. if (s.type() == session_type) {
  368. _s = s;
  369. return false;
  370. }
  371. });
  372. return _s;
  373. };
  374. self.addSession = function(session) {
  375. var toRemove = []
  376. $.each(self.sessions(), function (index, s) {
  377. if (s.type() == session.type()) {
  378. toRemove.push(s);
  379. }
  380. });
  381. $.each(toRemove, function (index, s) {
  382. self.sessions.remove(s);
  383. });
  384. self.sessions.push(session);
  385. };
  386. self.addSnippet = function(snippet) {
  387. var _snippet = new Snippet(self, snippet);
  388. self.snippets.push(_snippet);
  389. if (self.getSession(_snippet.type()) == null) {
  390. _snippet.create_session();
  391. }
  392. _snippet.init();
  393. };
  394. self.newSnippet = function() {
  395. var snippet = new Snippet(self, {type: self.selectedSnippet(), result: {}});
  396. self.snippets.push(snippet);
  397. if (self.getSession(self.selectedSnippet()) == null) {
  398. snippet.create_session();
  399. }
  400. };
  401. if (notebook.snippets) {
  402. $.each(notebook.snippets, function(index, snippet) {
  403. self.addSnippet(snippet);
  404. });
  405. }
  406. self.save = function () {
  407. $.post("/spark/api/notebook/save", {
  408. "notebook": ko.mapping.toJSON(self)
  409. }, function (data) {
  410. if (data.status == 0) {
  411. self.id(data.id);
  412. $(document).trigger("info", data.message);
  413. if (window.location.search.indexOf("notebook") == -1) {
  414. window.location.hash = '#notebook=' + data.id;
  415. }
  416. }
  417. else {
  418. $(document).trigger("error", data.message);
  419. }
  420. }).fail(function (xhr, textStatus, errorThrown) {
  421. $(document).trigger("error", xhr.responseText);
  422. });
  423. };
  424. }
  425. function EditorViewModel(notebooks) {
  426. var self = this;
  427. self.notebooks = ko.observableArray();
  428. self.selectedNotebook = ko.observable();
  429. self.isEditing = ko.observable(true);
  430. self.isEditing.subscribe(function(newVal){
  431. $(document).trigger("editingToggled");
  432. });
  433. self.toggleEditing = function () {
  434. self.isEditing(! self.isEditing());
  435. };
  436. self.assistContent = ko.observable();
  437. self.init = function() {
  438. $.each(notebooks, function(index, notebook) {
  439. self.loadNotebook(notebook);
  440. if (self.selectedNotebook() == null){
  441. self.selectedNotebook(self.notebooks()[0]);
  442. }
  443. });
  444. };
  445. self.loadNotebook = function(notebook) {
  446. self.notebooks.push(new Notebook(self, notebook));
  447. };
  448. self.newNotebook = function() {
  449. self.notebooks.push(new Notebook(self, {}));
  450. self.selectedNotebook(self.notebooks()[self.notebooks().length - 1]);
  451. };
  452. self.saveNotebook = function() {
  453. self.selectedNotebook().save();
  454. };
  455. }
  456. function logGA(page) {
  457. if (typeof trackOnGA == 'function') {
  458. trackOnGA('editor/' + page);
  459. }
  460. }