summaryrefslogtreecommitdiff
path: root/horizon/static/horizon/js/angular/services/hz.api.config.js
blob: e7315ef7a9ba3d5dd5a72a1bdcdc1f122d3d6f1a (plain)
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
/*
 * Copyright 2015 IBM Corp
 * (c) Copyright 2015 Hewlett-Packard Development Company, L.P.
 *
 * Licensed 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.
 */
(function () {
  'use strict';

  /**
   * @ngdoc service
   * @name hz.api.configAPI
   * @description Provides access to dashboard configuration.
   */
  function ConfigAPI(apiService) {

    /**
     * @name hz.api.configAPI.getUserDefaults
     * @description
     * Get the default user configuration settings.
     *
     * Returns an object with user configuration settings.
     */
    this.getUserDefaults = function() {
      return apiService.get('/api/config/user/')
        .success(function(data) {
          // store config in localStorage
          // should be call only when defaults are needed
          // or when user wants to reset it
          localStorage.user_config = angular.toJson(data);
        })
        .error(function () {
          horizon.alert('error', gettext('Unable to retrieve user configuration.'));
        });
    };

    /**
     * @name hz.api.configAPI.getAdminDefaults
     * @description
     * Get the default admin configuration settings.
     *
     * Returns an object with admin configuration settings.
     */
    this.getAdminDefaults = function(params) {
      return apiService.get('/api/config/admin/')
        .success(function(data) {
          // store this in localStorage
          // should be call once each page load
          localStorage.admin_config = angular.toJson(data);
        })
        .error(function () {
          horizon.alert('error', gettext('Unable to retrieve admin configuration.'));
        });
    };

  }

  // Register it with the API module so that anybody using the
  // API module will have access to the Config APIs.
  angular.module('hz.api')
    .service('configAPI', ['apiService', ConfigAPI]);

  /**
   * @ngdoc service
   * @name hz.api.settingsService
   * @description
   * Provides utilities to the cached settings data. This helps
   * with asynchronous data loading.
   *
   * The cache in current horizon (Kilo non-single page app) only has a
   * lifetime of the current page. The cache is reloaded every time you change
   * panels. It also happens when you change the region selector at the top
   * of the page, and when you log back in.
   *
   * So, at least for now, this seems to be a reliable way that will
   * make only a single request to get user information for a
   * particular page or modal. Making this a service allows it to be injected
   * and used transparently where needed without making every single use of it
   * pass it through as an argument.
   */
  function settingsService($q, apiService) {

    var service = {};

     /**
     * @name hz.api.configAPI.getSettings
     * @description
     * Gets all the allowed settings
     *
     * Returns an object with settings.
     */
     service.getSettings = function (suppressError) {

       function onError() {
         var message = gettext('Unable to retrieve settings.');
         if (!suppressError && horizon.alert) {
           horizon.alert('error', message);
         }

         return message;
       }

       // The below ensures that errors are handled like other
       // service errors (for better or worse), but when successful
       // unwraps the success result data for direct consumption.
       return apiService.get('/api/settings/', {cache: true})
         .error(onError)
         .then(function (response) {
           return response.data;
         });
     };

    /**
     * @name hz.api.settingsService.getSetting
     * @description
     * This retrieves a specific setting.
     *
     * If the setting isn't found, it will return undefined unless a default
     * is specified. In that case, the default will be returned.
     *
     * @param {string} setting The path to the setting to get.
     *
     * local_settings.py allows you to create settings such as:
     *
     * OPENSTACK_HYPERVISOR_FEATURES = {
     *    'can_set_mount_point': True,
     *    'can_set_password': False,
     * }
     *
     * To access a specific setting, use a simplified path where a . (dot)
     * separates elements in the path.  So in the above example, the paths
     * would be:
     *
     * OPENSTACK_HYPERVISOR_FEATURES.can_set_mount_point
     * OPENSTACK_HYPERVISOR_FEATURES.can_set_password
     *
     * @param {object=} defaultSetting If the requested setting does not exist,
     * the defaultSetting will be returned. This is optional.
     *
     * @example
     *
     * Using the OPENSTACK_HYPERVISOR_FEATURES mentioned above, the following
     * would call doSomething and pass the setting value into doSomething.
     *
     ```js
        settingsService.getSetting('OPENSTACK_HYPERVISOR_FEATURES.can_set_mount_point')
          .then(doSomething);
     ```
     */
    service.getSetting = function (path, defaultSetting) {
      var deferred = $q.defer(),
          pathElements = path.split("."),
          settingAtRequestedPath;

      function onSettingsLoaded(settings) {
        // This recursively traverses the object hierarchy until either all the
        // path elements are traversed or until the next element in the path
        // does not have the requested child object.
        settingAtRequestedPath = pathElements.reduce(
          function (setting, nextPathElement) {
            return setting ? setting[nextPathElement] : undefined;
          }, settings);

        if (typeof settingAtRequestedPath === "undefined" &&
          (typeof defaultSetting !== "undefined")) {
          settingAtRequestedPath = defaultSetting;
        }

        deferred.resolve(settingAtRequestedPath);
      }

      function onSettingsFailure(message) {
        deferred.reject(message);
      }

      service.getSettings()
        .then(onSettingsLoaded, onSettingsFailure);

      return deferred.promise;
    };

    /**
     * @name hz.api.settingsService.ifEnabled
     * @description
     * Checks if the desired setting is enabled. This returns a promise.
     * If the setting is enabled, the promise will be resolved.
     * If it is not enabled, the promise will be rejected. Use it like you
     * would normal promises.
     *
     * @param {string} setting The path to the setting to check.
     * local_settings.py allows you to create settings such as:
     *
     * OPENSTACK_HYPERVISOR_FEATURES = {
     *    'can_set_mount_point': True,
     *    'can_set_password': False,
     * }
     *
     * To access a specific setting, use a simplified path where a . (dot)
     * separates elements in the path.  So in the above example, the paths
     * would be:
     *
     * OPENSTACK_HYPERVISOR_FEATURES.can_set_mount_point
     * OPENSTACK_HYPERVISOR_FEATURES.can_set_password
     *
     * @param (object=} expected Used to determine if the setting is
     * enabled. The actual setting will be evaluated against the expected
     * value using angular.equals(). If they are equal, then it will be
     * considered enabled. This is optional and defaults to True.
     *
     * @param {object=} defaultSetting If the requested setting does not exist,
     * the defaultSetting will be used for evaluation. This is optional. If
     * not specified and the setting is not specified, then the setting will
     * not be considered to be enabled.
     *
     * @example
     * Simple true / false example:
     *
     * Using the OPENSTACK_HYPERVISOR_FEATURES mentioned above, the following
     * would call the "setMountPoint" function only if
     * OPENSTACK_HYPERVISOR_FEATURES.can_set_mount_point is set to true.
     *
     ```js
        settingsService.ifEnabled('OPENSTACK_HYPERVISOR_FEATURES.can_set_mount_point')
          .then(setMountPoint);
     ```
     *
     * Evaluating other types of settings:
     *
     * local_settings.py allows you optionally set the enabled OpenStack
     * Service API versions with the following setting:
     *
     *  OPENSTACK_API_VERSIONS = {
     *     "data-processing": 1.1,
     *     "identity": 3,
     *     "volume": 2,
     * }
     *
     * The above is a nested object structure. The simplified path to the
     * volume service version is OPENSTACK_API_VERSIONS.volume
     *
     * It is not uncommon for different OpenStack deployments to have
     * different versions of the service enabled for various reasons.
     *
     * So, now, assume that if version 2 of the volume service (Cinder) is
     * enabled that you want to do something.  If it isn't, then you will do
     * something else.
     *
     * Assume doSomethingIfVersion2 is a function you want to call if version 2
     * is enabled.
     *
     * Assume doSomethingElse is a function that does something else if
     * version 2 is not enabled (optional)
     *
     ```js
        settingsService.ifEnabled('OPENSTACK_API_VERSIONS.volume', 2)
          .then(doSomethingIfVersion2, doSomethingElse);
     ```
     *
     * Now assume that if nothing is set in local_settings, that you want to
     * treat the result as if version 1 is enabled (default when nothing set).
     *
     ```js
        settingsService.ifEnabled('OPENSTACK_API_VERSIONS.volume', 2, 1)
          .then(doSomethingIfVersion2, doSomethingElse);
     ```
     */
    service.ifEnabled = function (setting, expected, defaultSetting) {
      var deferred = $q.defer();

      // If expected is not defined, we default to expecting the setting
      // to be 'true' in order for it to be considered enabled.
      expected = (typeof expected === "undefined") ? true : expected;

      function onSettingLoaded(setting) {
        if (angular.equals(expected, setting)) {
          deferred.resolve();
        } else {
          deferred.reject(interpolate(
            gettext('Setting is not enabled: %(setting)s'),
            {setting: setting},
            true));
        }

        deferred.resolve(setting);
      }

      function onSettingFailure(message) {
        deferred.reject(message);
      }

      service.getSetting(setting, defaultSetting)
        .then(onSettingLoaded, onSettingFailure);

      return deferred.promise;
    };

    return service;
  }

  angular.module('hz.api')
    .factory('settingsService', ['$q', 'apiService', settingsService]);

}());