spark.vm.js 16 KB

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