<commit_before>/*global require */
/* jshint -W106 */

'use strict';
require(['jquery', 'underscore', 'backbone', 'humanize', 'views/application-view', 'models/application-model', 'helpers/config-loader', 'poller', 'helpers/generate-osds', 'collections/osd-collection', 'views/userdropdown', 'views/clusterdropdown', 'helpers/animation', 'views/graphwall-view', 'helpers/graph-utils', 'statemachine', 'marionette', 'bootstrap'], function($, _, Backbone, humanize, views, models, configloader, Poller, Generate, Collection, UserDropDown, ClusterDropDown, animation, GraphWall, helpers, StateMachine) {
    /* Default Configuration */
    var config = {
        offline: true,
        'delta-osd-api': false
    };

    /* Default Configuration */
    var AppRouter = Backbone.Router.extend({
        routes: {
            'workbench': 'workbench',
            'dashboard': 'dashboard',
            'graph/:host(/:osd)': 'graph'
        }
    });
    var appRouter = new AppRouter();
    /* Load Config.json first before starting app */
    var promise = configloader('scripts/config.json').then(function(result) {
        _.extend(config, result);
    });
    /* Load Config.json first before starting app */

    // TODO replace this with CSS version
    var replaceText = function($el, text, removeClass, addClass) {
            $el.css('display', 'none').text(text);
            if (removeClass !== undefined) {
                $el.removeClass(removeClass);
            }
            if (addClass !== undefined) {
                $el.addClass(addClass);
            }
            $el.fadeIn().css('display', '');
        };

    var App, userMenu, clusterMenu;
    promise.then(function() {
        App = new Backbone.Marionette.Application();
        App.ReqRes = new Backbone.Wreqr.RequestResponse();
        App.Config = config;
        userMenu = new UserDropDown({
            el: $('.usermenu'),
            App: App
        });
        userMenu.fetch();
        /* Demo Code */
        App.vent.listenTo(App.vent, 'status:healthok', function() {
            replaceText($('.warn-pg, .warn-osd, .warn-pool'), '0');
            replaceText($('.ok-pg'), 2400);
            replaceText($('.ok-pool'), 10);
        });
        App.vent.listenTo(App.vent, 'status:healthwarn', function() {
            var pg = Math.round(Math.random() * 45) + 5;
            var pool = Math.round(Math.random() * 1) + 1;
            replaceText($('.warn-pg'), pg);
            replaceText($('.warn-pool'), pool);
            replaceText($('.ok-pg'), 2400 - pg);
            replaceText($('.ok-pool'), 10 - pool);
        });
        App.vent.listenTo(App.vent, 'updateTotals', function() {
            var ONE_GIGABYTE = 1024 * 1024 * 1024;
            var totalUsed = 0,
                totalCapacity = 0,
                totalObj = 0,
                totalObjSpace = 0;
            viz.collection.each(function(m) {
                totalUsed += m.get('used');
                totalCapacity += m.get('capacity');
                totalObj += Math.random(Date.now()) * 100;
            });

            var settings = {
                cluster: 1,
                space: {
                    free_bytes: totalCapacity * ONE_GIGABYTE,
                    capacity_bytes: totalCapacity * ONE_GIGABYTE,
                    used_bytes: totalUsed * ONE_GIGABYTE
                }
            };
            gauge.set(new models.UsageModel(settings));
            $('.objcount').text(Math.floor(totalObj));
            totalObjSpace = totalObj * 50;
            totalObjSpace = humanize.filesize(Math.floor(totalObjSpace)).replace(' Kb', 'K');
            $('.objspace').text(totalObjSpace);
        });
        /* Demo Code */

        /* Widget Setup */
        var gaugesLayout = new views.GaugesLayout({
            el: '.gauges'
        });
        gaugesLayout.render();
        var healthView = new views.HealthView({
            App: App,
            model: new models.HealthModel({})
        });
        gaugesLayout.health.show(healthView);
        var gauge = new views.UsageView({
            App: App,
            model: new models.UsageModel({}),
            title: 'Usage'
        });
        gauge.listenTo(gauge, 'item:postrender', function() {
            App.vent.trigger('updateTotals');
        });

        var statusView = new views.StatusView({
            App: App,
            model: new models.StatusModel({})
        });
        gaugesLayout.status.show(statusView);

        var collection;
        if (config.offline) {
            collection = Generate.osds(160);
        } else {
            collection = new Collection([], {});
        }
        var viz = new views.OSDVisualization({
            App: App,
            collection: collection,
            el: '.raphael-one'
        });

        $('body').on('keyup', function(evt) {
            App.vent.trigger('keyup', evt);
        });

        _.extend(humanize.catalog, {
            'about_a_minute_ago': '1m',
            'minutes_ago': 'm',
            'about_an_hour_ago': '1h',
            'hours_ago': 'h',
            'one_day_ago': '1d',
            'days_ago': 'd',
            'about_a_month_ago': '1M',
            'months_ago': 'M',
            'a_year_ago': '1y',
            'years_ago': 'y'
        });
        views.NotificationCardView.view.setElement($('.notifications')).render();
        views.NotificationCardView.collection.add(
        [{
            title: 'OSD',
            message: 'OSD.100 has stopped responding',
            timestamp: humanize.time() - 24 * 60 * 60,
            priority: 2
        }, {
            title: 'Processes',
            message: 'MDS 192.168.20.2 is online',
            timestamp: humanize.time() - 60 * 60,
            priority: 0
        }, {
            title: 'Processes',
            message: 'OSD.10 has stopped responding',
            timestamp: humanize.time() - 60,
            priority: 2
        }, {
            title: 'Processes',
            message: 'MDS 192.168.20.2 has become unreachable',
            timestamp: humanize.time(),
            priority: 1
        }]);
        /* Widget Setup */

        /* Defer Visualization startup to after loading the cluster metadata */
        var clusterDeferred = $.Deferred();
        clusterMenu = new ClusterDropDown({
            el: $('.clustermenu'),
            App: App
        });
        clusterMenu.fetch().done(function() {
            clusterDeferred.resolve(clusterMenu.collection.at(0));
        });
        clusterDeferred.promise().done(function(cluster) {
            var poller = new Poller({
                App: App,
                cluster: cluster.get('id')
            });
            var graphWall = new GraphWall({
                App: App
            });

            viz.render().then(function() {
                gaugesLayout.usage.show(gauge);
                if (!config.offline) {
                    poller.start();
                }
            });

            var toWorkBenchAnimation = animation.single('toWorkBenchAnim');
            App.onentergraphmode = function( /*event, from, to, host, osd */ ) {
                $('.row').css('visibility', 'hidden');
                graphWall.render();
                $('.container').append(graphWall.$el);
            };
            App.ongraph = function(event, from, to, host, osd) {
                console.log('ongraph>> host: ' + host + ' osd: ' + osd);
                if (osd === 'all') {
                    graphWall.populateAll();
                }
            };
            App.onleavegraphmode = function() {
                graphWall.close();
                $('.row').css('visibility', 'visible');
            };
            App.onentervizmode = function(event, from) {
                var d = $.Deferred();
                var $body = $('body');
                var vent = App.vent;
                if (from === 'dashmode') {
                    vent.trigger('gauges:disappear', function() {
                        d.resolve();
                    });
                } else {
                    d.resolve();
                }

                d.promise().then(function() {
                    $body.addClass('workbench-mode');
                    toWorkBenchAnimation($body);
                    vent.trigger('viz:fullscreen', function() {
                        vent.trigger('gauges:collapse');
                    });
                });
            };
            var toDashboardAnimation = animation.single('toDashboardAnim');
            App.onleavevizmode = function(event, from, to) {
                var $body = $('body');
                var vent = App.vent;
                $body.removeClass('workbench-mode');
                var d = $.Deferred();
                if (to === 'dashmode') {
                    toDashboardAnimation($body).then(function() {
                        vent.trigger('viz:dashboard', function() {
                            d.resolve();
                        });
                    });

                } else {
                    vent.trigger('viz:dashboard', function() {
                        d.resolve();
                    });
                }
                d.promise().then(function() {
                    vent.trigger('gauges:expand', function() {
                        vent.trigger('gauges:reappear');
                    });
                });
            };
            App.onenterdashmode = function() {};

            App.onleavedashmode = function() {};

            var breadcrumbView = new views.BreadCrumbView({
                App: App,
                AppRouter: appRouter,
                el: '.inknav'
            });
            breadcrumbView.render();

            appRouter.on('route:workbench', function() {
                App.fsm.viz();
            });
            appRouter.on('route:dashboard', function() {
                App.fsm.dashboard();
            });
            appRouter.on('route:graph', function(host, osd) {
                console.log('router>> host: ' + host + ' osd: ' + osd);
                App.fsm.graph(host, osd);
            });

            appRouter.navigate('dashboard');

            App.fsm = StateMachine.create({
                initial: 'dashmode',
                events: [{
                    name: 'dashboard',
                    from: ['vizmode', 'graphmode'],
                    to: 'dashmode'
                }, {
                    name: 'viz',
                    from: ['dashmode', 'graphmode'],
                    to: 'vizmode'
                }, {
                    name: 'graph',
                    from: ['dashmode', 'vizmode', 'graphmode'],
                    to: 'graphmode'
                }],
                callbacks: {
                    onentervizmode: App.onentervizmode,
                    onleavevizmode: App.onleavevizmode,
                    onentergraphmode: App.onentergraphmode,
                    onleavegraphmode: App.onleavegraphmode,
                    onenterdashmode: App.onenterdashmode,
                    onleavedashmode: App.onleavedashmode,
                    ongraph: App.ongraph
                },
            });

            _.bindAll(App.fsm);

            App.listenTo(App.vent, 'app:fullscreen', function() {
                appRouter.navigate('workbench', {
                    trigger: true
                });
            });
            App.listenTo(App.vent, 'app:dashboard', function() {
                appRouter.navigate('dashboard', {
                    trigger: true
                });
            });
            App.listenTo(App.vent, 'app:graph', function() {
                appRouter.navigate('graph/all', {
                    trigger: true
                });
            });

            // Global Exports
            window.inktank = {
                App: App,
                Router: appRouter,
                ClusterMenu: clusterMenu,
                Gauge: gauge,
                Gauges: gaugesLayout,
                GraphWallView: graphWall,
                HealthView: healthView,
                Poller: poller,
                StatusView: statusView,
                UserMenu: userMenu,
                Viz: viz,
                models: models,
                helpers: helpers
            };
        });
        /* Defer Visualization startup to after loading the cluster metadata */
    });

    Backbone.history.start();

});
<commit_msg>Use the right key<commit_after>/*global require */
/* jshint -W106 */

'use strict';
require(['jquery', 'underscore', 'backbone', 'humanize', 'views/application-view', 'models/application-model', 'helpers/config-loader', 'poller', 'helpers/generate-osds', 'collections/osd-collection', 'views/userdropdown', 'views/clusterdropdown', 'helpers/animation', 'views/graphwall-view', 'helpers/graph-utils', 'statemachine', 'marionette', 'bootstrap'], function($, _, Backbone, humanize, views, models, configloader, Poller, Generate, Collection, UserDropDown, ClusterDropDown, animation, GraphWall, helpers, StateMachine) {
    /* Default Configuration */
    var config = {
        offline: true,
        'delta-osd-api': false
    };

    /* Default Configuration */
    var AppRouter = Backbone.Router.extend({
        routes: {
            'workbench': 'workbench',
            'dashboard': 'dashboard',
            'graph/:host(/:osd)': 'graph'
        }
    });
    var appRouter = new AppRouter();
    /* Load Config.json first before starting app */
    var promise = configloader('scripts/config.json').then(function(result) {
        _.extend(config, result);
    });
    /* Load Config.json first before starting app */

    // TODO replace this with CSS version
    var replaceText = function($el, text, removeClass, addClass) {
            $el.css('display', 'none').text(text);
            if (removeClass !== undefined) {
                $el.removeClass(removeClass);
            }
            if (addClass !== undefined) {
                $el.addClass(addClass);
            }
            $el.fadeIn().css('display', '');
        };

    var App, userMenu, clusterMenu;
    promise.then(function() {
        App = new Backbone.Marionette.Application();
        App.ReqRes = new Backbone.Wreqr.RequestResponse();
        App.Config = config;
        userMenu = new UserDropDown({
            el: $('.usermenu'),
            App: App
        });
        userMenu.fetch();
        /* Demo Code */
        App.vent.listenTo(App.vent, 'status:healthok', function() {
            replaceText($('.warn-pg, .warn-osd, .warn-pool'), '0');
            replaceText($('.ok-pg'), 2400);
            replaceText($('.ok-pool'), 10);
        });
        App.vent.listenTo(App.vent, 'status:healthwarn', function() {
            var pg = Math.round(Math.random() * 45) + 5;
            var pool = Math.round(Math.random() * 1) + 1;
            replaceText($('.warn-pg'), pg);
            replaceText($('.warn-pool'), pool);
            replaceText($('.ok-pg'), 2400 - pg);
            replaceText($('.ok-pool'), 10 - pool);
        });
        App.vent.listenTo(App.vent, 'updateTotals', function() {
            var ONE_GIGABYTE = 1024 * 1024 * 1024;
            var totalUsed = 0,
                totalCapacity = 0,
                totalObj = 0,
                totalObjSpace = 0;
            viz.collection.each(function(m) {
                totalUsed += m.get('used');
                totalCapacity += m.get('capacity');
                totalObj += Math.random(Date.now()) * 100;
            });

            var settings = {
                cluster: 1,
                space: {
                    free_bytes: totalCapacity * ONE_GIGABYTE,
                    capacity_bytes: totalCapacity * ONE_GIGABYTE,
                    used_bytes: totalUsed * ONE_GIGABYTE
                }
            };
            gauge.set(new models.UsageModel(settings));
            $('.objcount').text(Math.floor(totalObj));
            totalObjSpace = totalObj * 50;
            totalObjSpace = humanize.filesize(Math.floor(totalObjSpace)).replace(' Kb', 'K');
            $('.objspace').text(totalObjSpace);
        });
        /* Demo Code */

        /* Widget Setup */
        var gaugesLayout = new views.GaugesLayout({
            el: '.gauges'
        });
        gaugesLayout.render();
        var healthView = new views.HealthView({
            App: App,
            model: new models.HealthModel({})
        });
        gaugesLayout.health.show(healthView);
        var gauge = new views.UsageView({
            App: App,
            model: new models.UsageModel({}),
            title: 'Usage'
        });
        gauge.listenTo(gauge, 'item:postrender', function() {
            App.vent.trigger('updateTotals');
        });

        var statusView = new views.StatusView({
            App: App,
            model: new models.StatusModel({})
        });
        gaugesLayout.status.show(statusView);

        var collection;
        if (config.offline) {
            collection = Generate.osds(160);
        } else {
            collection = new Collection([], {});
        }
        var viz = new views.OSDVisualization({
            App: App,
            collection: collection,
            el: '.raphael-one'
        });

        $('body').on('keyup', function(evt) {
            App.vent.trigger('keyup', evt);
        });

        _.extend(humanize.catalog, {
            'about_a_minute_ago': '1m',
            'minutes_ago': 'm',
            'about_an_hour_ago': '1h',
            'hours_ago': 'h',
            'one_day_ago': '1d',
            'days_ago': 'd',
            'about_a_month_ago': '1M',
            'months_ago': 'M',
            'a_year_ago': '1y',
            'years_ago': 'y'
        });
        views.NotificationCardView.view.setElement($('.notifications')).render();
        views.NotificationCardView.collection.add(
        [{
            title: 'OSD',
            message: 'OSD.100 has stopped responding',
            timestamp: humanize.time() - 24 * 60 * 60,
            priority: 2
        }, {
            title: 'Processes',
            message: 'MDS 192.168.20.2 is online',
            timestamp: humanize.time() - 60 * 60,
            priority: 0
        }, {
            title: 'Processes',
            message: 'OSD.10 has stopped responding',
            timestamp: humanize.time() - 60,
            priority: 2
        }, {
            title: 'Processes',
            message: 'MDS 192.168.20.2 has become unreachable',
            timestamp: humanize.time(),
            priority: 1
        }]);
        /* Widget Setup */

        /* Defer Visualization startup to after loading the cluster metadata */
        var clusterDeferred = $.Deferred();
        clusterMenu = new ClusterDropDown({
            el: $('.clustermenu'),
            App: App
        });
        clusterMenu.fetch().done(function() {
            clusterDeferred.resolve(clusterMenu.collection.at(0));
        });
        clusterDeferred.promise().done(function(cluster) {
            var poller = new Poller({
                App: App,
                cluster: cluster.get('id')
            });
            var graphWall = new GraphWall({
                App: App
            });

            viz.render().then(function() {
                gaugesLayout.usage.show(gauge);
                if (!config.offline) {
                    poller.start();
                }
            });

            var toWorkBenchAnimation = animation.single('toWorkBenchAnim');
            App.onentergraphmode = function( /*event, from, to, host, osd */ ) {
                $('.row').css('visibility', 'hidden');
                graphWall.render();
                $('.container').append(graphWall.$el);
            };
            App.ongraph = function(event, from, to, host, osd) {
                console.log('ongraph>> host: ' + host + ' osd: ' + osd);
                if (host === 'all') {
                    graphWall.populateAll();
                }
            };
            App.onleavegraphmode = function() {
                graphWall.close();
                $('.row').css('visibility', 'visible');
            };
            App.onentervizmode = function(event, from) {
                var d = $.Deferred();
                var $body = $('body');
                var vent = App.vent;
                if (from === 'dashmode') {
                    vent.trigger('gauges:disappear', function() {
                        d.resolve();
                    });
                } else {
                    d.resolve();
                }

                d.promise().then(function() {
                    $body.addClass('workbench-mode');
                    toWorkBenchAnimation($body);
                    vent.trigger('viz:fullscreen', function() {
                        vent.trigger('gauges:collapse');
                    });
                });
            };
            var toDashboardAnimation = animation.single('toDashboardAnim');
            App.onleavevizmode = function(event, from, to) {
                var $body = $('body');
                var vent = App.vent;
                $body.removeClass('workbench-mode');
                var d = $.Deferred();
                if (to === 'dashmode') {
                    toDashboardAnimation($body).then(function() {
                        vent.trigger('viz:dashboard', function() {
                            d.resolve();
                        });
                    });

                } else {
                    vent.trigger('viz:dashboard', function() {
                        d.resolve();
                    });
                }
                d.promise().then(function() {
                    vent.trigger('gauges:expand', function() {
                        vent.trigger('gauges:reappear');
                    });
                });
            };
            App.onenterdashmode = function() {};

            App.onleavedashmode = function() {};

            var breadcrumbView = new views.BreadCrumbView({
                App: App,
                AppRouter: appRouter,
                el: '.inknav'
            });
            breadcrumbView.render();

            appRouter.on('route:workbench', function() {
                App.fsm.viz();
            });
            appRouter.on('route:dashboard', function() {
                App.fsm.dashboard();
            });
            appRouter.on('route:graph', function(host, osd) {
                console.log('router>> host: ' + host + ' osd: ' + osd);
                App.fsm.graph(host, osd);
            });

            appRouter.navigate('dashboard');

            App.fsm = StateMachine.create({
                initial: 'dashmode',
                events: [{
                    name: 'dashboard',
                    from: ['vizmode', 'graphmode'],
                    to: 'dashmode'
                }, {
                    name: 'viz',
                    from: ['dashmode', 'graphmode'],
                    to: 'vizmode'
                }, {
                    name: 'graph',
                    from: ['dashmode', 'vizmode', 'graphmode'],
                    to: 'graphmode'
                }],
                callbacks: {
                    onentervizmode: App.onentervizmode,
                    onleavevizmode: App.onleavevizmode,
                    onentergraphmode: App.onentergraphmode,
                    onleavegraphmode: App.onleavegraphmode,
                    onenterdashmode: App.onenterdashmode,
                    onleavedashmode: App.onleavedashmode,
                    ongraph: App.ongraph
                },
            });

            _.bindAll(App.fsm);

            App.listenTo(App.vent, 'app:fullscreen', function() {
                appRouter.navigate('workbench', {
                    trigger: true
                });
            });
            App.listenTo(App.vent, 'app:dashboard', function() {
                appRouter.navigate('dashboard', {
                    trigger: true
                });
            });
            App.listenTo(App.vent, 'app:graph', function() {
                appRouter.navigate('graph/all', {
                    trigger: true
                });
            });

            // Global Exports
            window.inktank = {
                App: App,
                Router: appRouter,
                ClusterMenu: clusterMenu,
                Gauge: gauge,
                Gauges: gaugesLayout,
                GraphWallView: graphWall,
                HealthView: healthView,
                Poller: poller,
                StatusView: statusView,
                UserMenu: userMenu,
                Viz: viz,
                models: models,
                helpers: helpers
            };
        });
        /* Defer Visualization startup to after loading the cluster metadata */
    });

    Backbone.history.start();

});
<|endoftext|>


<commit_before>/*
 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.
*/

// #/:core/analysis
sammy.get
(
  new RegExp( app.core_regex_base + '\\/(analysis)$' ),
  function( context )
  {
    var active_core = this.active_core;
    var core_basepath = active_core.attr( 'data-basepath' );
    var content_element = $( '#content' );

    $.get
    (
      'tpl/analysis.html',
      function( template )
      {
        content_element
          .html( template );

        var analysis_element = $( '#analysis', content_element );
        var analysis_form = $( 'form', analysis_element );
        var analysis_result = $( '#analysis-result', analysis_element );
        analysis_result.hide();

        var verbose_link = $( '.verbose_output a', analysis_element );

        var type_or_name = $( '#type_or_name', analysis_form );
        var schema_browser_element = $( '#tor_schema' );
        var schema_browser_path = app.core_menu.find( '.schema-browser a' ).attr( 'href' );
        var schema_browser_map = { 'fieldname' : 'field', 'fieldtype' : 'type' };

        type_or_name
          .die( 'change' )
          .live
          (
            'change',
            function( event )
            {
              var info = $( this ).val().split( '=' );

              schema_browser_element
                .attr( 'href', schema_browser_path + '?' + schema_browser_map[info[0]] + '=' + info[1] );
            }
          );

        $.ajax
        (
          {
            url : core_basepath + '/admin/luke?wt=json&show=schema',
            dataType : 'json',
            context : type_or_name,
            beforeSend : function( xhr, settings )
            {
              this
                .html( '<option value="">Loading ... </option>' )
                .addClass( 'loader' );
            },
            success : function( response, text_status, xhr )
            {
              var content = '';

              var fields = [];
              for( var field_name in response.schema.fields )
              {
                fields.push
                (
                  '<option value="fieldname=' + field_name + '">' + field_name + '</option>'
                );
              }
              if( 0 !== fields.length )
              {
                content += '<optgroup label="Fields">' + "\n";
                content += fields.sort().join( "\n" ) + "\n";
                content += '</optgroup>' + "\n";
              }

              var types = [];
              for( var type_name in response.schema.types )
              {
                types.push
                (
                  '<option value="fieldtype=' + type_name + '">' + type_name + '</option>'
                );
              }
              if( 0 !== types.length )
              {
                content += '<optgroup label="Types">' + "\n";
                content += types.sort().join( "\n" ) + "\n";
                content += '</optgroup>' + "\n";
              }

              this
                .html( content );

              var defaultSearchField = 'fieldname\=' + ( context.params['analysis.fieldname'] || response.schema.defaultSearchField );

              if( context.params['analysis.fieldtype'] )
              {
                defaultSearchField = 'fieldtype\=' + context.params['analysis.fieldtype'];
              }

              $( 'option[value="' + defaultSearchField + '"]', this )
                .attr( 'selected', 'selected' );

              this
                .chosen()
                .trigger( 'change' );

              var fields = 0;
              for( var key in context.params )
              {
                if( 'string' === typeof context.params[key] && 0 !== context.params[key].length )
                {
                  fields++;
                  $( '[name="' + key + '"]', analysis_form )
                    .val( context.params[key] );
                }
              }

              if( 'undefined' !== typeof context.params.verbose_output )
              {
                verbose_link.trigger( 'toggle', !!context.params.verbose_output.match( /^(1|true)$/ ) );
              }

              if( 0 !== fields )
              {
                analysis_form
                  .trigger( 'execute' );
              }
            },
            error : function( xhr, text_status, error_thrown)
            {
            },
            complete : function( xhr, text_status )
            {
              this
                .removeClass( 'loader' );
            }
          }
        );

        $( '.analysis-error .head a', analysis_element )
          .die( 'click' )
          .live
          (
            'click',
            function( event )
            {
              $( this ).parents( '.analysis-error' )
                .toggleClass( 'expanded' );
            }
          );

        var check_empty_spacer = function()
        {
          var spacer_holder = $( 'td.part.data.spacer .holder', analysis_result );

          if( 0 === spacer_holder.size() )
          {
            return false;
          }

          var verbose_output = analysis_result.hasClass( 'verbose_output' );

          spacer_holder
            .each
            (
              function( index, element )
              {
                element = $( element );

                if( verbose_output )
                {
                  var cell = element.parent();
                  element.height( cell.height() );
                }
                else
                {
                  element.removeAttr( 'style' );
                }
              }
            );
        }

        verbose_link
          .die( 'toggle' )
          .live
          (
            'toggle',
            function( event, state )
            {
              $( this ).parent()
                .toggleClass( 'active', state );

              analysis_result
                .toggleClass( 'verbose_output', state );

              check_empty_spacer();
            }
          )
          .die( 'click' )
          .live
          (
            'click',
            function( event )
            {
              $( this ).parent()
                .toggleClass( 'active' );

              analysis_form.trigger( 'submit' );
            }
          );

        var button = $( 'button', analysis_form )

        var compute_analysis_params = function()
        {
          var params = analysis_form.formToArray();

          var type_or_name = $( '#type_or_name', analysis_form ).val().split( '=' );
          params.push( { name: 'analysis.' + type_or_name[0], value: type_or_name[1] } );
          params.push( { name: 'verbose_output', value: $( '.verbose_output', analysis_element ).hasClass( 'active' ) ? 1 : 0 } );

          return params;
        }

        analysis_form
          .die( 'submit' )
          .live
          (
            'submit',
            function( event )
            {
              var params = $.param( compute_analysis_params() )
                            .replace( /[\w\.]+=\+*(&)/g, '$1' ) // remove empty parameters
                            .replace( /(&)+/, '$1' )            // reduce multiple ampersands
                            .replace( /^&/, '' )                // remove leading ampersand
                            .replace( /\+/, '%20' );            // replace plus-signs with encoded whitespaces

              context.redirect( context.path.split( '?' ).shift() + '?' + params );
              return false;
            }
          )
          .die( 'execute' )
          .live
          (
            'execute',
            function( event )
            {
              var url = core_basepath + '/analysis/field?wt=json&analysis.showmatch=true&' + context.path.split( '?' ).pop();
              url = url.replace( /&verbose_output=\d/, '' );

              $.ajax
              (
                {
                  url : url,
                  dataType : 'json',
                  beforeSend : function( xhr, settings )
                  {
                    loader.show( $( 'span', button ) );
                    button.attr( 'disabled', true );
                  },
                  success : function( response, status_text, xhr, form )
                  {
                    $( '.analysis-error', analysis_element )
                      .hide();

                    analysis_result
                      .empty()
                      .show();

                    for( var name in response.analysis.field_names )
                    {
                      build_analysis_table( 'name', name, response.analysis.field_names[name] );
                    }

                    for( var name in response.analysis.field_types )
                    {
                      build_analysis_table( 'type', name, response.analysis.field_types[name] );
                    }

                    check_empty_spacer();
                  },
                  error : function( xhr, text_status, error_thrown )
                  {
                    analysis_result
                      .empty()
                      .hide();

                    if( 404 === xhr.status )
                    {
                      $( '#analysis-handler-missing', analysis_element )
                        .show();
                    }
                    else
                    {
                      $( '#analysis-error', analysis_element )
                        .show();

                      var response = null;
                      try
                      {
                        eval( 'response = ' + xhr.responseText + ';' );
                      }
                      catch( e )
                      {
                        console.error( e );
                      }

                      $( '#analysis-error .body', analysis_element )
                        .text( response ? response.error.msg : xhr.responseText );
                    }
                  },
                  complete : function()
                  {
                    loader.hide( $( 'span', button ) );
                    button.removeAttr( 'disabled' );
                  }
                }
              );
            }
          );

          var generate_class_name = function( type )
          {
            var classes = [type];
            if( 'text' !== type )
            {
              classes.push( 'verbose_output' );
            }
            return classes.join( ' ' );
          }

          var build_analysis_table = function( field_or_name, name, analysis_data )
          {
            for( var type in analysis_data )
            {
              var type_length = analysis_data[type].length;
              if( 0 !== type_length )
              {
                var global_elements_count = 0;
                for( var i = 0; i < analysis_data[type].length; i += 2 )
                {
                  if( 'string' === typeof analysis_data[type][i+1] )
                  {
                    analysis_data[type][i+1] = [{ 'text': analysis_data[type][i+1] }]
                  }

                  var tmp = {};
                  var cols = analysis_data[type][i+1].filter
                  (
                    function( obj )
                    {
                      var obj_position = obj.position || 0;
                      if( !tmp[obj_position] )
                      {
                        tmp[obj_position] = true;
                        return true;
                      }

                      return false;
                    }
                  );

                  global_elements_count = Math.max( global_elements_count, cols.length );
                }

                var content = '
' + "\n";
                content += '
' + "\n";

                for( var i = 0; i < analysis_data[type].length; i += 2 )
                {
                  var colspan = 1;
                  var elements = analysis_data[type][i+1];
                  var elements_count = global_elements_count;

                  if( !elements[0] || !elements[0].positionHistory )
                  {
                    colspan = elements_count;
                    elements_count = 1;
                  }

                  var legend = [];
                  for( var key in elements[0] )
                  {
                    var key_parts = key.split( '#' );
                    var used_key = key_parts.pop();
                    var short_key = used_key;

                    if( 1 === key_parts.length )
                    {
                      used_key = '' + used_key + '';
                    }

                    if( 'positionHistory' === short_key || 'match' === short_key )
                    {
                      continue;
                    }

                    legend.push
                    (
                      '
' +
                      '' + used_key + '	' +
                      '
'
                    );
                  }

                  content += '
' + "\n";
                  content += '
' + "\n";

                    // analyzer
                    var analyzer_name = analysis_data[type][i].replace( /(\$1)+$/g, '' );

                    var analyzer_short = -1 !== analyzer_name.indexOf( '$' )
                                       ? analyzer_name.split( '$' )[1]
                                       : analyzer_name.split( '.' ).pop();
                    analyzer_short = analyzer_short.match( /[A-Z]/g ).join( '' );

                    content += '
' + "\n";
                    content += '' + "\n";
                    content += analyzer_short.esc() + '
	' + "\n";

                    // legend
                    content += '
' + "\n";
                    content += '
' + "\n";
                    content += '
' + "\n";
                    content += '
' + "\n";
                    content += legend.join( "\n" ) + "\n";
                    content += '

	' + "\n";

                    // data
                    var cell_content = '

	';
                    var cells = new Array( elements_count + 1 ).join( cell_content );
                    content += cells + "\n";

                  content += '
' + "\n";
                  content += '
' + "\n";
                }
                content += '
' + "\n";
                content += '
' + "\n";

                $( '.' + type, analysis_result )
                  .remove();

                analysis_result
                  .append( content );

                var analysis_result_type = $( '.' + type, analysis_result );

                for( var i = 0; i < analysis_data[type].length; i += 2 )
                {
                  for( var j = 0; j < analysis_data[type][i+1].length; j += 1 )
                  {
                    var pos = analysis_data[type][i+1][j].positionHistory
                        ? analysis_data[type][i+1][j].positionHistory[0]
                        : 1;
                    var selector = 'tr.step:eq(' + ( i / 2 ) +') '
                                 + 'td.data:eq(' + ( pos - 1 ) + ') '
                                 + '.holder';
                    var cell = $( selector, analysis_result_type );

                    cell.parent()
                      .removeClass( 'spacer' );

                    var table = $( 'table tr.details', cell );
                    if( 0 === table.size() )
                    {
                      cell
                        .html
                        (
                          '
' +
                          '

'
                        );
                      var table = $( 'table tr.details', cell );
                    }

                    var tokens = [];
                    for( var key in analysis_data[type][i+1][j] )
                    {
                      var short_key = key.split( '#' ).pop();

                      if( 'positionHistory' === short_key || 'match' === short_key )
                      {
                        continue;
                      }

                      var classes = [];
                      classes.push( generate_class_name( short_key ) );

                      var data = analysis_data[type][i+1][j][key];
                      if( 'object' === typeof data && data instanceof Array )
                      {
                        data = data.join( ' ' );
                      }
                      if( 'string' === typeof data )
                      {
                        data = data.esc();
                      }

                      if( null === data || 0 === data.length )
                      {
                        classes.push( 'empty' );
                        data = '∅';
                      }

                      if( analysis_data[type][i+1][j].match &&
                        ( 'text' === short_key || 'raw_bytes' === short_key ) )
                      {
                        classes.push( 'match' );
                      }

                      tokens.push
                      (
                        '
' +
                        '' + data + '	' +
                        '
'
                      );
                    }
                    table
                      .append
                      (
                        '' +
                        '
' +
                        tokens.join( "\n" ) +
                        '
	'
                      );
                  }
                }

              }
            }
          }

      }
    );
  }
);
<commit_msg>SOLR-4949: UI Analysis page dropping characters from input box<commit_after>/*
 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.
*/

// #/:core/analysis
sammy.get
(
  new RegExp( app.core_regex_base + '\\/(analysis)$' ),
  function( context )
  {
    var active_core = this.active_core;
    var core_basepath = active_core.attr( 'data-basepath' );
    var content_element = $( '#content' );

    $.get
    (
      'tpl/analysis.html',
      function( template )
      {
        content_element
          .html( template );

        var analysis_element = $( '#analysis', content_element );
        var analysis_form = $( 'form', analysis_element );
        var analysis_result = $( '#analysis-result', analysis_element );
        analysis_result.hide();

        var verbose_link = $( '.verbose_output a', analysis_element );

        var type_or_name = $( '#type_or_name', analysis_form );
        var schema_browser_element = $( '#tor_schema' );
        var schema_browser_path = app.core_menu.find( '.schema-browser a' ).attr( 'href' );
        var schema_browser_map = { 'fieldname' : 'field', 'fieldtype' : 'type' };

        type_or_name
          .die( 'change' )
          .live
          (
            'change',
            function( event )
            {
              var info = $( this ).val().split( '=' );

              schema_browser_element
                .attr( 'href', schema_browser_path + '?' + schema_browser_map[info[0]] + '=' + info[1] );
            }
          );

        $.ajax
        (
          {
            url : core_basepath + '/admin/luke?wt=json&show=schema',
            dataType : 'json',
            context : type_or_name,
            beforeSend : function( xhr, settings )
            {
              this
                .html( '<option value="">Loading ... </option>' )
                .addClass( 'loader' );
            },
            success : function( response, text_status, xhr )
            {
              var content = '';

              var fields = [];
              for( var field_name in response.schema.fields )
              {
                fields.push
                (
                  '<option value="fieldname=' + field_name + '">' + field_name + '</option>'
                );
              }
              if( 0 !== fields.length )
              {
                content += '<optgroup label="Fields">' + "\n";
                content += fields.sort().join( "\n" ) + "\n";
                content += '</optgroup>' + "\n";
              }

              var types = [];
              for( var type_name in response.schema.types )
              {
                types.push
                (
                  '<option value="fieldtype=' + type_name + '">' + type_name + '</option>'
                );
              }
              if( 0 !== types.length )
              {
                content += '<optgroup label="Types">' + "\n";
                content += types.sort().join( "\n" ) + "\n";
                content += '</optgroup>' + "\n";
              }

              this
                .html( content );

              var defaultSearchField = 'fieldname\=' + ( context.params['analysis.fieldname'] || response.schema.defaultSearchField );

              if( context.params['analysis.fieldtype'] )
              {
                defaultSearchField = 'fieldtype\=' + context.params['analysis.fieldtype'];
              }

              $( 'option[value="' + defaultSearchField + '"]', this )
                .attr( 'selected', 'selected' );

              this
                .chosen()
                .trigger( 'change' );

              var fields = 0;
              for( var key in context.params )
              {
                if( 'string' === typeof context.params[key] && 0 !== context.params[key].length )
                {
                  fields++;
                  $( '[name="' + key + '"]', analysis_form )
                    .val( context.params[key] );
                }
              }

              if( 'undefined' !== typeof context.params.verbose_output )
              {
                verbose_link.trigger( 'toggle', !!context.params.verbose_output.match( /^(1|true)$/ ) );
              }

              if( 0 !== fields )
              {
                analysis_form
                  .trigger( 'execute' );
              }
            },
            error : function( xhr, text_status, error_thrown)
            {
            },
            complete : function( xhr, text_status )
            {
              this
                .removeClass( 'loader' );
            }
          }
        );

        $( '.analysis-error .head a', analysis_element )
          .die( 'click' )
          .live
          (
            'click',
            function( event )
            {
              $( this ).parents( '.analysis-error' )
                .toggleClass( 'expanded' );
            }
          );

        var check_empty_spacer = function()
        {
          var spacer_holder = $( 'td.part.data.spacer .holder', analysis_result );

          if( 0 === spacer_holder.size() )
          {
            return false;
          }

          var verbose_output = analysis_result.hasClass( 'verbose_output' );

          spacer_holder
            .each
            (
              function( index, element )
              {
                element = $( element );

                if( verbose_output )
                {
                  var cell = element.parent();
                  element.height( cell.height() );
                }
                else
                {
                  element.removeAttr( 'style' );
                }
              }
            );
        }

        verbose_link
          .die( 'toggle' )
          .live
          (
            'toggle',
            function( event, state )
            {
              $( this ).parent()
                .toggleClass( 'active', state );

              analysis_result
                .toggleClass( 'verbose_output', state );

              check_empty_spacer();
            }
          )
          .die( 'click' )
          .live
          (
            'click',
            function( event )
            {
              $( this ).parent()
                .toggleClass( 'active' );

              analysis_form.trigger( 'submit' );
            }
          );

        var button = $( 'button', analysis_form )

        var compute_analysis_params = function()
        {
          var params = analysis_form.formToArray();

          var type_or_name = $( '#type_or_name', analysis_form ).val().split( '=' );
          params.push( { name: 'analysis.' + type_or_name[0], value: type_or_name[1] } );
          params.push( { name: 'verbose_output', value: $( '.verbose_output', analysis_element ).hasClass( 'active' ) ? 1 : 0 } );

          return params;
        }

        analysis_form
          .die( 'submit' )
          .live
          (
            'submit',
            function( event )
            {
              var params = $.param( compute_analysis_params() )
                            .replace( /[\w\.]+=\+*(&)/g, '$1' ) // remove empty parameters
                            .replace( /(&)+/, '$1' )            // reduce multiple ampersands
                            .replace( /^&/, '' )                // remove leading ampersand
                            .replace( /\+/g, '%20' );           // replace plus-signs with encoded whitespaces

              context.redirect( context.path.split( '?' ).shift() + '?' + params );
              return false;
            }
          )
          .die( 'execute' )
          .live
          (
            'execute',
            function( event )
            {
              var url = core_basepath + '/analysis/field?wt=json&analysis.showmatch=true&' + context.path.split( '?' ).pop();
              url = url.replace( /&verbose_output=\d/, '' );

              $.ajax
              (
                {
                  url : url,
                  dataType : 'json',
                  beforeSend : function( xhr, settings )
                  {
                    loader.show( $( 'span', button ) );
                    button.attr( 'disabled', true );
                  },
                  success : function( response, status_text, xhr, form )
                  {
                    $( '.analysis-error', analysis_element )
                      .hide();

                    analysis_result
                      .empty()
                      .show();

                    for( var name in response.analysis.field_names )
                    {
                      build_analysis_table( 'name', name, response.analysis.field_names[name] );
                    }

                    for( var name in response.analysis.field_types )
                    {
                      build_analysis_table( 'type', name, response.analysis.field_types[name] );
                    }

                    check_empty_spacer();
                  },
                  error : function( xhr, text_status, error_thrown )
                  {
                    analysis_result
                      .empty()
                      .hide();

                    if( 404 === xhr.status )
                    {
                      $( '#analysis-handler-missing', analysis_element )
                        .show();
                    }
                    else
                    {
                      $( '#analysis-error', analysis_element )
                        .show();

                      var response = null;
                      try
                      {
                        eval( 'response = ' + xhr.responseText + ';' );
                      }
                      catch( e )
                      {
                        console.error( e );
                      }

                      $( '#analysis-error .body', analysis_element )
                        .text( response ? response.error.msg : xhr.responseText );
                    }
                  },
                  complete : function()
                  {
                    loader.hide( $( 'span', button ) );
                    button.removeAttr( 'disabled' );
                  }
                }
              );
            }
          );

          var generate_class_name = function( type )
          {
            var classes = [type];
            if( 'text' !== type )
            {
              classes.push( 'verbose_output' );
            }
            return classes.join( ' ' );
          }

          var build_analysis_table = function( field_or_name, name, analysis_data )
          {
            for( var type in analysis_data )
            {
              var type_length = analysis_data[type].length;
              if( 0 !== type_length )
              {
                var global_elements_count = 0;
                for( var i = 0; i < analysis_data[type].length; i += 2 )
                {
                  if( 'string' === typeof analysis_data[type][i+1] )
                  {
                    analysis_data[type][i+1] = [{ 'text': analysis_data[type][i+1] }]
                  }

                  var tmp = {};
                  var cols = analysis_data[type][i+1].filter
                  (
                    function( obj )
                    {
                      var obj_position = obj.position || 0;
                      if( !tmp[obj_position] )
                      {
                        tmp[obj_position] = true;
                        return true;
                      }

                      return false;
                    }
                  );

                  global_elements_count = Math.max( global_elements_count, cols.length );
                }

                var content = '
' + "\n";
                content += '
' + "\n";

                for( var i = 0; i < analysis_data[type].length; i += 2 )
                {
                  var colspan = 1;
                  var elements = analysis_data[type][i+1];
                  var elements_count = global_elements_count;

                  if( !elements[0] || !elements[0].positionHistory )
                  {
                    colspan = elements_count;
                    elements_count = 1;
                  }

                  var legend = [];
                  for( var key in elements[0] )
                  {
                    var key_parts = key.split( '#' );
                    var used_key = key_parts.pop();
                    var short_key = used_key;

                    if( 1 === key_parts.length )
                    {
                      used_key = '' + used_key + '';
                    }

                    if( 'positionHistory' === short_key || 'match' === short_key )
                    {
                      continue;
                    }

                    legend.push
                    (
                      '
' +
                      '' + used_key + '	' +
                      '
'
                    );
                  }

                  content += '
' + "\n";
                  content += '
' + "\n";

                    // analyzer
                    var analyzer_name = analysis_data[type][i].replace( /(\$1)+$/g, '' );

                    var analyzer_short = -1 !== analyzer_name.indexOf( '$' )
                                       ? analyzer_name.split( '$' )[1]
                                       : analyzer_name.split( '.' ).pop();
                    analyzer_short = analyzer_short.match( /[A-Z]/g ).join( '' );

                    content += '
' + "\n";
                    content += '' + "\n";
                    content += analyzer_short.esc() + '
	' + "\n";

                    // legend
                    content += '
' + "\n";
                    content += '
' + "\n";
                    content += '
' + "\n";
                    content += '
' + "\n";
                    content += legend.join( "\n" ) + "\n";
                    content += '

	' + "\n";

                    // data
                    var cell_content = '

	';
                    var cells = new Array( elements_count + 1 ).join( cell_content );
                    content += cells + "\n";

                  content += '
' + "\n";
                  content += '
' + "\n";
                }
                content += '
' + "\n";
                content += '
' + "\n";

                $( '.' + type, analysis_result )
                  .remove();

                analysis_result
                  .append( content );

                var analysis_result_type = $( '.' + type, analysis_result );

                for( var i = 0; i < analysis_data[type].length; i += 2 )
                {
                  for( var j = 0; j < analysis_data[type][i+1].length; j += 1 )
                  {
                    var pos = analysis_data[type][i+1][j].positionHistory
                        ? analysis_data[type][i+1][j].positionHistory[0]
                        : 1;
                    var selector = 'tr.step:eq(' + ( i / 2 ) +') '
                                 + 'td.data:eq(' + ( pos - 1 ) + ') '
                                 + '.holder';
                    var cell = $( selector, analysis_result_type );

                    cell.parent()
                      .removeClass( 'spacer' );

                    var table = $( 'table tr.details', cell );
                    if( 0 === table.size() )
                    {
                      cell
                        .html
                        (
                          '
' +
                          '

'
                        );
                      var table = $( 'table tr.details', cell );
                    }

                    var tokens = [];
                    for( var key in analysis_data[type][i+1][j] )
                    {
                      var short_key = key.split( '#' ).pop();

                      if( 'positionHistory' === short_key || 'match' === short_key )
                      {
                        continue;
                      }

                      var classes = [];
                      classes.push( generate_class_name( short_key ) );

                      var data = analysis_data[type][i+1][j][key];
                      if( 'object' === typeof data && data instanceof Array )
                      {
                        data = data.join( ' ' );
                      }
                      if( 'string' === typeof data )
                      {
                        data = data.esc();
                      }

                      if( null === data || 0 === data.length )
                      {
                        classes.push( 'empty' );
                        data = '∅';
                      }

                      if( analysis_data[type][i+1][j].match &&
                        ( 'text' === short_key || 'raw_bytes' === short_key ) )
                      {
                        classes.push( 'match' );
                      }

                      tokens.push
                      (
                        '
' +
                        '' + data + '	' +
                        '
'
                      );
                    }
                    table
                      .append
                      (
                        '' +
                        '
' +
                        tokens.join( "\n" ) +
                        '
	'
                      );
                  }
                }

              }
            }
          }

      }
    );
  }
);
<|endoftext|>


<commit_before>$.tablesorter.addParser({
    id: 'humanizedBytes',
    is: function(s) {
        var spaceindex = s.indexOf(" ");
        if(spaceindex == -1) return false;

        var sp = s.split(" ");
        if(sp.length != 2) return false;
        var value = parseFloat(sp[0])
        if(isNaN(value)) return false;

        if(sp[1] == "B") return true;
        if(sp[1] == "KB") return true;
        if(sp[1] == "MB") return true;
        if(sp[1] == "GB") return true;

        return false;
    },
    format: function(s) {
        var sp = s.split(" ");
        var value = parseFloat(sp[0]);
        if(isNaN(value)) return $.tablesorter.formatFloat(0);

        var outval = 0;
        if(sp[1] == "B") outval = value;
        if(sp[1] == "KB") outval = value * 1024;
        if(sp[1] == "MB") outval = value * 1024 * 1024;
        if(sp[1] == "GB") outval = value * 1024 * 1024 * 1024;

        return $.tablesorter.formatFloat(outval);
    },
    type: 'numeric'
});

$.tablesorter.addParser({
    id: 'fiDate',
    is: function(s) {
        var spaceindex = s.indexOf(" ");
        if(spaceindex == -1) return false;

        var dtsplit = s.split(" ");
        if(dtsplit.length != 2) return false;
        if(dtsplit[0].length != 10 || dtsplit[0].indexOf(".") == -1) return false;
        if(dtsplit[1].length < 5  || dtsplit[1].indexOf(":") == -1) return false;

        var dates = dtsplit[0].split(".");
        var times = dtsplit[1].split(":");

        if(dates.length != 3) return false;
        if(times.length < 2) return false;
        if(dates[2].length != 4) return false;

        return true;
    },
    format: function(s) {
        var dtsplit = s.split(" ");
        var dates = dtsplit[0].split(".");
        var times = dtsplit[1].split(":");
        var s = (times.length == 3) ? times[2] : 0;
        var date = new Date(dates[2], dates[1], dates[0], times[0], times[1], s);
        return $.tablesorter.formatFloat(date.getTime());
    },
    type: 'numeric'
});

$.tablesorter.addParser({
    id: 'fiDateFancy',
    is: function(s) {
        var spaceindex = s.indexOf(" ");
        if(spaceindex == -1) return false;

        var dtsplit = s.split(" ");
        if(dtsplit.length != 3) return false;
        if(dtsplit[0].length != 10 || dtsplit[0].indexOf(".") == -1) return false;
        if(dtsplit[1] != "klo.") return false;
        if(dtsplit[2].length < 5 || dtsplit[2].indexOf(":") == -1) return false;

        var dates = dtsplit[0].split(".");
        var times = dtsplit[2].split(":");

        if(dates.length != 3) return false;
        if(times.length < 2) return false;
        if(dates[2].length != 4) return false;

        return true;
    },
    format: function(s) {
        var dtsplit = s.split(" ");
        var dates = dtsplit[0].split(".");
        var times = dtsplit[2].split(":");
        var s = (times.length == 3) ? times[2] : 0;
        var date = new Date(dates[2], dates[1]-1, dates[0], times[0], times[1], s, 0);
        return $.tablesorter.formatFloat(date.getTime());
    },
    type: 'numeric'
}); <commit_msg>libs: Remove unnecessary library files<commit_after><|endoftext|>


<commit_before>import moment from 'moment';
import { STAT_NAMES } from 'components/machines/Constants';

const Utils = {
  TERMINAL_TASK_STATES: ['TASK_KILLED', 'TASK_LOST', 'TASK_FAILED', 'TASK_FINISHED', 'TASK_ERROR'],

  DECOMMISION_STATES: ['DECOMMISSIONING', 'DECOMMISSIONED', 'STARTING_DECOMMISSION'],

  MACHINE_STATES_FOR_REVERT: ['DECOMMISSIONED', 'STARTING_DECOMMISSION', 'ACTIVE', 'FROZEN'],

  GLOB_CHARS: ['*', '!', '?', '[', ']'],

  LONG_RUNNING_IMMEDIATE_CLEANUPS: ['USER_REQUESTED', 'SCALING_DOWN', 'DEPLOY_FAILED', 'NEW_DEPLOY_SUCCEEDED', 'DEPLOY_STEP_FINISHED', 'DEPLOY_CANCELED' , 'TASK_EXCEEDED_TIME_LIMIT', 'UNHEALTHY_NEW_TASK', 'OVERDUE_NEW_TASK', 'USER_REQUESTED_DESTROY', 'PRIORITY_KILL', 'PAUSE'],

  NON_LONG_RUNNING_IMMEDIATE_CLEANUPS: ['USER_REQUESTED', 'DEPLOY_FAILED', 'DEPLOY_CANCELED', 'TASK_EXCEEDED_TIME_LIMIT', 'UNHEALTHY_NEW_TASK', 'OVERDUE_NEW_TASK', 'USER_REQUESTED_DESTROY', 'INCREMENTAL_DEPLOY_FAILED', 'INCREMENTAL_DEPLOY_CANCELLED', 'PRIORITY_KILL', 'PAUSE'],

  DEFAULT_SLAVES_COLUMNS: {'id': true, 'state': true, 'since': true, 'rack': true, 'host': true, 'uptime': true, 'actionUser': true, 'message': true, 'expiring': true},

  isIn(needle, haystack) {
    return !_.isEmpty(haystack) && haystack.indexOf(needle) >= 0;
  },

  humanizeText(text) {
    if (!text) {
      return '';
    }
    text = text.replace(/_/g, ' ');
    text = text.toLowerCase();
    text = text[0].toUpperCase() + text.substr(1);
    return text;
  },

  humanizeFileSize(bytes) {
    const kilo = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    if (bytes === 0) {
      return '0 B';
    }
    const numberOfPowers = Math.min(Math.floor(Math.log(bytes) / Math.log(kilo)), sizes.length - 1);
    return `${+(bytes / Math.pow(kilo, numberOfPowers)).toFixed(2)} ${sizes[numberOfPowers]}`;
  },

  humanizeCamelcase(text) {
    return text.replace(/^[a-z]|[A-Z]/g, (character, key) => (
      key === 0 ? character.toUpperCase() : ` ${character.toLowerCase()}`
    ));
  },

  humanizeSlaveHostName(longHostName) {
    return (config.shortenSlaveUsageHostname ? longHostName.split('.')[0] : longHostName);
  },

  timestampFromNow(millis) {
    const timeObject = moment(millis);
    return `${timeObject.fromNow()} (${timeObject.format(window.config.timestampFormat)})`;
  },

  absoluteTimestamp(millis) {
    return moment(millis).format(window.config.timestampFormat);
  },

  absoluteTimestampWithSeconds(millis) {
    return moment(millis).format(window.config.timestampWithSecondsFormat);
  },

  timestampWithinSeconds(timestamp, seconds) {
    const before = moment().subtract(seconds, 'seconds');
    const after = moment().add(seconds, 'seconds');
    return moment(timestamp).isBetween(before, after);
  },

  duration(millis) {
    return moment.duration(millis).humanize();
  },

  substituteTaskId(value, taskId) {
    return value.replace('$TASK_ID', taskId);
  },

  getLabelClassFromTaskState(state) {
    switch (state) {
      case 'TASK_STAGING':
      case 'TASK_LAUNCHED':
      case 'TASK_STARTING':
      case 'TASK_CLEANING':
        return 'info';
      case 'TASK_FINISHED':
      case 'TASK_KILLED':
        return 'primary';
      case 'TASK_RUNNING':
        return 'success';
      case 'TASK_LOST':
      case 'TASK_FAILED':
      case 'TASK_LOST_WHILE_DOWN':
      case 'TASK_ERROR':
        return 'danger';
      case 'TASK_OVERDUE':
        return 'warning';
      case 'TASK_SCHEDULED':
      case 'TASK_PENDING':
        return 'default';
      default:
        return 'danger'; // Unknown state.
    }
  },

  fileName(filePath) {
    return filePath.substring(filePath.lastIndexOf('/') + 1);
  },

  isGlobFilter(filter) {
    for (const char of this.GLOB_CHARS) {
      if (filter.indexOf(char) !== -1) {
        return true;
      }
    }
    return false;
  },

  fuzzyFilter(filter, fuzzyObjects) {
    const maxScore = _.max(fuzzyObjects, (fuzzyObject) => fuzzyObject.score).score;
    _.chain(fuzzyObjects).map((fuzzyObject) => {
        if (fuzzyObject.original.id.toLowerCase().startsWith(filter.toLowerCase())) {
          fuzzyObject.score = fuzzyObject.score * 10;
        } else if (fuzzyObject.original.id.toLowerCase().indexOf(filter.toLowerCase()) > -1) {
          fuzzyObject.score = fuzzyObject.score * 5;
        }
        return fuzzyObject;
    });
    return _.uniq(
      _.pluck(
        _.sortBy(
          _.filter(
            fuzzyObjects,
            (fuzzyObject) => {
              return fuzzyObject.score > (maxScore / 10) && fuzzyObject.score > 20;
            }
          ),
          (fuzzyObject) => {
            return fuzzyObject.score;
          }
        ).reverse(),
        'original'
      )
    );
  },

  convertMapFromObjectToArray(mapAsObj) {
    const mapAsArray = [];
    for (const key of _.keys(mapAsObj)) {
      mapAsArray.push({ key, value: mapAsObj[key] });
    }
    return mapAsArray;
  },

  convertMapFromArrayToObject(mapAsArray) {
    const mapAsObj = {};
    for (const pair of mapAsArray) {
      mapAsObj[pair.key] = pair.value;
    }
    return mapAsObj;
  },

  getTaskDataFromTaskId(taskId) {
    const splits = taskId.split('-');
    return {
      id: taskId,
      rackId: splits[splits.length - 1],
      host: splits[splits.length - 2],
      instanceNo: splits[splits.length - 3],
      startedAt: splits[splits.length - 4],
      deployId: splits[splits.length - 5],
      requestId: splits.slice(0, +(splits.length - 6) + 1 || 9e9).join('-')
    };
  },

  getMaxAvailableResource(slaveInfo, statName) {
    switch (statName) {
      case STAT_NAMES.cpusUsedStat:
        try {
          return parseFloat(slaveInfo.attributes.real_cpus || slaveInfo.resources.cpus);
        } catch (e) {
          throw new Error(`Could not find resource (cpus) for slave ${slaveInfo.host} (${slaveInfo.id})`);
        }
      case STAT_NAMES.memoryBytesUsedStat:
        try {
          return parseFloat(slaveInfo.attributes.real_memory_mb || slaveInfo.resources.mem);
        } catch (e) {
          throw new Error(`Could not find resource (memory) for slave ${slaveInfo.host} (${slaveInfo.id})`);
        }
      default:
        throw new Error(`${statName} is an unsupported statistic'`);
    }
  },

  deepClone(objectToClone) {
    return $.extend(true, {}, objectToClone);
  },

  ignore404(response) {
    if (response.status === 404) {
      app.caughtError();
    }
  },

  joinPath(firstPart, secondPart) {
    if (!firstPart.endsWith('/')) firstPart += '/';
    if (secondPart.startsWith('/')) secondPart = secondPart.substring(1);
    return `${firstPart}${secondPart}`;
  },

  range(begin, end, interval = 1) {
    const res = [];
    for (let currentValue = begin; currentValue < end; currentValue += interval) {
      res.push(currentValue);
    }
    return res;
  },

  trimS3File(filename, taskId) {
    if (!config.taskS3LogOmitPrefix) {
      return filename;
    }
    const finalRegex = config.taskS3LogOmitPrefix.replace('%taskId', taskId.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).replace('%index', '[0-9]+').replace('%s', '[0-9]+');
    return filename.replace(new RegExp(finalRegex), '');
  },

  roundTo(value, place) {
    return +(Math.round(parseFloat(value) + 'e+' + place) + 'e-' + place);
  },

  millisecondsToSecondsRoundToTenth(millis) {
    return Math.round(millis / 100) / 10;
  },

  isCauseOfFailure(task, deploy) {
    for (const failure of deploy.deployResult.deployFailures) {
      if (failure.taskId && failure.taskId.id === task.task.taskId.id) {
        return true;
      }
    }
    return false;
  },

  causeOfDeployFailure(task, deploy) {
    for (const failure of deploy.deployResult.deployFailures) {
      if (failure.taskId && failure.taskId.id === task.task.taskId.id) {
        return this.humanizeText(failure.reason);
      }
    }
    return '';
  },

  ifDeployFailureCausedTaskToBeKilled(task) {
    let deployFailed = false;
    let taskKilled = false;
    for (const update of task.taskUpdates) {
      if (update.statusMessage && update.statusMessage.indexOf('DEPLOY_FAILED' !== -1)) {
        deployFailed = true;
      }
      if (update.taskState === 'TASK_KILLED') {
        taskKilled = true;
      }
    }
    return deployFailed && taskKilled;
  },

  healthcheckPort(healthcheckOptions, ports) {
    if (healthcheckOptions) {
      if (healthcheckOptions.portNumber) {
        return healthcheckOptions.portNumber;
      } else if (healthcheckOptions.portIndex && ports.length > healthcheckOptions.portIndex) {
        return ports[healthcheckOptions.portIndex];
      } else {
        return _.first(ports);
      }
    } else {
      return _.first(ports);
    }
  },

  healthcheckTimeout(healthcheckOptions) {
    if (healthcheckOptions) {
      let startupTimeout = healthcheckOptions.startupTimeoutSeconds || config.defaultStartupTimeoutSeconds;
      let attempts = (healthcheckOptions.maxRetries || config.defaultHealthcheckMaxRetries) + 1
      return startupTimeout + (attempts * (healthcheckOptions.intervalSeconds || config.defaultHealthcheckIntervalSeconds))
    } else {
      return config.defaultStartupTimeoutSeconds + ((config.defaultHealthcheckMaxRetries + 1) * config.defaultHealthcheckIntervalSeconds);
    }
  },

  maybe(object, path, defaultValue = undefined) {
    if (!path.length) {
      return object;
    }
    if (!object) {
      return defaultValue;
    }
    if (object.hasOwnProperty(path[0])) {
      return Utils.maybe(
        object[path[0]],
        path.slice(1, path.length)
      );
    }

    return defaultValue;
  },

  api: {
    isFirstLoad: (api) => {
      return !api || (
        api.isFetching &&
        !api.error &&
        !api.receivedAt
      );
    }
  },
  task: {
    instanceBreakdown: (tasks) => {
      const taskStates = {
        TASK_LAUNCHED: 0,
        TASK_STAGING: 0,
        TASK_STARTING: 0,
        TASK_RUNNING: 0,
        TASK_CLEANING: 0,
        TASK_KILLING: 0,
        TASK_FINISHED: 0,
        TASK_FAILED: 0,
        TASK_KILLED: 0,
        TASK_LOST: 0,
        TASK_LOST_WHILE_DOWN: 0,
        TASK_ERROR: 0
      };

      tasks.forEach((task) => {
        taskStates[task.lastTaskState] = (taskStates[task.lastTaskState] || 0) + 1;
      });

      return taskStates;
    }
  },
  request: {
    // all of these expect a RequestParent object
    LONG_RUNNING_TYPES: new Set(['WORKER', 'SERVICE']),
    hasActiveDeploy: (requestParent) => {
      return Utils.maybe(requestParent, ['activeDeploy'], false) || Utils.maybe(requestParent, ['requestDeployState', 'activeDeploy'], false);
    },
    isDeploying: (requestParent) => {
      return Utils.maybe(requestParent, ['pendingDeploy'], false);
    },
    isLongRunning: (requestParent) => {
      return Utils.request.LONG_RUNNING_TYPES.has(requestParent.request.requestType);
    },
    canBeRunNow: (requestParent) => {
      return requestParent.state === 'ACTIVE'
        && new Set(['SCHEDULED', 'ON_DEMAND']).has(requestParent.request.requestType)
        && Utils.request.hasActiveDeploy(requestParent);
    },
    canBeBounced: (requestParent) => {
      return new Set(['ACTIVE', 'SYSTEM_COOLDOWN']).has(requestParent.state)
        && Utils.request.isLongRunning(requestParent);
    },
    canBeScaled: (requestParent) => {
      return new Set(['ACTIVE', 'SYSTEM_COOLDOWN']).has(requestParent.state)
        && Utils.request.hasActiveDeploy(requestParent)
        && Utils.request.isLongRunning(requestParent);
    },
    runningInstanceCount: (activeTasksForRequest) => {
      return activeTasksForRequest.filter(
        (task) => task.lastTaskState === 'TASK_RUNNING'
      ).length;
    },
    deployingInstanceCount: (requestParent, activeTasksForRequest) => {
      if (!requestParent.pendingDeploy) {
        return 0;
      }
      return activeTasksForRequest.filter((task) => (
        task.lastTaskState === 'TASK_RUNNING'
        && task.taskId.deployId === requestParent.pendingDeploy.id
      )).length;
    },
    // other
    canDisableHealthchecks: (requestParent) => {
      return !!requestParent.activeDeploy
        && !!requestParent.activeDeploy.healthcheck
        && !!requestParent.activeDeploy.healthcheck.uri
        && requestParent.state !== 'PAUSED'
        && !requestParent.expiringSkipHealthchecks;
    },
    pauseDisabled: (requestParent) => {
      const expiringPause = Utils.maybe(requestParent, 'expiringPause');
      return expiringPause
        ? (expiringPause.startMillis + expiringPause.expiringAPIRequestObject.durationMillis) > new Date().getTime()
        : false;
    },
    scaleDisabled: (requestParent) => {
      const expiringScale = Utils.maybe(requestParent, 'expiringScale');
      return expiringScale
        ? (expiringScale.startMillis + expiringScale.expiringAPIRequestObject.durationMillis) > new Date().getTime()
        : false;
    },
    bounceDisabled: (requestParent) => {
      const expiringBounce = Utils.maybe(requestParent, 'expiringBounce');
      return expiringBounce
        ? (expiringBounce.startMillis + expiringBounce.expiringAPIRequestObject.durationMillis) > new Date().getTime()
        : false;
    },
  },

  isImmediateCleanup: (cleanupType, longRunning) => {
    if (longRunning) {
      return _.contains(Utils.LONG_RUNNING_IMMEDIATE_CLEANUPS, cleanupType)
    } else {
      return _.contains(Utils.NON_LONG_RUNNING_IMMEDIATE_CLEANUPS, cleanupType)
    }
  },

  enums: {
    SingularityRequestTypes: ['SERVICE', 'WORKER', 'SCHEDULED', 'ON_DEMAND', 'RUN_ONCE'],
    SingularityEmailDestination: ['OWNERS', 'ACTION_TAKER', 'ADMINS'],
    SingularityEmailType: [
      'TASK_LOST',
      'TASK_KILLED',
      'TASK_FINISHED_SCHEDULED',
      'TASK_FINISHED_LONG_RUNNING',
      'TASK_FINISHED_ON_DEMAND',
      'TASK_FINISHED_RUN_ONCE',
      'TASK_FAILED',
      'TASK_SCHEDULED_OVERDUE_TO_FINISH',
      'TASK_KILLED_DECOMISSIONED',
      'TASK_KILLED_UNHEALTHY',
      'REQUEST_IN_COOLDOWN',
      'SINGULARITY_ABORTING',
      'REQUEST_REMOVED',
      'REQUEST_PAUSED',
      'REQUEST_UNPAUSED',
      'REQUEST_SCALED',
      'TASK_FAILED_DECOMISSIONED'
    ]
  },

  queryParams(source) {
    const array = [];
    for (const key in source) {
      if (source[key]) {
        array.push(`${encodeURIComponent(key)}=${encodeURIComponent(source[key])}`);
      }
    }
    return array.join('&');
  }
};

export default Utils;
<commit_msg>ref error<commit_after>import moment from 'moment';
import { STAT_NAMES } from './components/machines/Constants';

const Utils = {
  TERMINAL_TASK_STATES: ['TASK_KILLED', 'TASK_LOST', 'TASK_FAILED', 'TASK_FINISHED', 'TASK_ERROR'],

  DECOMMISION_STATES: ['DECOMMISSIONING', 'DECOMMISSIONED', 'STARTING_DECOMMISSION'],

  MACHINE_STATES_FOR_REVERT: ['DECOMMISSIONED', 'STARTING_DECOMMISSION', 'ACTIVE', 'FROZEN'],

  GLOB_CHARS: ['*', '!', '?', '[', ']'],

  LONG_RUNNING_IMMEDIATE_CLEANUPS: ['USER_REQUESTED', 'SCALING_DOWN', 'DEPLOY_FAILED', 'NEW_DEPLOY_SUCCEEDED', 'DEPLOY_STEP_FINISHED', 'DEPLOY_CANCELED' , 'TASK_EXCEEDED_TIME_LIMIT', 'UNHEALTHY_NEW_TASK', 'OVERDUE_NEW_TASK', 'USER_REQUESTED_DESTROY', 'PRIORITY_KILL', 'PAUSE'],

  NON_LONG_RUNNING_IMMEDIATE_CLEANUPS: ['USER_REQUESTED', 'DEPLOY_FAILED', 'DEPLOY_CANCELED', 'TASK_EXCEEDED_TIME_LIMIT', 'UNHEALTHY_NEW_TASK', 'OVERDUE_NEW_TASK', 'USER_REQUESTED_DESTROY', 'INCREMENTAL_DEPLOY_FAILED', 'INCREMENTAL_DEPLOY_CANCELLED', 'PRIORITY_KILL', 'PAUSE'],

  DEFAULT_SLAVES_COLUMNS: {'id': true, 'state': true, 'since': true, 'rack': true, 'host': true, 'uptime': true, 'actionUser': true, 'message': true, 'expiring': true},

  isIn(needle, haystack) {
    return !_.isEmpty(haystack) && haystack.indexOf(needle) >= 0;
  },

  humanizeText(text) {
    if (!text) {
      return '';
    }
    text = text.replace(/_/g, ' ');
    text = text.toLowerCase();
    text = text[0].toUpperCase() + text.substr(1);
    return text;
  },

  humanizeFileSize(bytes) {
    const kilo = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    if (bytes === 0) {
      return '0 B';
    }
    const numberOfPowers = Math.min(Math.floor(Math.log(bytes) / Math.log(kilo)), sizes.length - 1);
    return `${+(bytes / Math.pow(kilo, numberOfPowers)).toFixed(2)} ${sizes[numberOfPowers]}`;
  },

  humanizeCamelcase(text) {
    return text.replace(/^[a-z]|[A-Z]/g, (character, key) => (
      key === 0 ? character.toUpperCase() : ` ${character.toLowerCase()}`
    ));
  },

  humanizeSlaveHostName(longHostName) {
    return (config.shortenSlaveUsageHostname ? longHostName.split('.')[0] : longHostName);
  },

  timestampFromNow(millis) {
    const timeObject = moment(millis);
    return `${timeObject.fromNow()} (${timeObject.format(window.config.timestampFormat)})`;
  },

  absoluteTimestamp(millis) {
    return moment(millis).format(window.config.timestampFormat);
  },

  absoluteTimestampWithSeconds(millis) {
    return moment(millis).format(window.config.timestampWithSecondsFormat);
  },

  timestampWithinSeconds(timestamp, seconds) {
    const before = moment().subtract(seconds, 'seconds');
    const after = moment().add(seconds, 'seconds');
    return moment(timestamp).isBetween(before, after);
  },

  duration(millis) {
    return moment.duration(millis).humanize();
  },

  substituteTaskId(value, taskId) {
    return value.replace('$TASK_ID', taskId);
  },

  getLabelClassFromTaskState(state) {
    switch (state) {
      case 'TASK_STAGING':
      case 'TASK_LAUNCHED':
      case 'TASK_STARTING':
      case 'TASK_CLEANING':
        return 'info';
      case 'TASK_FINISHED':
      case 'TASK_KILLED':
        return 'primary';
      case 'TASK_RUNNING':
        return 'success';
      case 'TASK_LOST':
      case 'TASK_FAILED':
      case 'TASK_LOST_WHILE_DOWN':
      case 'TASK_ERROR':
        return 'danger';
      case 'TASK_OVERDUE':
        return 'warning';
      case 'TASK_SCHEDULED':
      case 'TASK_PENDING':
        return 'default';
      default:
        return 'danger'; // Unknown state.
    }
  },

  fileName(filePath) {
    return filePath.substring(filePath.lastIndexOf('/') + 1);
  },

  isGlobFilter(filter) {
    for (const char of this.GLOB_CHARS) {
      if (filter.indexOf(char) !== -1) {
        return true;
      }
    }
    return false;
  },

  fuzzyFilter(filter, fuzzyObjects) {
    const maxScore = _.max(fuzzyObjects, (fuzzyObject) => fuzzyObject.score).score;
    _.chain(fuzzyObjects).map((fuzzyObject) => {
        if (fuzzyObject.original.id.toLowerCase().startsWith(filter.toLowerCase())) {
          fuzzyObject.score = fuzzyObject.score * 10;
        } else if (fuzzyObject.original.id.toLowerCase().indexOf(filter.toLowerCase()) > -1) {
          fuzzyObject.score = fuzzyObject.score * 5;
        }
        return fuzzyObject;
    });
    return _.uniq(
      _.pluck(
        _.sortBy(
          _.filter(
            fuzzyObjects,
            (fuzzyObject) => {
              return fuzzyObject.score > (maxScore / 10) && fuzzyObject.score > 20;
            }
          ),
          (fuzzyObject) => {
            return fuzzyObject.score;
          }
        ).reverse(),
        'original'
      )
    );
  },

  convertMapFromObjectToArray(mapAsObj) {
    const mapAsArray = [];
    for (const key of _.keys(mapAsObj)) {
      mapAsArray.push({ key, value: mapAsObj[key] });
    }
    return mapAsArray;
  },

  convertMapFromArrayToObject(mapAsArray) {
    const mapAsObj = {};
    for (const pair of mapAsArray) {
      mapAsObj[pair.key] = pair.value;
    }
    return mapAsObj;
  },

  getTaskDataFromTaskId(taskId) {
    const splits = taskId.split('-');
    return {
      id: taskId,
      rackId: splits[splits.length - 1],
      host: splits[splits.length - 2],
      instanceNo: splits[splits.length - 3],
      startedAt: splits[splits.length - 4],
      deployId: splits[splits.length - 5],
      requestId: splits.slice(0, +(splits.length - 6) + 1 || 9e9).join('-')
    };
  },

  getMaxAvailableResource(slaveInfo, statName) {
    switch (statName) {
      case STAT_NAMES.cpusUsedStat:
        try {
          return parseFloat(slaveInfo.attributes.real_cpus || slaveInfo.resources.cpus);
        } catch (e) {
          throw new Error(`Could not find resource (cpus) for slave ${slaveInfo.host} (${slaveInfo.id})`);
        }
      case STAT_NAMES.memoryBytesUsedStat:
        try {
          return parseFloat(slaveInfo.attributes.real_memory_mb || slaveInfo.resources.mem);
        } catch (e) {
          throw new Error(`Could not find resource (memory) for slave ${slaveInfo.host} (${slaveInfo.id})`);
        }
      default:
        throw new Error(`${statName} is an unsupported statistic'`);
    }
  },

  deepClone(objectToClone) {
    return $.extend(true, {}, objectToClone);
  },

  ignore404(response) {
    if (response.status === 404) {
      app.caughtError();
    }
  },

  joinPath(firstPart, secondPart) {
    if (!firstPart.endsWith('/')) firstPart += '/';
    if (secondPart.startsWith('/')) secondPart = secondPart.substring(1);
    return `${firstPart}${secondPart}`;
  },

  range(begin, end, interval = 1) {
    const res = [];
    for (let currentValue = begin; currentValue < end; currentValue += interval) {
      res.push(currentValue);
    }
    return res;
  },

  trimS3File(filename, taskId) {
    if (!config.taskS3LogOmitPrefix) {
      return filename;
    }
    const finalRegex = config.taskS3LogOmitPrefix.replace('%taskId', taskId.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).replace('%index', '[0-9]+').replace('%s', '[0-9]+');
    return filename.replace(new RegExp(finalRegex), '');
  },

  roundTo(value, place) {
    return +(Math.round(parseFloat(value) + 'e+' + place) + 'e-' + place);
  },

  millisecondsToSecondsRoundToTenth(millis) {
    return Math.round(millis / 100) / 10;
  },

  isCauseOfFailure(task, deploy) {
    for (const failure of deploy.deployResult.deployFailures) {
      if (failure.taskId && failure.taskId.id === task.task.taskId.id) {
        return true;
      }
    }
    return false;
  },

  causeOfDeployFailure(task, deploy) {
    for (const failure of deploy.deployResult.deployFailures) {
      if (failure.taskId && failure.taskId.id === task.task.taskId.id) {
        return this.humanizeText(failure.reason);
      }
    }
    return '';
  },

  ifDeployFailureCausedTaskToBeKilled(task) {
    let deployFailed = false;
    let taskKilled = false;
    for (const update of task.taskUpdates) {
      if (update.statusMessage && update.statusMessage.indexOf('DEPLOY_FAILED' !== -1)) {
        deployFailed = true;
      }
      if (update.taskState === 'TASK_KILLED') {
        taskKilled = true;
      }
    }
    return deployFailed && taskKilled;
  },

  healthcheckPort(healthcheckOptions, ports) {
    if (healthcheckOptions) {
      if (healthcheckOptions.portNumber) {
        return healthcheckOptions.portNumber;
      } else if (healthcheckOptions.portIndex && ports.length > healthcheckOptions.portIndex) {
        return ports[healthcheckOptions.portIndex];
      } else {
        return _.first(ports);
      }
    } else {
      return _.first(ports);
    }
  },

  healthcheckTimeout(healthcheckOptions) {
    if (healthcheckOptions) {
      let startupTimeout = healthcheckOptions.startupTimeoutSeconds || config.defaultStartupTimeoutSeconds;
      let attempts = (healthcheckOptions.maxRetries || config.defaultHealthcheckMaxRetries) + 1
      return startupTimeout + (attempts * (healthcheckOptions.intervalSeconds || config.defaultHealthcheckIntervalSeconds))
    } else {
      return config.defaultStartupTimeoutSeconds + ((config.defaultHealthcheckMaxRetries + 1) * config.defaultHealthcheckIntervalSeconds);
    }
  },

  maybe(object, path, defaultValue = undefined) {
    if (!path.length) {
      return object;
    }
    if (!object) {
      return defaultValue;
    }
    if (object.hasOwnProperty(path[0])) {
      return Utils.maybe(
        object[path[0]],
        path.slice(1, path.length)
      );
    }

    return defaultValue;
  },

  api: {
    isFirstLoad: (api) => {
      return !api || (
        api.isFetching &&
        !api.error &&
        !api.receivedAt
      );
    }
  },
  task: {
    instanceBreakdown: (tasks) => {
      const taskStates = {
        TASK_LAUNCHED: 0,
        TASK_STAGING: 0,
        TASK_STARTING: 0,
        TASK_RUNNING: 0,
        TASK_CLEANING: 0,
        TASK_KILLING: 0,
        TASK_FINISHED: 0,
        TASK_FAILED: 0,
        TASK_KILLED: 0,
        TASK_LOST: 0,
        TASK_LOST_WHILE_DOWN: 0,
        TASK_ERROR: 0
      };

      tasks.forEach((task) => {
        taskStates[task.lastTaskState] = (taskStates[task.lastTaskState] || 0) + 1;
      });

      return taskStates;
    }
  },
  request: {
    // all of these expect a RequestParent object
    LONG_RUNNING_TYPES: new Set(['WORKER', 'SERVICE']),
    hasActiveDeploy: (requestParent) => {
      return Utils.maybe(requestParent, ['activeDeploy'], false) || Utils.maybe(requestParent, ['requestDeployState', 'activeDeploy'], false);
    },
    isDeploying: (requestParent) => {
      return Utils.maybe(requestParent, ['pendingDeploy'], false);
    },
    isLongRunning: (requestParent) => {
      return Utils.request.LONG_RUNNING_TYPES.has(requestParent.request.requestType);
    },
    canBeRunNow: (requestParent) => {
      return requestParent.state === 'ACTIVE'
        && new Set(['SCHEDULED', 'ON_DEMAND']).has(requestParent.request.requestType)
        && Utils.request.hasActiveDeploy(requestParent);
    },
    canBeBounced: (requestParent) => {
      return new Set(['ACTIVE', 'SYSTEM_COOLDOWN']).has(requestParent.state)
        && Utils.request.isLongRunning(requestParent);
    },
    canBeScaled: (requestParent) => {
      return new Set(['ACTIVE', 'SYSTEM_COOLDOWN']).has(requestParent.state)
        && Utils.request.hasActiveDeploy(requestParent)
        && Utils.request.isLongRunning(requestParent);
    },
    runningInstanceCount: (activeTasksForRequest) => {
      return activeTasksForRequest.filter(
        (task) => task.lastTaskState === 'TASK_RUNNING'
      ).length;
    },
    deployingInstanceCount: (requestParent, activeTasksForRequest) => {
      if (!requestParent.pendingDeploy) {
        return 0;
      }
      return activeTasksForRequest.filter((task) => (
        task.lastTaskState === 'TASK_RUNNING'
        && task.taskId.deployId === requestParent.pendingDeploy.id
      )).length;
    },
    // other
    canDisableHealthchecks: (requestParent) => {
      return !!requestParent.activeDeploy
        && !!requestParent.activeDeploy.healthcheck
        && !!requestParent.activeDeploy.healthcheck.uri
        && requestParent.state !== 'PAUSED'
        && !requestParent.expiringSkipHealthchecks;
    },
    pauseDisabled: (requestParent) => {
      const expiringPause = Utils.maybe(requestParent, 'expiringPause');
      return expiringPause
        ? (expiringPause.startMillis + expiringPause.expiringAPIRequestObject.durationMillis) > new Date().getTime()
        : false;
    },
    scaleDisabled: (requestParent) => {
      const expiringScale = Utils.maybe(requestParent, 'expiringScale');
      return expiringScale
        ? (expiringScale.startMillis + expiringScale.expiringAPIRequestObject.durationMillis) > new Date().getTime()
        : false;
    },
    bounceDisabled: (requestParent) => {
      const expiringBounce = Utils.maybe(requestParent, 'expiringBounce');
      return expiringBounce
        ? (expiringBounce.startMillis + expiringBounce.expiringAPIRequestObject.durationMillis) > new Date().getTime()
        : false;
    },
  },

  isImmediateCleanup: (cleanupType, longRunning) => {
    if (longRunning) {
      return _.contains(Utils.LONG_RUNNING_IMMEDIATE_CLEANUPS, cleanupType)
    } else {
      return _.contains(Utils.NON_LONG_RUNNING_IMMEDIATE_CLEANUPS, cleanupType)
    }
  },

  enums: {
    SingularityRequestTypes: ['SERVICE', 'WORKER', 'SCHEDULED', 'ON_DEMAND', 'RUN_ONCE'],
    SingularityEmailDestination: ['OWNERS', 'ACTION_TAKER', 'ADMINS'],
    SingularityEmailType: [
      'TASK_LOST',
      'TASK_KILLED',
      'TASK_FINISHED_SCHEDULED',
      'TASK_FINISHED_LONG_RUNNING',
      'TASK_FINISHED_ON_DEMAND',
      'TASK_FINISHED_RUN_ONCE',
      'TASK_FAILED',
      'TASK_SCHEDULED_OVERDUE_TO_FINISH',
      'TASK_KILLED_DECOMISSIONED',
      'TASK_KILLED_UNHEALTHY',
      'REQUEST_IN_COOLDOWN',
      'SINGULARITY_ABORTING',
      'REQUEST_REMOVED',
      'REQUEST_PAUSED',
      'REQUEST_UNPAUSED',
      'REQUEST_SCALED',
      'TASK_FAILED_DECOMISSIONED'
    ]
  },

  queryParams(source) {
    const array = [];
    for (const key in source) {
      if (source[key]) {
        array.push(`${encodeURIComponent(key)}=${encodeURIComponent(source[key])}`);
      }
    }
    return array.join('&');
  }
};

export default Utils;
<|endoftext|>