serverValidator.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. var App = require('app');
  19. var blueprintUtils = require('utils/blueprint');
  20. App.ServerValidatorMixin = Em.Mixin.create({
  21. /**
  22. * defines if we use validation and recommendation on wizards
  23. * depend on this flag some properties will be taken from different places
  24. * @type {boolean}
  25. */
  26. isWizard: function() {
  27. return this.get('wizardController') && ['addServiceController', 'installerController'].contains(this.get('wizardController.name'));
  28. }.property('wizardController.name'),
  29. /**
  30. * @type {boolean} set true if at least one config has error
  31. */
  32. configValidationError: false,
  33. /**
  34. * @type {boolean} set true if at least one config has warning
  35. */
  36. configValidationWarning: false,
  37. /**
  38. * @type {boolean} set true if at least one config has warning
  39. */
  40. configValidationFailed: false,
  41. /**
  42. * @type {object[]} contains additional message about validation errors
  43. */
  44. configValidationGlobalMessage: [],
  45. /**
  46. * recommendation configs loaded from server
  47. * (used only during install)
  48. * @type {Object}
  49. */
  50. recommendationsConfigs: null,
  51. /**
  52. * by default loads data from model otherwise must be overridden as computed property
  53. * refer to \assets\data\stacks\HDP-2.1\recommendations_configs.json to learn structure
  54. * (shouldn't contain configurations filed)
  55. * @type {Object}
  56. */
  57. hostNames: function() {
  58. return this.get('isWizard')
  59. ? Object.keys(this.get('content.hosts'))
  60. : App.get('allHostNames');
  61. }.property('isWizard', 'content.hosts', 'App.allHostNames'),
  62. /**
  63. * by default loads data from model otherwise must be overridden as computed property
  64. * @type {Array} - of strings (serviceNames)
  65. */
  66. serviceNames: function() {
  67. // When editing a service we validate only that service's configs.
  68. // However, we should pass the IDs of services installed, or else,
  69. // default value calculations will alter.
  70. return this.get('isWizard') ? this.get('allSelectedServiceNames') : App.Service.find().mapProperty('serviceName');
  71. }.property('isWizard', 'allSelectedServiceNames'),
  72. /**
  73. * by default loads data from model otherwise must be overridden as computed property
  74. * filter services that support server validation and concat with misc configs if Installer or current service
  75. * @type {Array} - of objects (services)
  76. */
  77. services: function() {
  78. var stackServices = App.StackService.find().filter(function(s) {
  79. return this.get('serviceNames').contains(s.get('serviceName'));
  80. }, this);
  81. return this.get('isWizard') ? stackServices.concat(require("data/service_configs")) : stackServices;
  82. }.property('serviceNames'),
  83. /**
  84. * by default loads data from model otherwise must be overridden as computed property
  85. * can be used for service|host configs pages
  86. * @type {Array} of strings (hostNames)
  87. */
  88. hostGroups: function() {
  89. return this.get('content.recommendationsHostGroups') || blueprintUtils.generateHostGroups(App.get('allHostNames'));
  90. }.property('content.recommendationsHostGroups', 'App.allHostNames'),
  91. /**
  92. * controller that is child of this mixin has to contain stepConfigs
  93. * @type {Array}
  94. */
  95. stepConfigs: null,
  96. /**
  97. * @method loadServerSideConfigsRecommendations
  98. * load recommendations from server
  99. * (used only during install)
  100. * @returns {*}
  101. */
  102. loadServerSideConfigsRecommendations: function() {
  103. var self = this;
  104. // if extended controller doesn't support recommendations ignore this call but keep promise chain
  105. if (!this.get('isControllerSupportsEnhancedConfigs')) {
  106. return $.Deferred().resolve().promise();
  107. }
  108. var recommendations = this.get('hostGroups');
  109. // send user's input based on stored configurations
  110. if (this.get('content.serviceConfigProperties.length')) {
  111. recommendations.blueprint.configurations = blueprintUtils.buildConfigsJSON(this.get('services'), this.get('stepConfigs'));
  112. }
  113. // for add service send configurations for installed services on first transition to Customize Services step
  114. if (!this.get('content.serviceConfigProperties.length') && this.get('wizardController.name') === 'addServiceController') {
  115. recommendations.blueprint.configurations = blueprintUtils.buildConfigsJSON(this.get('services'), this.get('stepConfigs').filter(function(serviceConfigs) {
  116. return self.get('installedServiceNames').contains(serviceConfigs.get('serviceName'));
  117. }));
  118. }
  119. return App.ajax.send({
  120. 'name': 'config.recommendations',
  121. 'sender': this,
  122. 'data': {
  123. stackVersionUrl: App.get('stackVersionURL'),
  124. dataToSend: {
  125. recommend: 'configurations',
  126. hosts: this.get('hostNames'),
  127. services: this.get('serviceNames'),
  128. recommendations: recommendations
  129. }
  130. },
  131. 'success': 'loadRecommendationsSuccess',
  132. 'error': 'loadRecommendationsError'
  133. });
  134. },
  135. /**
  136. * @method loadRecommendationsSuccess
  137. * success callback after loading recommendations
  138. * (used only during install)
  139. * @param data
  140. */
  141. loadRecommendationsSuccess: function(data) {
  142. if (!data) {
  143. console.warn('error while loading default config values');
  144. }
  145. this._saveRecommendedValues(data);
  146. var configObject = data.resources[0].recommendations.blueprint.configurations;
  147. if (configObject) this.updateInitialValue(configObject);
  148. this.set("recommendationsConfigs", Em.get(data.resources[0] , "recommendations.blueprint.configurations"));
  149. },
  150. loadRecommendationsError: function(jqXHR, ajaxOptions, error, opt) {
  151. App.ajax.defaultErrorHandler(jqXHR, opt.url, opt.method, jqXHR.status);
  152. console.error('Load recommendations failed');
  153. },
  154. serverSideValidation: function () {
  155. var deferred = $.Deferred();
  156. var self = this;
  157. this.set('configValidationFailed', false);
  158. this.set('configValidationGlobalMessage', []);
  159. if (this.get('configValidationFailed')) {
  160. this.warnUser(deferred);
  161. } else {
  162. if (this.get('isInstaller')) {
  163. this.runServerSideValidation(deferred);
  164. } else {
  165. // on Service Configs page we need to load all hosts with componnets
  166. this.getAllHostsWithComponents().then(function(data) {
  167. self.set('content.recommendationsHostGroups', blueprintUtils.generateHostGroups(App.get('allHostNames'), self.mapHostsToComponents(data.items)));
  168. self.runServerSideValidation(deferred);
  169. });
  170. }
  171. }
  172. return deferred;
  173. },
  174. getAllHostsWithComponents: function() {
  175. return App.ajax.send({
  176. sender: this,
  177. name: 'common.hosts.all',
  178. data: {
  179. urlParams: 'fields=HostRoles/component_name,HostRoles/host_name'
  180. }
  181. });
  182. },
  183. /**
  184. * Generate array similar to App.HostComponent which will be used to
  185. * create blueprint hostGroups object as well.
  186. *
  187. * @param {Object[]} jsonData
  188. * @returns {Em.Object[]}
  189. */
  190. mapHostsToComponents: function(jsonData) {
  191. var result = [];
  192. jsonData.forEach(function(item) {
  193. result.push(Em.Object.create({
  194. componentName: Em.get(item, 'HostRoles.component_name'),
  195. hostName: Em.get(item, 'HostRoles.host_name')
  196. }));
  197. });
  198. return result;
  199. },
  200. /**
  201. * @method serverSideValidation
  202. * send request to validate configs
  203. * @returns {*}
  204. */
  205. runServerSideValidation: function(deferred) {
  206. var self = this;
  207. var recommendations = this.get('hostGroups');
  208. recommendations.blueprint.configurations = blueprintUtils.buildConfigsJSON(this.get('services'), this.get('stepConfigs'));
  209. return App.ajax.send({
  210. name: 'config.validations',
  211. sender: this,
  212. data: {
  213. stackVersionUrl: App.get('stackVersionURL'),
  214. hosts: this.get('hostNames'),
  215. services: this.get('serviceNames'),
  216. validate: 'configurations',
  217. recommendations: recommendations
  218. },
  219. success: 'validationSuccess',
  220. error: 'validationError'
  221. }).complete(function() {
  222. self.warnUser(deferred);
  223. });
  224. },
  225. /**
  226. * @method validationSuccess
  227. * success callback after getting responce from server
  228. * go through the step configs and set warn and error messages
  229. * @param data
  230. */
  231. validationSuccess: function(data) {
  232. var self = this;
  233. var checkedProperties = [];
  234. var globalWarning = [];
  235. self.set('configValidationError', false);
  236. self.set('configValidationWarning', false);
  237. data.resources.forEach(function(r) {
  238. r.items.forEach(function(item){
  239. if (item.type == "configuration") {
  240. self.get('stepConfigs').forEach(function(service) {
  241. service.get('configs').forEach(function(property) {
  242. if ((property.get('filename') == item['config-type'] + '.xml') && (property.get('name') == item['config-name'])) {
  243. if (item.level == "ERROR") {
  244. self.set('configValidationError', true);
  245. property.set('errorMessage', item.message);
  246. property.set('error', true);
  247. } else if (item.level == "WARN") {
  248. self.set('configValidationWarning', true);
  249. property.set('warnMessage', item.message);
  250. property.set('warn', true);
  251. }
  252. // store property data to detect WARN or ERROR messages for missed property
  253. if (["ERROR", "WARN"].contains(item.level)) checkedProperties.push(item['config-type'] + '/' + item['config-name']);
  254. }
  255. });
  256. });
  257. // check if error or warn message detected for property that absent in step configs
  258. if (["ERROR", "WARN"].contains(item.level) && !checkedProperties.contains(item['config-type'] + '/' + item['config-name'])) {
  259. var message = {
  260. propertyName: item['config-name'],
  261. filename: item['config-type'],
  262. warnMessage: item.message
  263. };
  264. if (item['config-type'] === "" && item['config-name'] === "") {
  265. //service-independent validation
  266. message.isGeneral = true;
  267. } else {
  268. message.serviceName = App.StackService.find().filter(function(service) {
  269. return !!service.get('configTypes')[item['config-type']];
  270. })[0].get('displayName')
  271. }
  272. self.set(item.level == 'WARN' ? 'configValidationWarning' : 'configValidationError', true);
  273. globalWarning.push(message);
  274. }
  275. }
  276. });
  277. });
  278. self.set('configValidationGlobalMessage', globalWarning);
  279. },
  280. validationError: function (jqXHR, ajaxOptions, error, opt) {
  281. this.set('configValidationFailed', true);
  282. App.ajax.defaultErrorHandler(jqXHR, opt.url, opt.method, jqXHR.status);
  283. console.error('config validation failed');
  284. },
  285. /**
  286. * warn user if some errors or warning were
  287. * in seting up configs otherwise go to the nex operation
  288. * @param deferred
  289. * @returns {*}
  290. */
  291. warnUser: function(deferred) {
  292. var self = this;
  293. if (this.get('configValidationFailed')) {
  294. deferred.reject();
  295. return App.showAlertPopup(Em.I18n.t('installer.step7.popup.validation.failed.header'), Em.I18n.t('installer.step7.popup.validation.request.failed.body'));
  296. } else if (this.get('configValidationWarning') || this.get('configValidationError')) {
  297. // Motivation: for server-side validation warnings and EVEN errors allow user to continue wizard
  298. return App.ModalPopup.show({
  299. header: Em. I18n.t('installer.step7.popup.validation.warning.header'),
  300. classNames: ['sixty-percent-width-modal','modal-full-width'],
  301. primary: Em.I18n.t('common.proceedAnyway'),
  302. primaryClass: 'btn-danger',
  303. marginBottom: 200,
  304. onPrimary: function () {
  305. this.hide();
  306. deferred.resolve();
  307. },
  308. onSecondary: function () {
  309. this.hide();
  310. deferred.reject("invalid_configs"); // message used to differentiate types of rejections.
  311. },
  312. onClose: function () {
  313. this.hide();
  314. deferred.reject("invalid_configs"); // message used to differentiate types of rejections.
  315. },
  316. bodyClass: Em.View.extend({
  317. controller: self,
  318. templateName: require('templates/common/modal_popups/config_recommendation_popup')
  319. })
  320. });
  321. } else {
  322. deferred.resolve();
  323. }
  324. }
  325. });