PageRenderTime 51ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins/bigdesk/_site/js/store/BigdeskStore.js

https://gitlab.com/zouxc/elasticsearch-cn-out-of-box
JavaScript | 373 lines | 265 code | 34 blank | 74 comment | 42 complexity | e82f39775213d04dd850ee5e063f73a1 MD5 | raw file
  1. /*
  2. Copyright 2011-2014 Lukas Vlcek
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. /*
  14. {
  15. cluster: {
  16. cluster_name: {
  17. connectionVerified: bool,
  18. intervals: {_all_active_intervals_},
  19. timeouts: {_all_active_timeouts_},
  20. storeSize: int,
  21. health: {},
  22. nodesStats: [
  23. timestamp_x: {
  24. [nodeStats, nodeStats, ...]
  25. },
  26. timestamp_y: {[...]},
  27. timestamp_z: {[...]},
  28. ...
  29. ],
  30. nodesState: [
  31. {node_with_id},
  32. {node_with_id},
  33. ...
  34. ],
  35. nodeInfo: {}, //relevant to selected node
  36. clusterState: [
  37. clusterStateTimestamp: {},
  38. ...
  39. ],
  40. indicesStatus: [
  41. indicesStatusTimestamp: {},
  42. ...
  43. ]
  44. }
  45. }
  46. }
  47. */
  48. var Cluster = Backbone.Model.extend({
  49. defaults: {
  50. id: "not_set_yet",
  51. connectionVerified: false,
  52. health: undefined,
  53. nodesStats: undefined,
  54. nodesState: undefined,
  55. nodeInfo: undefined,
  56. clusterState: undefined,
  57. indicesStatus: undefined,
  58. storeSize: 60000, // 1min
  59. intervals: {},
  60. timeouts: {},
  61. dispatcher: undefined
  62. },
  63. // id: "cluster_name"
  64. // baseUrl: "complete URL for REST API including port number"
  65. // refreshInterval: _some_number_ [optional, defaults to 2000ms]
  66. // dispatcher: function [optional].
  67. initialize: function(attrs){
  68. var _model = this;
  69. var _conn = _model.get("connectionVerified");
  70. if (_conn == false) {
  71. // ensure default dispatcher (in case user explicitly provided "undefined" value instead of function)
  72. if (this.get("dispatcher") == undefined /*|| typeof this.get("dispatcher") != "function"*/) {
  73. console.log("using default dispatcher");
  74. var _dispatcher = _.clone(Backbone.Events);
  75. _dispatcher.on("onAjaxResponse", function(clusterName, restApiName, response) {
  76. console.log("["+clusterName+"] ["+restApiName+"]", response)
  77. });
  78. this.set({dispatcher: _dispatcher});
  79. }
  80. var connection = {
  81. baseUrl: attrs.baseUrl,
  82. refreshInterval: attrs.refreshInterval || 2000
  83. };
  84. var hello = new Hello({},connection);
  85. hello.fetch({
  86. success: function(model, response){
  87. var version = hello.get("version");
  88. if (version && version.number) {
  89. version = version.number;
  90. var _vArray = version.split(".");
  91. if (_vArray.length > 2 && _model.checkVersion(_vArray)) {
  92. _model.versionVerified(version);
  93. _model.initCluster(connection);
  94. } else {
  95. _model.yellAboutVersion(version);
  96. }
  97. } else {
  98. _model.yellAboutVersion("n/a");
  99. }
  100. },
  101. error: function(model, response) {
  102. console.log("[Error] something wrong happened...", model, response);
  103. }
  104. });
  105. }
  106. },
  107. // When creating a new cluster, client has to provide both REST URL endpoint and cluster name.
  108. // The idea is that the cluster name is obtained by client upfront using cluster health API for example.
  109. validate: function(attrs){
  110. // this must be constructor call
  111. if (this.get("connectionVerified") == undefined) {
  112. if (!attrs.id || !attrs.baseUrl) {
  113. return "Both cluster name and URL must be provided.\n" +
  114. "Example: { " +
  115. "id: \"_cluster_name_\", " +
  116. "baseUrl: \"_ES_REST_end_point_\" " +
  117. "}";
  118. }
  119. if (attrs.dispatcher != undefined) {
  120. if (typeof attrs.dispatcher != "function") {
  121. return "dispatcher must be a function.";
  122. }
  123. }
  124. }
  125. },
  126. // returns false or true depending on given version numbers
  127. checkVersion: function(parsedArray) {
  128. var major = parsedArray[0];
  129. var minor = parsedArray[1];
  130. var maintenance = parsedArray[2];
  131. var build = undefined;
  132. if (parsedArray.length > 3) {
  133. build = parsedArray[3]; // Betax, RCx, GAx ...
  134. }
  135. return (major == 1 && minor >= 0 && maintenance >= 0 && (build != 'Beta1' || build != 'Beta2'));
  136. },
  137. versionVerified: function(version) {
  138. console.log("Check ES node version: " + version + " [ok]");
  139. },
  140. yellAboutVersion: function(version) {
  141. var message =
  142. "*********************************\n" +
  143. "Bigdesk may not work correctly!\n" +
  144. "Found ES node version: " + version + "\n" +
  145. "Requires ES node version: >= 1.0.0.RC1\n" +
  146. "*********************************";
  147. console.log(message);
  148. if (alert) { alert(message); }
  149. },
  150. // connection.baseUrl
  151. // connection.refreshInterval
  152. initCluster: function(connection) {
  153. var _model = this;
  154. // connection has been already verified
  155. _model.set({connectionVerified: true});
  156. _model.set({ health: new ClusterHealth({}, connection) });
  157. _model.set({ nodesStats: new NodesStats([], connection) });
  158. _model.set({ nodesState: new NodesState([], connection) });
  159. _model.set({ nodeInfo: new NodeInfo({}, connection) });
  160. _model.set({ clusterState: new ClusterState([], connection) });
  161. _model.set({ indicesStatus: new IndicesStatus([], connection) });
  162. this.startFetch(connection.refreshInterval);
  163. },
  164. clearTimeouts: function() {
  165. var _cluster = this;
  166. var timeouts = _cluster.get("timeouts");
  167. _.each(timeouts, function(num, key){
  168. _cluster.clearTimeout(key);
  169. });
  170. },
  171. clearTimeout: function(timeoutId) {
  172. var timeouts = this.get("timeouts");
  173. if (timeouts && timeouts[timeoutId]) {
  174. window.clearTimeout(timeouts[timeoutId]);
  175. delete timeouts[timeoutId];
  176. this.set({timeouts: timeouts});
  177. }
  178. },
  179. clearIntervals: function() {
  180. var _cluster = this;
  181. var intervals = this.get("intervals");
  182. _.each(intervals, function(num, key){
  183. _cluster.clearInterval(key);
  184. });
  185. },
  186. clearInterval: function(intervalId) {
  187. // console.log("stop interval " + intervalId);
  188. var intervals = this.get("intervals");
  189. if (intervals && intervals[intervalId]) {
  190. window.clearInterval(intervals[intervalId]);
  191. delete intervals[intervalId];
  192. this.set({intervals: intervals});
  193. }
  194. },
  195. startTimeout: function(timeoutId, functionCall, interval) {
  196. var _model = this;
  197. var timeouts = _model.get("timeouts");
  198. if (timeouts) {
  199. if (timeouts[timeoutId]) {
  200. console.log("[WARN] clearing and replacing existing timeout");
  201. _model.clearTimeout(timeoutId);
  202. }
  203. var timeoutFn = function() {
  204. functionCall();
  205. timeouts[timeoutId] = window.setTimeout(timeoutFn, interval);
  206. _model.set({timeouts: timeouts});
  207. };
  208. timeoutFn();
  209. }
  210. },
  211. startInterval: function(intervalId, functionCall, interval) {
  212. var _model = this;
  213. var intervals = this.get("intervals");
  214. if (intervals) {
  215. if (intervals[intervalId]) {
  216. console.log("[WARN] clearing and replacing existing interval");
  217. _model.clearInterval(intervalId);
  218. }
  219. intervals[intervalId] = window.setInterval(functionCall, interval);
  220. this.set({intervals: intervals});
  221. // fire callback right now
  222. functionCall();
  223. }
  224. },
  225. // start fetching bigdesk models and collections
  226. // params:
  227. // refreshInterval
  228. // baseUrl [optional] can override baseUrl that was passed into Cluster constructor
  229. startFetch: function(refreshInterval, baseUrl) {
  230. var _cluster = this;
  231. var _dispatcher = _cluster.get("dispatcher");
  232. var _clusterName = _cluster.get("id");
  233. if (baseUrl && typeof baseUrl == "string") {
  234. _cluster.get("health").setBaseUrl(baseUrl);
  235. _cluster.get("nodesStats").setBaseUrl(baseUrl);
  236. _cluster.get("nodesState").setBaseUrl(baseUrl);
  237. _cluster.get("nodeInfo").setBaseUrl(baseUrl);
  238. _cluster.get("clusterState").setBaseUrl(baseUrl);
  239. _cluster.get("indicesStatus").setBaseUrl(baseUrl);
  240. }
  241. var healthRefreshFunction = function(){
  242. _cluster.get("health").fetch({
  243. success: function(model, response){
  244. _dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > Health", response);
  245. }
  246. });
  247. };
  248. var nodesStatsRefreshFunction = function(){
  249. _cluster.get("nodesStats").fetch({
  250. add: true,
  251. storeSize: _cluster.get("storeSize"),
  252. now: new Date().getTime(),
  253. silent: true,
  254. success: function(model, response){
  255. _dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > NodesStats", response);
  256. }
  257. });
  258. };
  259. var nodesStateRefreshFunction = function(){
  260. _cluster.get("nodesState").fetch({
  261. add: true,
  262. silent: true,
  263. success: function(model, response){
  264. _dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > NodesState", response);
  265. }
  266. });
  267. };
  268. var clusterStateRefreshFunction = function(){
  269. _cluster.get("clusterState").fetch({
  270. add: true,
  271. storeSize: _cluster.get("storeSize"),
  272. now: new Date().getTime(),
  273. silent: true,
  274. success: function(model, response){
  275. _dispatcher.trigger("onAjaxResponse", _clusterName, "cluster > State", response);
  276. _dispatcher.trigger("newClusterState");
  277. }
  278. });
  279. };
  280. var indicesStatusRefreshFunction = function(){
  281. _cluster.get("indicesStatus").fetch({
  282. add: true,
  283. storeSize: _cluster.get("storeSize"),
  284. now: new Date().getTime(),
  285. silent: true,
  286. success: function(model, response){
  287. _dispatcher.trigger("onAjaxResponse", _clusterName, "indices > Status", response);
  288. _dispatcher.trigger("newIndicesStatus");
  289. }
  290. });
  291. };
  292. this.clearInterval("nodesStateInterval");
  293. this.clearInterval("nodesStatsInterval");
  294. this.clearInterval("healthInterval");
  295. this.clearTimeout("clusterStateInterval");
  296. this.clearTimeout("indicesStatusInterval");
  297. this.startInterval("nodesStateInterval", nodesStateRefreshFunction, refreshInterval);
  298. this.startInterval("nodesStatsInterval", nodesStatsRefreshFunction, refreshInterval);
  299. this.startInterval("healthInterval", healthRefreshFunction, refreshInterval);
  300. this.startTimeout("clusterStateInterval", clusterStateRefreshFunction, refreshInterval);
  301. this.startTimeout("indicesStatusInterval", indicesStatusRefreshFunction, refreshInterval);
  302. },
  303. // set storeSize value of the cluster
  304. setStoreSize: function(storeSize) {
  305. var _cluster = this;
  306. _cluster.set({storeSize: storeSize});
  307. },
  308. // return master node id if available, otherwise return empty string
  309. getMasterNodeId: function() {
  310. var _cluster = this;
  311. return _cluster.get("nodesState").getMasterNodeId();
  312. }
  313. });
  314. var ClusterCollection = Backbone.Collection.extend({
  315. model: Cluster
  316. });
  317. var BigdeskStore = Backbone.Model.extend({
  318. defaults: {
  319. cluster: new ClusterCollection()
  320. },
  321. // Returns an instance of a Cluster model with given name (id)
  322. // or <code>undefined</code> if no instance if found.
  323. getCluster: function(clusterName) {
  324. return this.get("cluster").get(clusterName);
  325. },
  326. // Add a new cluster into store. Parameter is an instance of a Cluster model.
  327. // Throws error if there already is a cluster with the same id.
  328. addCluster: function(clusterModel) {
  329. var _c = this.get("cluster");
  330. if (_c.get(clusterModel.get("id")) == undefined) {
  331. _c.add(clusterModel)
  332. } else {
  333. throw "Cluster already exists.";
  334. }
  335. }
  336. });