Browse Source

AMBARI-6381. Make appropriate changes for GET requests that we will send as POST with custom header. (onechiporenko)

Oleg Nechiporenko 11 years ago
parent
commit
c5e04983ae

+ 48 - 19
ambari-web/app/controllers/global/update_controller.js

@@ -48,8 +48,8 @@ App.UpdateController = Em.Controller.extend({
    * @return {String}
    * @return {String}
    */
    */
   getComplexUrl: function (testUrl, realUrl, queryParams) {
   getComplexUrl: function (testUrl, realUrl, queryParams) {
-    var prefix = App.apiPrefix + '/clusters/' + App.get('clusterName');
-    var params = '';
+    var prefix = App.get('apiPrefix') + '/clusters/' + App.get('clusterName'),
+      params = '';
 
 
     if (App.get('testMode')) {
     if (App.get('testMode')) {
       return testUrl;
       return testUrl;
@@ -146,8 +146,9 @@ App.UpdateController = Em.Controller.extend({
   },
   },
 
 
   updateHost: function (callback, error) {
   updateHost: function (callback, error) {
-    var testUrl = App.get('isHadoop2Stack') ? '/data/hosts/HDP2/hosts.json' : '/data/hosts/hosts.json';
-    var self = this;
+    var testUrl = App.get('isHadoop2Stack') ? '/data/hosts/HDP2/hosts.json' : '/data/hosts/hosts.json',
+      self = this,
+      p = '';
     var realUrl = '/hosts?<parameters>fields=Hosts/host_name,Hosts/maintenance_state,Hosts/public_host_name,Hosts/cpu_count,Hosts/ph_cpu_count,Hosts/total_mem,' +
     var realUrl = '/hosts?<parameters>fields=Hosts/host_name,Hosts/maintenance_state,Hosts/public_host_name,Hosts/cpu_count,Hosts/ph_cpu_count,Hosts/total_mem,' +
       'Hosts/host_status,Hosts/last_heartbeat_time,Hosts/os_arch,Hosts/os_type,Hosts/ip,host_components/HostRoles/state,host_components/HostRoles/maintenance_state,' +
       'Hosts/host_status,Hosts/last_heartbeat_time,Hosts/os_arch,Hosts/os_type,Hosts/ip,host_components/HostRoles/state,host_components/HostRoles/maintenance_state,' +
       'host_components/HostRoles/stale_configs,host_components/HostRoles/service_name,metrics/disk,metrics/load/load_one,metrics/cpu/cpu_system,metrics/cpu/cpu_user,' +
       'host_components/HostRoles/stale_configs,host_components/HostRoles/service_name,metrics/disk,metrics/load/load_one,metrics/cpu/cpu_system,metrics/cpu/cpu_user,' +
@@ -155,17 +156,24 @@ App.UpdateController = Em.Controller.extend({
 
 
     if (App.router.get('currentState.name') == 'index' && App.router.get('currentState.parentState.name') == 'hosts') {
     if (App.router.get('currentState.name') == 'index' && App.router.get('currentState.parentState.name') == 'hosts') {
       App.updater.updateInterval('updateHost', App.get('contentUpdateInterval'));
       App.updater.updateInterval('updateHost', App.get('contentUpdateInterval'));
-    } else if(App.router.get('currentState.name') == 'summary' && App.router.get('currentState.parentState.name') == 'hostDetails') {
-      realUrl = realUrl.replace('<parameters>', 'Hosts/host_name=' + App.router.get('location.lastSetURL').match(/\/hosts\/(.*)\/summary/)[1] + '&');
-      App.updater.updateInterval('updateHost', App.get('componentsUpdateInterval'));
-    } else {
-      callback();
-      // On pages except for hosts/hostDetails, making sure hostsMapper loaded only once on page load, no need to update, but at least once
-      if (this.get('queryParams.Hosts') && this.get('queryParams.Hosts').length > 0) {
-        return;
+    }
+    else {
+      if(App.router.get('currentState.name') == 'summary' && App.router.get('currentState.parentState.name') == 'hostDetails') {
+        p = 'Hosts/host_name=' + App.router.get('location.lastSetURL').match(/\/hosts\/(.*)\/summary/)[1] + '&';
+        App.updater.updateInterval('updateHost', App.get('componentsUpdateInterval'));
+      }
+      else {
+        callback();
+        // On pages except for hosts/hostDetails, making sure hostsMapper loaded only once on page load, no need to update, but at least once
+        if (this.get('queryParams.Hosts') && this.get('queryParams.Hosts').length > 0) {
+          return;
+        }
       }
       }
     }
     }
-    this.get('queryParams').set('Hosts', App.router.get('mainHostController').getQueryParameters());
+    var mainHostController = App.router.get('mainHostController'),
+      viewProperties = mainHostController.getViewProperties(),
+      sortProperties = mainHostController.getSortProperties();
+    this.get('queryParams').set('Hosts', mainHostController.getQueryParameters(true));
     var clientCallback = function (skipCall, queryParams) {
     var clientCallback = function (skipCall, queryParams) {
       if (skipCall) {
       if (skipCall) {
         //no hosts match filter by component
         //no hosts match filter by component
@@ -174,12 +182,33 @@ App.UpdateController = Em.Controller.extend({
           itemTotal: '0'
           itemTotal: '0'
         });
         });
         callback();
         callback();
-      } else {
-        var hostsUrl = self.getComplexUrl(testUrl, realUrl, queryParams);
-        App.HttpClient.get(hostsUrl, App.hostsMapper, {
-          complete: callback,
-          error: error
-        });
+      }
+      else {
+        var params = p + self.computeParameters(queryParams),
+          viewProps = self.computeParameters(viewProperties),
+          sortProps = self.computeParameters(sortProperties);
+        if (!viewProps.length) viewProps = '&';
+        if (!sortProps.length) sortProps = '&';
+        if ((params.length + viewProps.length + sortProps.length) > 0) {
+          realUrl = App.get('apiPrefix') + '/clusters/' + App.get('clusterName') +
+            realUrl.replace('<parameters>', '') + '&' +
+            viewProps.substring(0, viewProps.length - 1) + '&' +
+            sortProps.substring(0, sortProps.length - 1);
+          App.HttpClient.get(realUrl, App.hostsMapper, {
+            complete: callback,
+            doGetAsPost: true,
+            params: params.substring(0, params.length - 1),
+            error: error
+          });
+        }
+        else {
+          var hostsUrl = self.getComplexUrl(testUrl, realUrl, queryParams);
+          App.HttpClient.get(hostsUrl, App.hostsMapper, {
+            complete: callback,
+            doGetAsPost: false,
+            error: error
+          });
+        }
       }
       }
     };
     };
 
 

+ 54 - 25
ambari-web/app/controllers/main/host.js

@@ -218,26 +218,62 @@ App.MainHostController = Em.ArrayController.extend({
   },
   },
 
 
   /**
   /**
-   * get query parameters computed from filter properties, sort properties and custom properties of view
-   * @return {Array}
+   * Transform <code>viewProperties</code> to queryParameters
+   * @returns {Object[]}
+   * @method getViewProperties
    */
    */
-  getQueryParameters: function () {
-    var queryParams = [];
-    var savedFilterConditions = App.db.getFilterConditions(this.get('name')) || [];
-    var savedSortConditions = App.db.getSortingStatuses(this.get('name')) || [];
-    var colPropAssoc = this.get('colPropAssoc');
-    var filterProperties = this.get('filterProperties');
-    var sortProperties = this.get('sortProps');
-    var oldProperties = App.router.get('updateController.queryParams.Hosts');
-
-    this.set('resetStartIndex', false);
-    this.get('viewProperties').forEach(function (property) {
-      queryParams.push({
+  getViewProperties: function() {
+    return this.get('viewProperties').map(function (property) {
+      return {
         key: property.get('alias'),
         key: property.get('alias'),
         value: property.getValue(this),
         value: property.getValue(this),
         type: 'EQUAL'
         type: 'EQUAL'
-      })
+      };
     }, this);
     }, this);
+  },
+
+  /**
+   * Transform <code>sortProps</code> to queryParameters
+   * @returns {Object[]}
+   * @method getSortProperties
+   */
+  getSortProperties: function() {
+    var savedSortConditions = App.db.getSortingStatuses(this.get('name')) || [],
+      sortProperties = this.get('sortProps'),
+      queryParams = [];
+    savedSortConditions.forEach(function (sort) {
+      var property = sortProperties.findProperty('key', sort.name);
+
+      if (property && (sort.status === 'sorting_asc' || sort.status === 'sorting_desc')) {
+        queryParams.push({
+          key: property.alias,
+          value: sort.status.replace('sorting_', ''),
+          type: 'SORT'
+        });
+      }
+    });
+    return queryParams;
+  },
+
+  /**
+   * get query parameters computed from filter properties, sort properties and custom properties of view
+   * @return {Array}
+   * @method getQueryParameters
+   */
+  getQueryParameters: function (skipNonFilterProperties) {
+    skipNonFilterProperties = skipNonFilterProperties || false;
+    var queryParams = [],
+      savedFilterConditions = App.db.getFilterConditions(this.get('name')) || [],
+      savedSortConditions = App.db.getSortingStatuses(this.get('name')) || [],
+      colPropAssoc = this.get('colPropAssoc'),
+      filterProperties = this.get('filterProperties'),
+      sortProperties = this.get('sortProps'),
+      oldProperties = App.router.get('updateController.queryParams.Hosts');
+
+    this.set('resetStartIndex', false);
+
+    queryParams.pushObjects(this.getViewProperties());
+
     savedFilterConditions.forEach(function (filter) {
     savedFilterConditions.forEach(function (filter) {
       var property = filterProperties.findProperty('key', colPropAssoc[filter.iColumn]);
       var property = filterProperties.findProperty('key', colPropAssoc[filter.iColumn]);
       if (property && filter.value.length > 0 && !filter.skipFilter) {
       if (property && filter.value.length > 0 && !filter.skipFilter) {
@@ -290,17 +326,10 @@ App.MainHostController = Em.ArrayController.extend({
         }
         }
       }, this);
       }, this);
     }
     }
-    savedSortConditions.forEach(function (sort) {
-      var property = sortProperties.findProperty('key', sort.name);
 
 
-      if (property && (sort.status === 'sorting_asc' || sort.status === 'sorting_desc')) {
-        queryParams.push({
-          key: property.alias,
-          value: sort.status.replace('sorting_', ''),
-          type: 'SORT'
-        });
-      }
-    });
+    if (!skipNonFilterProperties) {
+      queryParams.pushObjects(this.getSortProperties());
+    }
 
 
     return queryParams;
     return queryParams;
   },
   },

+ 23 - 11
ambari-web/app/utils/ajax/ajax.js

@@ -1102,7 +1102,7 @@ var urls = {
         type: 'PUT',
         type: 'PUT',
         data: data.data
         data: data.data
       };
       };
-      if (App.testMode) {
+      if (App.get('testMode')) {
         d.type = 'GET';
         d.type = 'GET';
       }
       }
       return d;
       return d;
@@ -1116,7 +1116,7 @@ var urls = {
         type: 'PUT',
         type: 'PUT',
         data: data.data
         data: data.data
       };
       };
-      if (App.testMode) {
+      if (App.get('testMode')) {
         d.type = 'GET';
         d.type = 'GET';
       }
       }
       return d;
       return d;
@@ -1802,12 +1802,18 @@ var urls = {
     'mock': ''
     'mock': ''
   },
   },
   'host.host_components.filtered': {
   'host.host_components.filtered': {
-    'real': '/clusters/{clusterName}/hosts',
+    'real': '/clusters/{clusterName}/hosts?{fields}',
     'mock': '',
     'mock': '',
-    format: function(data, opt) {
+    format: function(data) {
       return {
       return {
-        url: opt.url + data.urlParams
-      }
+        headers: {
+          'X-Http-Method-Override': 'GET'
+        },
+        type: 'POST',
+        data: JSON.stringify({
+          "RequestInfo": {"query" : data.parameters}
+        })
+      };
     }
     }
   },
   },
   'host.status.counters': {
   'host.status.counters': {
@@ -1952,11 +1958,19 @@ var urls = {
     }
     }
   },
   },
   'hosts.bulk.operations': {
   'hosts.bulk.operations': {
-    real: '',
+    real: '/clusters/{clusterName}/hosts?fields=Hosts/host_name,Hosts/maintenance_state,' +
+      'host_components/HostRoles/state,host_components/HostRoles/maintenance_state,' +
+      'host_components/HostRoles/stale_configs&minimal_response=true',
     mock: '',
     mock: '',
     format: function(data) {
     format: function(data) {
       return {
       return {
-        url: data.url
+        headers: {
+          'X-Http-Method-Override': 'GET'
+        },
+        type: 'POST',
+        data: JSON.stringify({
+          "RequestInfo": {"query" : data.parameters }
+        })
       }
       }
     }
     }
   }
   }
@@ -1999,7 +2013,7 @@ var formatRequest = function (data) {
     dataType: 'json',
     dataType: 'json',
     statusCode: require('data/statusCodes')
     statusCode: require('data/statusCodes')
   };
   };
-  if (App.testMode) {
+  if (App.get('testMode')) {
     opt.url = formatUrl(this.mock ? this.mock : '', data);
     opt.url = formatUrl(this.mock ? this.mock : '', data);
     opt.type = 'GET';
     opt.type = 'GET';
   }
   }
@@ -2037,8 +2051,6 @@ var ajax = Em.Object.extend({
    */
    */
   send: function (config) {
   send: function (config) {
 
 
-    console.warn('============== ajax ==============', config.name, config.data);
-
     if (!config.sender) {
     if (!config.sender) {
       console.warn('Ajax sender should be defined!');
       console.warn('Ajax sender should be defined!');
       return null;
       return null;

+ 25 - 23
ambari-web/app/utils/batch_scheduled_requests.js

@@ -99,22 +99,22 @@ module.exports = {
   /**
   /**
    * construct URL from parameters for request in <code>getComponentsFromServer()</code>
    * construct URL from parameters for request in <code>getComponentsFromServer()</code>
    * @param options
    * @param options
-   * @return {String}
+   * @return {{fields: string, params: string}}
    */
    */
   constructComponentsCallUrl: function (options) {
   constructComponentsCallUrl: function (options) {
     var multipleValueParams = {
     var multipleValueParams = {
-      'services': 'host_components/HostRoles/service_name.in(<entity-names>)',
-      'hosts': 'Hosts/host_name.in(<entity-names>)',
-      'components': 'host_components/HostRoles/component_name.in(<entity-names>)'
-    };
-    var singleValueParams = {
-      staleConfigs: 'host_components/HostRoles/stale_configs=',
-      passiveState: 'Hosts/maintenance_state=',
-      workStatus: 'host_components/HostRoles/state='
-    };
-    var displayParams = options.displayParams || [];
-    var urlParams = '?';
-    var addAmpersand = false;
+        'services': 'host_components/HostRoles/service_name.in(<entity-names>)',
+        'hosts': 'Hosts/host_name.in(<entity-names>)',
+        'components': 'host_components/HostRoles/component_name.in(<entity-names>)'
+      },
+      singleValueParams = {
+        staleConfigs: 'host_components/HostRoles/stale_configs=',
+        passiveState: 'Hosts/maintenance_state=',
+        workStatus: 'host_components/HostRoles/state='
+      },
+      displayParams = options.displayParams || [],
+      urlParams = '',
+      addAmpersand = false;
 
 
     for (var i in multipleValueParams) {
     for (var i in multipleValueParams) {
       var arrayParams = options[i];
       var arrayParams = options[i];
@@ -136,17 +136,19 @@ module.exports = {
         addAmpersand = true;
         addAmpersand = true;
       }
       }
     }
     }
-
+    var params = urlParams,
+      fields = '';
     displayParams.forEach(function (displayParam, index, array) {
     displayParams.forEach(function (displayParam, index, array) {
       if (index === 0) {
       if (index === 0) {
-        urlParams += (addAmpersand) ? '&' : '';
-        urlParams += 'fields=';
+        fields += (addAmpersand) ? '&' : '';
+        fields += 'fields=';
       }
       }
-      urlParams += displayParam;
-      urlParams += (array.length === (index + 1)) ? '' : ",";
+      fields += displayParam;
+      fields += (array.length === (index + 1)) ? '' : ",";
     });
     });
+    fields += '&minimal_response=true';
 
 
-    return urlParams + '&minimal_response=true';
+    return {fields: fields.substring(1, fields.length), params: params};
   },
   },
 
 
   /**
   /**
@@ -156,13 +158,13 @@ module.exports = {
    * @param callback
    * @param callback
    */
    */
   getComponentsFromServer: function (options, callback) {
   getComponentsFromServer: function (options, callback) {
-    var urlParams = this.constructComponentsCallUrl(options);
-
-    App.ajax.send({
+    var request_parameters = this.constructComponentsCallUrl(options);
+    return App.ajax.send({
       name: 'host.host_components.filtered',
       name: 'host.host_components.filtered',
       sender: this,
       sender: this,
       data: {
       data: {
-        urlParams: urlParams,
+        parameters: request_parameters.params,
+        fields: request_parameters.fields,
         callback: callback
         callback: callback
       },
       },
       success: 'getComponentsFromServerSuccessCallback'
       success: 'getComponentsFromServerSuccessCallback'

+ 48 - 14
ambari-web/app/utils/http_client.js

@@ -33,12 +33,12 @@ App.HttpClient = Em.Object.create({
   defaultErrorHandler: function (jqXHR, textStatus, errorThrown, url) {
   defaultErrorHandler: function (jqXHR, textStatus, errorThrown, url) {
     try {
     try {
       var json = $.parseJSON(jqXHR.responseText);
       var json = $.parseJSON(jqXHR.responseText);
-    } catch (err) {
-    }
+    } catch (err) { }
     App.ajax.defaultErrorHandler(jqXHR, url);
     App.ajax.defaultErrorHandler(jqXHR, url);
     if (json) {
     if (json) {
       Em.assert("HttpClient:", json);
       Em.assert("HttpClient:", json);
-    } else {
+    }
+    else {
       if (!$.mocho) { // don't use this assert on tests
       if (!$.mocho) { // don't use this assert on tests
         Em.assert("HttpClient:", errorThrown);
         Em.assert("HttpClient:", errorThrown);
       }
       }
@@ -66,6 +66,34 @@ App.HttpClient = Em.Object.create({
     this.onReady(xhr, "", ajaxOptions, mapper, errorHandler, url);
     this.onReady(xhr, "", ajaxOptions, mapper, errorHandler, url);
   },
   },
 
 
+  /**
+   * Do POST-request equal to GET-request but with some params put to body
+   * @param {string} url
+   * @param {{params: string, success: callback, error: callback}} ajaxOptions
+   * @param {App.QuickDataMapper} mapper
+   * @param errorHandler
+   * @method getAsPostRequest
+   */
+  getAsPostRequest: function (url, ajaxOptions, mapper, errorHandler) {
+
+    if (!errorHandler) {
+      errorHandler = this.defaultErrorHandler;
+    }
+
+    var xhr = new XMLHttpRequest(),
+      curTime = App.dateTime(),
+      params = JSON.stringify({
+        "RequestInfo": {"query" : ajaxOptions.params }
+      });
+
+    xhr.open('POST', url + (url.indexOf('?') >= 0 ? '&_=' : '?_=') + curTime, true);
+    xhr.setRequestHeader("X-Http-Method-Override", "GET");
+    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
+    xhr.send(params);
+
+    this.onReady(xhr, "", ajaxOptions, mapper, errorHandler, url);
+  },
+
   /*
   /*
    This function checks if we get response from server
    This function checks if we get response from server
    Not using onreadystatechange cuz of possible closure
    Not using onreadystatechange cuz of possible closure
@@ -92,8 +120,8 @@ App.HttpClient = Em.Object.create({
         xhr = null;
         xhr = null;
         clearTimeout(timeout);
         clearTimeout(timeout);
         timeout = null;
         timeout = null;
-
-      } else {
+      }
+      else {
         self.onReady(xhr, timeout, tmp_val, mapper, errorHandler, url);
         self.onReady(xhr, timeout, tmp_val, mapper, errorHandler, url);
       }
       }
     }, 10);
     }, 10);
@@ -110,19 +138,25 @@ App.HttpClient = Em.Object.create({
     if (!errorHandler && data.error) {
     if (!errorHandler && data.error) {
       errorHandler = data.error;
       errorHandler = data.error;
     }
     }
-    var client = this;
-    var request = function () {
-      client.request(url, data, mapper, errorHandler);
-      url = null;
-      data = null;
-      mapper = null;
-      errorHandler = null;
-    };
+    var client = this,
+      request = function () {
+        if (data.doGetAsPost) {
+          client.getAsPostRequest(url, data, mapper, errorHandler);
+        }
+        else {
+          client.request(url, data, mapper, errorHandler);
+        }
+        url = null;
+        data = null;
+        mapper = null;
+        errorHandler = null;
+      };
 
 
     interval = "" + interval;
     interval = "" + interval;
     if (interval.match(/\d+/)) {
     if (interval.match(/\d+/)) {
       $.periodic({period: interval}, request);
       $.periodic({period: interval}, request);
-    } else {
+    }
+    else {
       request();
       request();
     }
     }
   },
   },

+ 10 - 15
ambari-web/app/views/main/host.js

@@ -200,10 +200,11 @@ App.MainHostView = App.TableView.extend(App.TableServerProvider, {
 
 
   /**
   /**
    * get query parameters computed in controller
    * get query parameters computed in controller
+   * @param {bool} flag should non-filters params be skipped
    * @return {Array}
    * @return {Array}
    */
    */
-  getQueryParameters: function () {
-    return this.get('controller').getQueryParameters();
+  getQueryParameters: function (flag) {
+    return this.get('controller').getQueryParameters(flag);
   },
   },
   /**
   /**
    * stub for filter function in TableView
    * stub for filter function in TableView
@@ -356,11 +357,7 @@ App.MainHostView = App.TableView.extend(App.TableServerProvider, {
    */
    */
   bulkOperationConfirm: function(operationData, selection) {
   bulkOperationConfirm: function(operationData, selection) {
     var hostsNames = [],
     var hostsNames = [],
-    realUrl = '/hosts?<parameters>fields=Hosts/host_name,Hosts/maintenance_state,' +
-      'host_components/HostRoles/state,host_components/HostRoles/maintenance_state,' +
-      'host_components/HostRoles/stale_configs&minimal_response=true' +
-    '';
-    var queryParams = [];
+      queryParams = [];
     switch(selection) {
     switch(selection) {
       case 's':
       case 's':
         hostsNames = this.get('selectedHosts');
         hostsNames = this.get('selectedHosts');
@@ -373,11 +370,8 @@ App.MainHostView = App.TableView.extend(App.TableServerProvider, {
         }
         }
         break;
         break;
       case 'f':
       case 'f':
-        queryParams = this.getQueryParameters().filter(function (obj){
-          if(obj.key == 'page_size' || obj.key == 'from'){
-            return false;
-          }
-          return true;
+        queryParams = this.getQueryParameters(true).filter(function (obj) {
+          return !(obj.key == 'page_size' || obj.key == 'from');
         });
         });
         break;
         break;
     }
     }
@@ -387,15 +381,16 @@ App.MainHostView = App.TableView.extend(App.TableServerProvider, {
       primary: false,
       primary: false,
       secondary: false,
       secondary: false,
       bodyClass: Ember.View.extend({
       bodyClass: Ember.View.extend({
-        template: Ember.Handlebars.compile('<p><div class="spinner"></div></p>')
+        template: Ember.Handlebars.compile('<div class="spinner"></div>')
       })
       })
     });
     });
-
+    var parameters = App.router.get('updateController').computeParameters(queryParams);
+    if (!parameters.length) parameters = '&';
     App.ajax.send({
     App.ajax.send({
       name: 'hosts.bulk.operations',
       name: 'hosts.bulk.operations',
       sender: this,
       sender: this,
       data: {
       data: {
-        url: App.router.get('updateController').getComplexUrl("", realUrl, queryParams),
+        parameters: parameters.substring(0, parameters.length - 1),
         operationData: operationData,
         operationData: operationData,
         loadingPopup: loadingPopup
         loadingPopup: loadingPopup
       },
       },