Statistics.js 18.8 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 33 34 35 36 37 38 39 40 41 42 43 44 45
/**
 * 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',
    'moment-timezone'
], function(require, Backbone, StatTmpl, StatsNotiTable, TopicOffsetTable, EntityTable, Modal, VCommon, UrlLinks, VTagList, CommonViewFunction, Enums, moment, Utils) {
    'use strict';

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

            /** Layout sub regions */
            regions: {},
            /** ui selector cache */
            ui: {
46 47
                entity: "[data-id='entity']",
                classification: "[data-id='classification']",
48 49 50 51 52
                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']",
53
                classificationCard: "[data-id='classification-card']",
54 55 56 57 58
                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']"
59 60 61 62 63 64 65 66 67 68
            },
            /** ui events hash */
            events: function() {},
            /**
             * intialize a new AboutAtlasView Layout
             * @constructs
             */
            initialize: function(options) {
                _.extend(this, options);
                var that = this;
69
                this.DATA_MAX_LENGTH = 25;
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
                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 });
                        }
                    }]
                }).open();

                modal.on('closeModal', function() {
                    modal.trigger('cancel');
                });
                this.modal = modal;
            },
93 94 95 96 97 98
            bindEvents: function() {
                var that = this;
                this.$el.on('click', '.linkClicked', function() {
                    that.modal.close();
                })
            },
99 100 101 102 103 104 105
            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 });
106
                        that.renderSystemDeatils({ data: data });
107
                        that.renderClassifications({ data: data });
108 109 110 111 112 113 114 115 116 117 118 119
                        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() {
120
                this.bindEvents();
121 122
                this.fetchMetricData();
            },
123 124 125 126 127
            closePanel: function(options) {
                var el = options.el;
                el.find(">.panel-heading").attr("aria-expanded", "false");
                el.find(">.panel-collapse.collapse").removeClass("in");
            },
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
            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;
            },
144 145 146
            createTable: function(obj) {
                var that = this,
                    tableBody = '',
147
                    type = obj.type,
148 149
                    data = obj.data;
                _.each(data, function(value, key, list) {
150
                    var newValue = that.getValue({
151
                        "value": value
152 153 154 155 156
                    });
                    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>';
157 158 159 160 161 162 163 164 165 166
                });
                return tableBody;

            },
            renderClassifications: function(options) {
                var that = this,
                    data = options.data,
                    classificationData = data.tag || {},
                    tagEntitiesData = classificationData ? classificationData.tagEntities || {} : {},
                    tagsCount = 0,
167 168 169
                    newTagEntitiesData = {},
                    tagEntitiesKeys = _.keys(tagEntitiesData);
                _.each(_.sortBy(tagEntitiesKeys, function(o) {
170 171 172 173 174 175 176 177 178 179 180
                    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({
181 182
                            "data": tagEntitiesData,
                            "type": "classification"
183 184
                        })
                    );
185 186 187 188 189 190
                    this.ui.classification.find(".count").html("&nbsp;(" + _.numberFormatWithComa(tagsCount) + ")");
                    if (tagEntitiesKeys.length > this.DATA_MAX_LENGTH) {
                        this.closePanel({
                            el: this.ui.classification
                        })
                    }
191 192
                }
            },
193 194 195 196 197 198
            renderEntities: function(options) {
                var that = this,
                    data = options.data,
                    entityData = data.entity,
                    activeEntities = entityData.entityActive || {},
                    deletedEntities = entityData.entityDeleted || {},
199
                    shellEntities = entityData.entityShell || {},
200 201 202
                    stats = {},
                    activeEntityCount = 0,
                    deletedEntityCount = 0,
203
                    shellEntityCount = 0,
204 205 206 207 208 209 210
                    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;
211
                            }
212
                            if (type == "deleted") {
213
                                deletedEntityCount += intVal;
214 215
                            }
                            if (type == "shell") {
216
                                shellEntityCount += intVal
217 218 219 220 221 222 223 224 225 226
                            }
                            intVal = _.numberFormatWithComa(intVal)
                            if (stats[key]) {
                                stats[key][type] = intVal;
                            } else {
                                stats[key] = {};
                                stats[key][type] = intVal;
                            }
                        })
                    };
227

228 229 230 231 232 233 234 235
                createEntityData({
                    "entityData": activeEntities,
                    "type": "active"
                })
                createEntityData({
                    "entityData": deletedEntities,
                    "type": "deleted"
                });
236 237 238 239
                createEntityData({
                    "entityData": shellEntities,
                    "type": "shell"
                });
240
                if (!_.isEmpty(stats)) {
241 242
                    var statsKeys = _.keys(stats);
                    this.ui.entityCard.html(
243
                        EntityTable({
244
                            "data": _.pick(stats, _.sortBy(statsKeys, function(o) {
245 246
                                return o.toLocaleLowerCase();
                            })),
247 248
                        })
                    );
249 250 251 252 253 254 255 256 257
                    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
                        })
                    }
258 259 260 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
                }
            },
            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'))
                        })
                    );
                }
            },
357 358 359 360 361 362
            renderSystemDeatils: function(options) {
                var that = this,
                    data = options.data,
                    systemData = data.system,
                    systemOS = systemData.os || {},
                    systemRuntimeData = systemData.runtime || {},
363
                    systemMemoryData = systemData.memory || {};
364 365
                if (!_.isEmpty(systemOS)) {
                    that.ui.osCard.html(
366
                        that.createTable({
367 368 369 370 371 372 373 374 375
                            "data": systemOS
                        })
                    );
                }
                if (!_.isEmpty(systemRuntimeData)) {
                    _.each(systemRuntimeData, function(val, key) {
                        var space
                    })
                    that.ui.runtimeCard.html(
376
                        that.createTable({
377 378 379 380 381 382 383
                            "data": systemRuntimeData
                        })
                    );
                }
                if (!_.isEmpty(systemMemoryData)) {
                    var memoryTable = CommonViewFunction.propertyTable({
                        scope: this,
384
                        formatStringVal: true,
385 386 387 388 389 390
                        valueObject: systemMemoryData
                    });
                    that.ui.memoryCard.html(
                        memoryTable);
                }
            },
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
            getValue: function(options) {
                var value = options.value,
                    type = options.type;
                if (type == 'time') {
                    return Utils.millisecondsToTime(value);
                } else if (type == 'day') {
                    return moment.tz(value, moment.tz.guess()).format("MM/DD/YYYY h:mm A z");
                } 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;
});