Code coverage report for app/mixins/main/service/configs/config_overridable.js

Statements: 64.71% (99 / 153)      Branches: 50.6% (42 / 83)      Functions: 64.1% (25 / 39)      Lines: 64.71% (99 / 153)      Ignored: none     

All files » app/mixins/main/service/configs/ » config_overridable.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508    1                                     1 1             1             3 3 3 3 3     3 1         1   2   1             1 1         2                             6 6   6 6     6 6 18 18     6 6 6   6                                   6                                                                                                         8 8 8 8 3 3 3 1 1 2 1 1       8 8                               6                                                 1 1           1                           1           1                   1                         3 3 3 3 3                                             1                                     1 1                 1   1             1         1                                     2 2                 2 2     2   2 2     2     2   2 2 2   2                                 1 1                                       1 1                   2 2 1 1   1                                     2 2               1 1 1 1   1     1     1 1                   2 2 2 2            
'use strict';
 
;require.register("mixins/main/service/configs/config_overridable", function (exports, require, module) {
  /**
   * 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.
   */
 
  var App = require('app');
  var validator = require('utils/validator');
 
  /**
   * Mixin with methods for config groups and overrides processing
   * Used in the installer step7, service configs page and others
   * @type {Em.Mixin}
   */
  App.ConfigOverridable = Em.Mixin.create({
 
    /**
     *
     * @method createOverrideProperty
     */
    createOverrideProperty: function createOverrideProperty(event) {
      var serviceConfigProperty = event.contexts[0];
      var serviceConfigController = this.get('isView') ? this.get('controller') : this;
      var selectedConfigGroup = serviceConfigController.get('selectedConfigGroup');
      var isInstaller = this.get('controller.name') === 'wizardStep7Controller';
      var configGroups = isInstaller ? serviceConfigController.get('selectedService.configGroups') : serviceConfigController.get('configGroups');
 
      //user property is added, and it has not been saved, not allow override
      if (serviceConfigProperty.get('isUserProperty') && serviceConfigProperty.get('isNotSaved') && !isInstaller) {
        App.ModalPopup.show({
          header: Em.I18n.t('services.service.config.configOverride.head'),
          body: Em.I18n.t('services.service.config.configOverride.body'),
          secondary: false
        });
        return;
      }
      if (selectedConfigGroup.get('isDefault')) {
        // Launch dialog to pick/create Config-group
        this.launchConfigGroupSelectionCreationDialog(this.get('service.serviceName'), configGroups, serviceConfigProperty, function (selectedGroupInPopup) {
          if (selectedGroupInPopup) {
            serviceConfigController.set('overrideToAdd', serviceConfigProperty);
            serviceConfigController.set('selectedConfigGroup', selectedGroupInPopup);
          }
        }, isInstaller);
      } else {
        var valueForOverride = serviceConfigProperty.get('widget') || serviceConfigProperty.get('displayType') == 'checkbox' ? serviceConfigProperty.get('value') : '';
        App.config.createOverride(serviceConfigProperty, {
          "value": valueForOverride,
          "isEditable": true
        }, selectedConfigGroup);
      }
      Em.$('body>.tooltip').remove();
    },
 
    /**
     * Open popup with list of config groups
     * User may select existing group or create a new one
     * @param {string} serviceId service name like 'HDFS', 'HBASE' etc
     * @param {App.ConfigGroup[]} configGroups
     * @param {App.ConfigProperty} configProperty
     * @param {Function} callback function called after config group is selected (or new one is created)
     * @param {Boolean} isInstaller determines if user is currently on the installer
     * @return {App.ModalPopup}
     * @method launchConfigGroupSelectionCreationDialog
     */
    launchConfigGroupSelectionCreationDialog: function launchConfigGroupSelectionCreationDialog(serviceId, configGroups, configProperty, callback, isInstaller) {
      var self = this;
      var availableConfigGroups = configGroups.slice();
      // delete Config Groups, that already have selected property overridden
      var alreadyOverriddenGroups = [];
      Iif (configProperty.get('overrides')) {
        alreadyOverriddenGroups = configProperty.get('overrides').mapProperty('group.name');
      }
      var result = [];
      availableConfigGroups.forEach(function (group) {
        Eif (!group.get('isDefault') && (!alreadyOverriddenGroups.length || !alreadyOverriddenGroups.contains(Em.get(group, 'name')))) {
          result.push(group);
        }
      }, this);
      availableConfigGroups = result;
      var selectedConfigGroup = availableConfigGroups && availableConfigGroups.length > 0 ? availableConfigGroups[0] : null;
      var serviceName = App.format.role(serviceId, true);
 
      return App.ModalPopup.show({
        classNames: ['common-modal-wrapper'],
        modalDialogClasses: ['modal-lg'],
        header: Em.I18n.t('config.group.selection.dialog.title').format(serviceName),
        subTitle: Em.I18n.t('config.group.selection.dialog.subtitle').format(serviceName),
        selectExistingGroupLabel: Em.I18n.t('config.group.selection.dialog.option.select').format(serviceName),
        noGroups: Em.I18n.t('config.group.selection.dialog.no.groups').format(serviceName),
        createNewGroupLabel: Em.I18n.t('config.group.selection.dialog.option.create').format(serviceName),
        createNewGroupDescription: Em.I18n.t('config.group.selection.dialog.option.create.msg').format(serviceName),
        warningMessage: ' ',
        isWarning: false,
        optionSelectConfigGroup: true,
        optionCreateConfigGroup: Em.computed.not('optionSelectConfigGroup'),
        hasExistedGroups: Em.computed.bool('availableConfigGroups.length'),
        availableConfigGroups: availableConfigGroups,
        selectedConfigGroup: selectedConfigGroup,
        newConfigGroupName: '',
        disablePrimary: function () {
          return !(this.get('optionSelectConfigGroup') || this.get('newConfigGroupName').trim().length > 0 && !this.get('isWarning'));
        }.property('newConfigGroupName', 'optionSelectConfigGroup', 'warningMessage'),
        onPrimary: function onPrimary() {
          var popup = this;
          if (this.get('optionSelectConfigGroup')) {
            var selectedConfigGroup = this.get('selectedConfigGroup');
            popup.hide();
            callback(selectedConfigGroup);
            if (!isInstaller) {
              App.get('router.mainServiceInfoConfigsController').doSelectConfigGroup({ context: selectedConfigGroup });
            }
          } else {
            var newConfigGroupName = this.get('newConfigGroupName').trim();
            var newConfigGroup = {
              id: new Date().getTime(),
              name: newConfigGroupName,
              is_default: false,
              parent_config_group_id: App.ServiceConfigGroup.getParentConfigGroupId(serviceId),
              description: Em.I18n.t('config.group.description.default').format(new Date().toDateString()),
              service_id: serviceId,
              service_name: serviceId,
              hosts: [],
              desired_configs: [],
              properties: []
            };
            if (!isInstaller) {
              self.postNewConfigurationGroup(newConfigGroup, function () {
                newConfigGroup = App.ServiceConfigGroup.find().filterProperty('serviceName', serviceId).findProperty('name', newConfigGroupName);
                self.saveGroupConfirmationPopup(newConfigGroupName);
                callback(newConfigGroup);
                popup.hide();
              });
            } else {
              newConfigGroup.is_temporary = true;
              App.store.safeLoad(App.ServiceConfigGroup, newConfigGroup);
              App.store.fastCommit();
              newConfigGroup = App.ServiceConfigGroup.find(newConfigGroup.id);
              configGroups.pushObject(newConfigGroup);
              self.persistConfigGroups();
              callback(newConfigGroup);
              popup.hide();
            }
          }
        },
        onSecondary: function onSecondary() {
          this.hide();
          callback(null);
        },
        doSelectConfigGroup: function doSelectConfigGroup(event) {
          var configGroup = event.context;
          this.set('selectedConfigGroup', configGroup);
        },
        validate: function () {
          var msg = ' ';
          var isWarning = false;
          var optionSelect = this.get('optionSelectConfigGroup');
          if (!optionSelect) {
            var nn = this.get('newConfigGroupName').trim();
            Eif (nn) {
              if (!validator.isValidConfigGroupName(nn)) {
                msg = Em.I18n.t("form.validator.configGroupName");
                isWarning = true;
              } else if (configGroups.mapProperty('name').contains(nn)) {
                msg = Em.I18n.t("config.group.selection.dialog.err.name.exists");
                isWarning = true;
              }
            }
          }
          this.set('warningMessage', msg);
          this.set('isWarning', isWarning);
        }.observes('newConfigGroupName', 'optionSelectConfigGroup'),
        bodyClass: Em.View.extend({
          templateName: require('templates/common/configs/selectCreateConfigGroup'),
          controllerBinding: 'App.router.mainServiceInfoConfigsController',
          selectConfigGroupRadioButton: App.RadioButtonView.extend({
            label: Em.computed.alias('parentView.parentView.selectExistingGroupLabel'),
            checked: Em.computed.alias('parentView.parentView.optionSelectConfigGroup'),
            disabled: Em.computed.not('parentView.parentView.hasExistedGroups'),
            click: function click() {
              if (this.get('disabled')) {
                return;
              }
              this.set('parentView.parentView.optionSelectConfigGroup', true);
            },
            didInsertElement: function didInsertElement() {
              Iif (!this.get('parentView.parentView.hasExistedGroups')) {
                this.set('parentView.parentView.optionSelectConfigGroup', false);
              }
            }
          }),
          createConfigGroupRadioButton: App.RadioButtonView.extend({
            label: Em.computed.alias('parentView.parentView.createNewGroupLabel'),
            checked: Em.computed.not('parentView.parentView.optionSelectConfigGroup'),
            click: function click() {
              this.set('parentView.parentView.optionSelectConfigGroup', false);
            }
          })
        })
      });
    },
 
    /**
     * Create a new config-group for a service.
     *
     * @param {object} newConfigGroupData config group to post to server
     * @param {Function} [callback] Callback function for Success or Error handling
     * @return {$.ajax}
     * @method postNewConfigurationGroup
     */
    postNewConfigurationGroup: function postNewConfigurationGroup(newConfigGroupData, callback) {
      var typeToPropertiesMap = {};
      newConfigGroupData.properties.forEach(function (property) {
        if (!typeToPropertiesMap[property.get('type')]) {
          typeToPropertiesMap[property.get('type')] = {};
        }
        typeToPropertiesMap[property.get('type')][property.get('name')] = property.get('value');
      });
      var newGroupData = {
        "ConfigGroup": {
          "group_name": newConfigGroupData.name,
          "tag": newConfigGroupData.service_id,
          "description": newConfigGroupData.description,
          "service_name": newConfigGroupData.service_id,
          "desired_configs": newConfigGroupData.desired_configs.map(function (cst) {
            var type = Em.get(cst, 'site') || Em.get(cst, 'type');
            return {
              type: type,
              properties: typeToPropertiesMap[type]
            };
          }),
          "hosts": newConfigGroupData.hosts.map(function (h) {
            return {
              host_name: h
            };
          })
        }
      };
      return App.ajax.send({
        name: 'config_groups.create',
        sender: this,
        data: {
          data: [newGroupData],
          modelData: newConfigGroupData
        },
        success: 'postNewConfigurationGroupSuccess',
        error: 'postNewConfigurationGroupError'
      }).always(function (xhr, text, errorThrown) {
        Iif (callback) {
          callback(xhr, text, errorThrown);
        }
      });
    },
 
    /**
     *
     * @param {string} response
     * @param {object} opt
     * @param {object} params
     */
    postNewConfigurationGroupSuccess: function postNewConfigurationGroupSuccess(response, opt, params) {
      var modelData = params.modelData;
      modelData.id = response.resources[0].ConfigGroup.id;
      App.store.safeLoad(App.ServiceConfigGroup, modelData);
      App.store.fastCommit();
      App.ServiceConfigGroup.deleteTemporaryRecords();
    },
 
    /**
     *
     * @param {object} xhr
     * @param {string} text
     * @param {Error} errorThrown
     */
    postNewConfigurationGroupError: Em.K,
 
    /**
     * PUTs the new configuration-group on the server.
     * Changes possible here are the name, description and
     * host memberships of the configuration-group.
     *
     * @param {App.ConfigGroup} configGroup Configuration group to update
     * @param {Function} successCallback
     * @param {Function} errorCallback
     * @return {$.ajax}
     * @method updateConfigurationGroup
     */
    updateConfigurationGroup: function updateConfigurationGroup(configGroup, successCallback, errorCallback) {
      var sendData = {
        name: 'config_groups.update',
        data: {
          id: configGroup.get('id'),
          data: this.getConfigGroupData(configGroup)
        },
        success: 'successFunction',
        error: 'errorFunction',
        successFunction: function successFunction() {
          if (successCallback) {
            successCallback();
          }
        },
        errorFunction: function errorFunction(xhr, text, errorThrown) {
          if (errorCallback) {
            errorCallback(xhr, text, errorThrown);
          }
        }
      };
      sendData.sender = sendData;
      return App.ajax.send(sendData);
    },
 
    /**
     *
     * @param {Em.Object} configGroup
     * @returns {{ConfigGroup: {group_name: *, description: *, tag: *, hosts: *, desired_configs: (Array|*)}}}
     */
    getConfigGroupData: function getConfigGroupData(configGroup) {
      var desiredConfigs = configGroup.get('desiredConfigs') || [];
 
      return {
        ConfigGroup: {
          group_name: configGroup.get('name'),
          description: configGroup.get('description'),
          tag: configGroup.get('service.id'),
          service_name: configGroup.get('service.id'),
          hosts: configGroup.get('hosts').map(function (h) {
            return {
              host_name: h
            };
          }),
          desired_configs: desiredConfigs.map(function (cst) {
            return {
              type: Em.get(cst, 'site') || Em.get(cst, 'type'),
              tag: Em.get(cst, 'tag')
            };
          })
        }
      };
    },
 
    /**
     * launch dialog where can be assigned another group to host
     * @param {App.ConfigGroup} selectedGroup
     * @param {App.ConfigGroup[]} configGroups
     * @param {String} hostName
     * @param {Function} callback
     * @return {App.ModalPopup}
     * @method launchSwitchConfigGroupOfHostDialog
     */
    launchSwitchConfigGroupOfHostDialog: function launchSwitchConfigGroupOfHostDialog(selectedGroup, configGroups, hostName, callback) {
      var self = this;
      return App.ModalPopup.show({
        classNames: ['change-config-group-modal'],
        header: Em.I18n.t('config.group.host.switch.dialog.title'),
        configGroups: configGroups,
        selectedConfigGroup: selectedGroup,
        disablePrimary: function () {
          return this.get('selectedConfigGroup.name') === selectedGroup.get('name');
        }.property('selectedConfigGroup.name'),
        onPrimary: function onPrimary() {
          var newGroup = this.get('selectedConfigGroup');
          Iif (selectedGroup.get('isDefault')) {
            selectedGroup.set('hosts.length', selectedGroup.get('hosts.length') - 1);
          } else {
            selectedGroup.get('hosts').removeObject(hostName);
          }
          Eif (!selectedGroup.get('isDefault')) {
            self.updateConfigurationGroup(selectedGroup, Em.K, Em.K);
          }
 
          Iif (newGroup.get('isDefault')) {
            newGroup.set('hosts.length', newGroup.get('hosts.length') + 1);
          } else {
            newGroup.get('hosts').pushObject(hostName);
          }
          callback(newGroup);
          Eif (!newGroup.get('isDefault')) {
            self.updateConfigurationGroup(newGroup, Em.K, Em.K);
          }
          this.hide();
        },
        bodyClass: Em.View.extend({
          templateName: require('templates/utils/config_launch_switch_config_group_of_host')
        })
      });
    },
 
    /**
     * Do request to delete config group
     * @param {App.ConfigGroup} configGroup
     * @param {Function} [successCallback]
     * @param {Function} [errorCallback]
     * @return {$.ajax}
     * @method deleteConfigurationGroup
     */
    deleteConfigurationGroup: function deleteConfigurationGroup(configGroup, successCallback, errorCallback) {
      var self = this;
      var sendData = {
        name: 'common.delete.config_group',
        sender: this,
        data: {
          id: configGroup.get('id')
        },
        success: 'successFunction',
        error: 'errorFunction',
        successFunction: function successFunction(data, xhr, params) {
          self.deleteConfigurationGroupSuccess(data, xhr, params);
          if (successCallback) {
            successCallback();
          }
        },
        errorFunction: function errorFunction(xhr, text, errorThrown) {
          if (errorCallback) {
            errorCallback(xhr, text, errorThrown);
          }
        }
      };
      sendData.sender = sendData;
      return App.ajax.send(sendData);
    },
 
    /**
     *
     * @param {object} data
     * @param {object} xhr
     * @param {object} params
     */
    deleteConfigurationGroupSuccess: function deleteConfigurationGroupSuccess(data, xhr, params) {
      var groupFromModel = App.ServiceConfigGroup.find().findProperty('id', params.id);
      if (groupFromModel) {
        Eif (groupFromModel.get('stateManager.currentState.name') !== 'saved') {
          groupFromModel.get('stateManager').transitionTo('loaded');
        }
        App.configGroupsMapper.deleteRecord(groupFromModel);
      }
    },
 
    /**
     * Launches a dialog where an existing config-group can be selected, or a new
     * one can be created. This is different than the config-group management
     * dialog where host membership can be managed.
     *
     * The callback will be passed the created/selected config-group in the form
     * of {id:2, name:'New hardware group'}. In the case of dialog being cancelled,
     * the callback is provided <code>null</code>
     *
     * @param {String} groupName
     *  is closed, cancelled or OK is pressed.
     * @return {App.ModalPopup}
     * @method saveGroupConfirmationPopup
     */
    saveGroupConfirmationPopup: function saveGroupConfirmationPopup(groupName) {
      var self = this;
      return App.ModalPopup.show({
        header: Em.I18n.t('config.group.save.confirmation.header'),
        secondary: Em.I18n.t('config.group.save.confirmation.manage.button'),
        groupName: groupName,
        bodyClass: Em.View.extend({
          templateName: require('templates/common/configs/saveConfigGroup')
        }),
        onPrimary: function onPrimary() {
          Eif (self.get('controller.name') === 'mainServiceInfoConfigsController') {
            self.get('controller').loadConfigGroups([self.get('controller.content.serviceName')]).done(function () {
              var group = App.ServiceConfigGroup.find().find(function (g) {
                return g.get('serviceName') === self.get('controller.content.serviceName') && g.get('name') === groupName;
              });
              self.get('controller').doSelectConfigGroup({ context: group });
            });
          }
          this._super();
        },
        onSecondary: function onSecondary() {
          App.router.get('manageConfigGroupsController').manageConfigurationGroups(null, self.get('controller.content'));
          this.hide();
        }
      });
    },
 
    /**
     * Persist config groups created in step7 wizard controller
     * @method persistConfigGroups
     */
    persistConfigGroups: function persistConfigGroups() {
      var installerController = App.router.get('installerController');
      var step7Controller = App.router.get('wizardStep7Controller');
      installerController.saveServiceConfigGroups(step7Controller, step7Controller.get('content.controllerName') === 'addServiceController');
      App.clusterStatus.setClusterStatus({
        localdb: App.db.data
      });
    }
 
  });
});