Statistics.js 19 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

define(['require',
    'backbone',
    'hbs!tmpl/site/Statistics_tmpl',
    'hbs!tmpl/site/Statistics_Notification_table_tmpl',
    'hbs!tmpl/site/Statistics_Topic_Offset_table_tmpl',
    'hbs!tmpl/site/entity_tmpl',
    'modules/Modal',
    'models/VCommon',
    'utils/UrlLinks',
    'collection/VTagList',
    'utils/CommonViewFunction',
    'utils/Enums',
    'moment',
    'utils/Utils',
33
    'utils/Globals',
34
    'moment-timezone'
35
], function(require, Backbone, StatTmpl, StatsNotiTable, TopicOffsetTable, EntityTable, Modal, VCommon, UrlLinks, VTagList, CommonViewFunction, Enums, moment, Utils, Globals) {
36 37 38 39 40 41 42 43 44 45 46
    'use strict';

    var StatisticsView = Backbone.Marionette.LayoutView.extend(
        /** @lends AboutAtlasView */
        {
            template: StatTmpl,

            /** Layout sub regions */
            regions: {},
            /** ui selector cache */
            ui: {
47 48
                entity: "[data-id='entity']",
                classification: "[data-id='classification']",
49 50 51 52 53
                serverCard: "[data-id='server-card']",
                connectionCard: "[data-id='connection-card']",
                notificationCard: "[data-id='notification-card']",
                statsNotificationTable: "[data-id='stats-notification-table']",
                entityCard: "[data-id='entity-card']",
54
                classificationCard: "[data-id='classification-card']",
55 56 57 58 59
                offsetCard: "[data-id='offset-card']",
                osCard: "[data-id='os-card']",
                runtimeCard: "[data-id='runtime-card']",
                memoryCard: "[data-id='memory-card']",
                memoryPoolUsage: "[data-id='memory-pool-usage-card']"
60 61 62 63 64 65 66 67 68 69
            },
            /** ui events hash */
            events: function() {},
            /**
             * intialize a new AboutAtlasView Layout
             * @constructs
             */
            initialize: function(options) {
                _.extend(this, options);
                var that = this;
70
                this.DATA_MAX_LENGTH = 25;
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
                var modal = new Modal({
                    title: 'Statistics',
                    content: this,
                    okCloses: true,
                    okText: "Close",
                    showFooter: true,
                    allowCancel: false,
                    width: "60%",
                    headerButtons: [{
                        title: "Refresh Data",
                        btnClass: "fa fa-refresh",
                        onClick: function() {
                            modal.$el.find('.header-button .fa-refresh').tooltip('hide').prop('disabled', true).addClass('fa-spin');
                            that.fetchMetricData({ update: true });
                        }
                    }]
87
                });
88 89 90 91
                modal.on('closeModal', function() {
                    modal.trigger('cancel');
                });
                this.modal = modal;
92
                modal.open();
93
            },
94 95
            bindEvents: function() {
                var that = this;
96 97 98 99 100
                if (this.modal) {
                    this.$el.on('click', '.linkClicked', function() {
                        that.modal.close();
                    })
                }
101
            },
102 103 104 105 106 107 108
            fetchMetricData: function(options) {
                var that = this;
                this.metricCollection.fetch({
                    success: function(data) {
                        var data = _.first(data.toJSON());
                        that.renderStats({ valueObject: data.general.stats, dataObject: data.general });
                        that.renderEntities({ data: data });
109
                        that.renderSystemDeatils({ data: data });
110
                        that.renderClassifications({ data: data });
111 112 113 114 115 116 117 118 119 120 121 122
                        that.$('.statsContainer,.statsNotificationContainer').removeClass('hide');
                        that.$('.statsLoader,.statsNotificationLoader').removeClass('show');
                        if (options && options.update) {
                            that.modal.$el.find('.header-button .fa-refresh').prop('disabled', false).removeClass('fa-spin');
                            Utils.notifySuccess({
                                content: "Metric data is refreshed"
                            })
                        }
                    }
                });
            },
            onRender: function() {
123
                this.bindEvents();
124 125
                this.fetchMetricData();
            },
126 127 128 129 130
            closePanel: function(options) {
                var el = options.el;
                el.find(">.panel-heading").attr("aria-expanded", "false");
                el.find(">.panel-collapse.collapse").removeClass("in");
            },
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
            genrateStatusData: function(stateObject) {
                var that = this,
                    stats = {};
                _.each(stateObject, function(val, key) {
                    var keys = key.split(":"),
                        key = keys[0],
                        subKey = keys[1];
                    if (stats[key]) {
                        stats[key][subKey] = val;
                    } else {
                        stats[key] = {};
                        stats[key][subKey] = val;
                    }
                });
                return stats;
            },
147 148 149
            createTable: function(obj) {
                var that = this,
                    tableBody = '',
150
                    type = obj.type,
151 152
                    data = obj.data;
                _.each(data, function(value, key, list) {
153
                    var newValue = that.getValue({
154
                        "value": value
155 156 157 158 159
                    });
                    if (type === "classification") {
                        newValue = '<a title="Search for entities associated with \'' + key + '\'" class="linkClicked" href="#!/search/searchResult?searchType=basic&tag=' + key + '">' + newValue + '<a>';
                    }
                    tableBody += '<tr><td>' + key + '</td><td class="">' + newValue + '</td></tr>';
160 161 162 163 164 165 166 167 168 169
                });
                return tableBody;

            },
            renderClassifications: function(options) {
                var that = this,
                    data = options.data,
                    classificationData = data.tag || {},
                    tagEntitiesData = classificationData ? classificationData.tagEntities || {} : {},
                    tagsCount = 0,
170 171 172
                    newTagEntitiesData = {},
                    tagEntitiesKeys = _.keys(tagEntitiesData);
                _.each(_.sortBy(tagEntitiesKeys, function(o) {
173 174 175 176 177 178 179 180 181 182 183
                    return o.toLocaleLowerCase();
                }), function(key) {
                    var val = tagEntitiesData[key];
                    newTagEntitiesData[key] = val;
                    tagsCount += val;
                });
                tagEntitiesData = newTagEntitiesData;

                if (!_.isEmpty(tagEntitiesData)) {
                    this.ui.classificationCard.html(
                        that.createTable({
184 185
                            "data": tagEntitiesData,
                            "type": "classification"
186 187
                        })
                    );
188 189 190 191 192 193
                    this.ui.classification.find(".count").html("&nbsp;(" + _.numberFormatWithComa(tagsCount) + ")");
                    if (tagEntitiesKeys.length > this.DATA_MAX_LENGTH) {
                        this.closePanel({
                            el: this.ui.classification
                        })
                    }
194 195
                }
            },
196 197 198 199 200 201
            renderEntities: function(options) {
                var that = this,
                    data = options.data,
                    entityData = data.entity,
                    activeEntities = entityData.entityActive || {},
                    deletedEntities = entityData.entityDeleted || {},
202
                    shellEntities = entityData.entityShell || {},
203 204 205
                    stats = {},
                    activeEntityCount = 0,
                    deletedEntityCount = 0,
206
                    shellEntityCount = 0,
207 208 209 210 211 212 213
                    createEntityData = function(opt) {
                        var entityData = opt.entityData,
                            type = opt.type;
                        _.each(entityData, function(val, key) {
                            var intVal = _.isUndefined(val) ? 0 : val;
                            if (type == "active") {
                                activeEntityCount += intVal;
214
                            }
215
                            if (type == "deleted") {
216
                                deletedEntityCount += intVal;
217 218
                            }
                            if (type == "shell") {
219
                                shellEntityCount += intVal
220 221 222 223 224 225 226 227 228 229
                            }
                            intVal = _.numberFormatWithComa(intVal)
                            if (stats[key]) {
                                stats[key][type] = intVal;
                            } else {
                                stats[key] = {};
                                stats[key][type] = intVal;
                            }
                        })
                    };
230

231 232 233 234 235 236 237 238
                createEntityData({
                    "entityData": activeEntities,
                    "type": "active"
                })
                createEntityData({
                    "entityData": deletedEntities,
                    "type": "deleted"
                });
239 240 241 242
                createEntityData({
                    "entityData": shellEntities,
                    "type": "shell"
                });
243
                if (!_.isEmpty(stats)) {
244 245
                    var statsKeys = _.keys(stats);
                    this.ui.entityCard.html(
246
                        EntityTable({
247
                            "data": _.pick(stats, _.sortBy(statsKeys, function(o) {
248 249
                                return o.toLocaleLowerCase();
                            })),
250 251
                        })
                    );
252 253 254 255 256 257 258 259 260
                    this.$('[data-id="activeEntity"]').html("&nbsp;(" + _.numberFormatWithComa(activeEntityCount) + ")");
                    this.$('[data-id="deletedEntity"]').html("&nbsp;(" + _.numberFormatWithComa(deletedEntityCount) + ")");
                    this.$('[data-id="shellEntity"]').html("&nbsp;(" + _.numberFormatWithComa(shellEntityCount) + ")");
                    this.ui.entity.find(".count").html("&nbsp;(" + _.numberFormatWithComa(data.general.entityCount) + ")");
                    if (statsKeys.length > this.DATA_MAX_LENGTH) {
                        this.closePanel({
                            el: this.ui.entity
                        })
                    }
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
                }
            },
            renderStats: function(options) {
                var that = this,
                    data = this.genrateStatusData(options.valueObject),
                    generalData = options.dataObject,
                    createTable = function(obj) {
                        var tableBody = '',
                            enums = obj.enums,
                            data = obj.data;
                        _.each(data, function(value, key, list) {
                            tableBody += '<tr><td>' + key + '</td><td class="">' + that.getValue({
                                "value": value,
                                "type": enums[key]
                            }) + '</td></tr>';
                        });
                        return tableBody;
                    };
                if (data.Notification) {
                    var tableCol = [{
                                label: "Total <br> (from " + (that.getValue({
                                    "value": data.Server["startTimeStamp"],
                                    "type": Enums.stats.Server["startTimeStamp"],
                                })) + ")",
                                key: "total"
                            },
                            {
                                label: "Current Hour <br> (from " + (that.getValue({
                                    "value": data.Notification["currentHourStartTime"],
                                    "type": Enums.stats.Notification["currentHourStartTime"],
                                })) + ")",
                                key: "currentHour"
                            },
                            { label: "Previous Hour", key: "previousHour" },
                            {
                                label: "Current Day <br> (from " + (that.getValue({
                                    "value": data.Notification["currentDayStartTime"],
                                    "type": Enums.stats.Notification["currentDayStartTime"],
                                })) + ")",
                                key: "currentDay"
                            },
                            { label: "Previous Day", key: "previousDay" }
                        ],
                        tableHeader = ["count", "AvgTime", "EntityCreates", "EntityUpdates", "EntityDeletes", "Failed"];
                    that.ui.notificationCard.html(
                        StatsNotiTable({
                            "enums": Enums.stats.Notification,
                            "data": data.Notification,
                            "tableHeader": tableHeader,
                            "tableCol": tableCol,
                            "getTmplValue": function(argument, args) {
                                var pickValueFrom = argument.key.concat(args);
                                if (argument.key == "total" && args == "EntityCreates") {
                                    pickValueFrom = "totalCreates";
                                } else if (argument.key == "total" && args == "EntityUpdates") {
                                    pickValueFrom = "totalUpdates";
                                } else if (argument.key == "total" && args == "EntityDeletes") {
                                    pickValueFrom = "totalDeletes";
                                } else if (args == "count") {
                                    pickValueFrom = argument.key;
                                }
                                var returnVal = data.Notification[pickValueFrom];
                                return returnVal ? _.numberFormatWithComa(returnVal) : 0;
                            }
                        })
                    );

                    var offsetTableColumn = function(obj) {
                        var returnObj = []
                        _.each(obj, function(value, key) {
                            returnObj.push({ "label": key, "dataValue": value });
                        });
                        return returnObj
                    }

                    that.ui.offsetCard.html(
                        TopicOffsetTable({
                            data: data.Notification.topicDetails,
                            tableHeader: ["offsetStart", "offsetCurrent", "processedMessageCount", "failedMessageCount", "lastMessageProcessedTime"],
                            tableCol: offsetTableColumn(data.Notification.topicDetails),
                            getTmplValue: function(argument, args) {
                                var returnVal = data.Notification.topicDetails[argument.label][args];
                                return returnVal ? that.getValue({ value: returnVal, type: Enums.stats.Notification[args] }) : 0;
                            }
                        })
                    )
                }

                if (data.Server) {
                    that.ui.serverCard.html(
                        createTable({
                            "enums": _.extend(Enums.stats.Server, Enums.stats.ConnectionStatus, Enums.stats.generalData),
                            "data": _.extend(
                                _.pick(data.Server, 'startTimeStamp', 'activeTimeStamp', 'upTime', 'statusBackendStore', 'statusIndexStore'),
                                _.pick(generalData, 'collectionTime'))
                        })
                    );
                }
            },
360 361 362 363 364 365
            renderSystemDeatils: function(options) {
                var that = this,
                    data = options.data,
                    systemData = data.system,
                    systemOS = systemData.os || {},
                    systemRuntimeData = systemData.runtime || {},
366
                    systemMemoryData = systemData.memory || {};
367 368
                if (!_.isEmpty(systemOS)) {
                    that.ui.osCard.html(
369
                        that.createTable({
370 371 372 373 374 375 376 377 378
                            "data": systemOS
                        })
                    );
                }
                if (!_.isEmpty(systemRuntimeData)) {
                    _.each(systemRuntimeData, function(val, key) {
                        var space
                    })
                    that.ui.runtimeCard.html(
379
                        that.createTable({
380 381 382 383 384 385 386
                            "data": systemRuntimeData
                        })
                    );
                }
                if (!_.isEmpty(systemMemoryData)) {
                    var memoryTable = CommonViewFunction.propertyTable({
                        scope: this,
387
                        formatStringVal: true,
388 389
                        valueObject: systemMemoryData,
                        numberFormat: _.numberFormatWithBytes
390 391 392 393 394
                    });
                    that.ui.memoryCard.html(
                        memoryTable);
                }
            },
395 396 397 398 399 400
            getValue: function(options) {
                var value = options.value,
                    type = options.type;
                if (type == 'time') {
                    return Utils.millisecondsToTime(value);
                } else if (type == 'day') {
401
                    return Utils.formatDate({ date: value, dateFormat: Globals.meridiemFormat })
402 403 404 405 406 407 408 409 410 411 412 413 414
                } else if (type == 'number') {
                    return _.numberFormatWithComa(value);
                } else if (type == 'millisecond') {
                    return _.numberFormatWithComa(value) + " millisecond/s";
                } else if (type == "status-html") {
                    return '<span class="connection-status ' + value + '"></span>';
                } else {
                    return value;
                }
            }
        });
    return StatisticsView;
});