修改ambari样式-前端View扩展[一]
# 10-成神之路_ambari_Ambari实战-051-UI-如何通过配置修改ambari样式-前端View扩展🎯
# 1. 页面渲染概述
页面渲染主要有两种核心方式,分别是基于 widgetTypeMap
和 displayType
的渲染。
- 渲染方式一widgetTypeMap: 基于
theme.json
的widget
配置渲染,属于主题驱动的动态方式。 - 渲染方式二displayType: 前端配置 displayType 字段,直接决定控件类型,多见于早期实现或特殊控件。
# 2. 基于 widgetTypeMap
的渲染
# 2.1 机制与优势
- 定义:通过
theme.json
中的widget
字段,前端通过widgetTypeMap
完成控件类型映射。 - 典型场景:适合灵活切换页面控件类型,如输入框、密码框、滑块、下拉框等。
# 2.2 渲染效果与类型说明
widgetTypeMap
是 Ambari 配置页面控件类型的核心映射。不同 widget.type
会自动加载不同的控件视图组件,支持高度定制化。
# 2.2.1 常见控件类型一览
控件类型 | 对应控件视图 | 渲染效果 |
---|---|---|
checkbox | CheckboxConfigWidgetView | 复选框,适合布尔值配置。 |
combo | ComboConfigWidgetView | 下拉菜单,适合单选预设值场景。 |
directory | TextFieldConfigWidgetView | 单行文本框,常用于路径输入。 |
directories | DirectoryConfigWidgetView | 多目录选择,适合多个路径输入。 |
list | ListConfigWidgetView | 多选列表,允许用户勾选多个值。 |
password | PasswordConfigWidgetView | 密码输入框,内容不可见。 |
radio-buttons | RadioButtonConfigWidgetView | 单选按钮,适合互斥项配置。 |
slider | SliderConfigWidgetView | 滑块,支持范围数值调节。 |
text-field | TextFieldConfigWidgetView | 单行文本输入框。 |
time-interval-spinner | TimeIntervalSpinnerView | 时间区间选择器,适合超时等参数。 |
toggle | ToggleConfigWidgetView | 开关按钮,启用/禁用场景。 |
text-area | StringConfigWidgetView | 多行文本输入,适合脚本或说明。 |
label | LabelView | 只读标签,只做展示。 |
test-db-connection | TestDbConnectionWidgetView | 数据库连接测试按钮,支持一键连通性检测。 |
# 2.2.2 代码示例
以下为实际 widgetTypeMap
代码片段,演示类型与组件的映射关系(代码源自 app/mixins/common/configs/enhanced_configs.js
):
/**
* ConfigType-Widget map
* key - widget type
* value - widget view
* @type {object}
*/
widgetTypeMap: {
checkbox: 'CheckboxConfigWidgetView',
combo
:
'ComboConfigWidgetView',
directory
:
'TextFieldConfigWidgetView',
directories
:
'DirectoryConfigWidgetView',
list
:
'ListConfigWidgetView',
password
:
'PasswordConfigWidgetView',
'radio-buttons'
:
'RadioButtonConfigWidgetView',
slider
:
'SliderConfigWidgetView',
'text-field'
:
'TextFieldConfigWidgetView',
'time-interval-spinner'
:
'TimeIntervalSpinnerView',
toggle
:
'ToggleConfigWidgetView',
'text-area'
:
'StringConfigWidgetView',
'label'
:
'LabelView',
'test-db-connection'
:
'TestDbConnectionWidgetView'
}
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
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
# 2.3 渲染代码逻辑与 test-db-connection 深度解读
- 疑点突破
"type": "test-db-connection"
并非传统配置项,而是 theme 扩展中专门为连通性测试场景设计的控件类型,很多交互逻辑需靠前端实现补充。 控件示例(test-db-connection):
{
"config": "ranger-env/test_db_connection",
"widget": {
"type": "test-db-connection",
"display-name": "Test Connection",
"required-properties": {
"jdbc.driver.class": "ranger-admin-site/ranger.jpa.jdbc.driver",
"jdbc.driver.url": "ranger-admin-site/ranger.jpa.jdbc.url",
"db.connection.source.host": "ranger-site/ranger_admin_hosts",
"db.type": "admin-properties/DB_FLAVOR",
"db.connection.destination.host": "admin-properties/db_host",
"db.connection.user": "admin-properties/db_user",
"db.connection.password": "admin-properties/db_password"
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- widgetTypeMap 决定渲染组件:
widgetTypeMap: {
...,
'test-db-connection'
:
'TestDbConnectionWidgetView',
...
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 2.3.1 TestDbConnection 组件主逻辑
//@Todo merge with CheckDBConnectionView
App.TestDbConnectionWidgetView = App.ConfigWidgetView.extend({
templateName: require('templates/common/configs/widgets/test_db_connection_widget'),
classNames: ['widget'],
dbInfo: require('data/db_properties_info'),
didInsertElement: function () {
var requiredProperties = this.get('config.stackConfigProperty.widget.required-properties');
var serviceName = this.get('config.serviceName');
var serviceConfigs = this.get('controller.stepConfigs').findProperty('serviceName', serviceName).get('configs');
var requiredServiceConfigs = Object.keys(requiredProperties).map(function (key) {
var split = requiredProperties[key].split('/');
var fileName = split[0] + '.xml';
var configName = split[1];
var requiredConfig = serviceConfigs.filterProperty('filename', fileName).findProperty('name', configName);
if (!requiredConfig) {
var componentName = App.config.getComponentName(configName);
var stackComponent = App.StackServiceComponent.find(componentName);
if (stackComponent && stackComponent.get('componentName')) {
var value = this.get('controller').getComponentHostValue(componentName,
this.get('controller.wizardController.content.masterComponentHosts'),
this.get('controller.wizardController.content.slaveComponentHosts'));
var hProperty = App.config.createHostNameProperty(serviceName, componentName, value, stackComponent);
return App.ServiceConfigProperty.create(hProperty);
}
} else {
return requiredConfig;
}
}, this);
this.set('requiredProperties', requiredServiceConfigs);
this.setDbProperties(requiredProperties);
this.getAmbariProperties();
},
/**
* This function is used to set Database name and master host name
* @param requiredProperties: `config.stackConfigProperty.widget.required-properties` as stated in the theme
*/
setDbProperties: function (requiredProperties) {
var dbProperties = {
'db.connection.source.host': 'masterHostName',
'db.type': 'db_type',
'db.connection.user': 'user_name',
'db.connection.password': 'user_passwd',
'jdbc.driver.url': 'db_connection_url',
'db.type.label': 'db_type_label'
};
for (var key in dbProperties) {
var masterHostNameProperty = requiredProperties[key];
if (masterHostNameProperty) {
var split = masterHostNameProperty.split('/');
var fileName = split[0] + '.xml';
var configName = split[1];
var dbConfig = this.get('requiredProperties').filterProperty('filename', fileName).findProperty('name', configName);
this.set(dbProperties[key], dbConfig);
}
}
},
/**
* `Action` method for starting connect to current database.
*
* @method connectToDatabase
**/
connectToDatabase: function () {
if (this.get('isBtnDisabled')) return;
this.set('isRequestResolved', false);
App.db.set('tmp', this.get('db_connection_url.serviceName') + '_connection', {});
this.setConnectingStatus(true);
if (App.get('testMode')) {
this.startPolling();
} else {
this.runCheckConnection();
}
},
/**
* runs check connections methods depending on service
* @return {void}
* @method runCheckConnection
*/
runCheckConnection: function () {
this.createCustomAction();
},
/**
* Run custom action for database connection.
*
* @method createCustomAction
**/
createCustomAction: function () {
var connectionProperties = this.getProperties('db_connection_url', 'user_name', 'user_passwd');
var db_name = this.dbInfo.dpPropertiesMap[dbUtils.getDBType(this.get('db_type').value)].db_type;
var isServiceInstalled = App.Service.find(this.get('config.serviceName')).get('isLoaded');
for (var key in connectionProperties) {
if (connectionProperties.hasOwnProperty(key)) {
connectionProperties[key] = connectionProperties[key].value;
}
}
var params = $.extend(true, {}, {db_name: db_name}, connectionProperties, this.get('ambariProperties'));
var filteredHosts = Array.isArray(this.get('masterHostName.value')) ? this.get('masterHostName.value') : [this.get('masterHostName.value')];
App.ajax.send({
name: (isServiceInstalled) ? 'cluster.custom_action.create' : 'custom_action.create',
sender: this,
data: {
requestInfo: {
parameters: params
},
filteredHosts: filteredHosts
},
success: 'onCreateActionSuccess',
error: 'onCreateActionError'
});
},
/**
* Run updater if task is created successfully.
*
* @method onConnectActionS
**/
onCreateActionSuccess: function (data) {
this.set('currentRequestId', data.Requests.id);
App.ajax.send({
name: 'custom_action.request',
sender: this,
data: {
requestId: this.get('currentRequestId')
},
success: 'setCurrentTaskId'
});
},
setCurrentTaskId: function (data) {
this.set('currentTaskId', data.items[0].Tasks.id);
this.startPolling();
},
startPolling: function () {
if (this.get('isConnecting'))
this.getTaskInfo();
},
getTaskInfo: function () {
var request = App.ajax.send({
name: 'custom_action.request',
sender: this,
data: {
requestId: this.get('currentRequestId'),
taskId: this.get('currentTaskId')
},
success: 'getTaskInfoSuccess'
});
this.set('request', request);
},
preparedDBProperties: function () {
var propObj = {};
var serviceName = this.get('config.serviceName');
var serviceConfigs = this.get('controller.stepConfigs').findProperty('serviceName', serviceName).get('configs');
for (var key in this.get('propertiesPattern')) {
var propName = this.getConnectionProperty(this.get('propertiesPattern')[key], true);
propObj[propName] = serviceConfigs.findProperty('name', propName).get('value');
}
return propObj;
}.property(),
requiredProps: function () {
var ranger = App.StackService.find().findProperty('serviceName', 'RANGER');
var propertiesMap = {
OOZIE: ['oozie.db.schema.name', 'oozie.service.JPAService.jdbc.username', 'oozie.service.JPAService.jdbc.password', 'oozie.service.JPAService.jdbc.driver', 'oozie.service.JPAService.jdbc.url'],
HIVE: ['ambari.hive.db.schema.name', 'javax.jdo.option.ConnectionUserName', 'javax.jdo.option.ConnectionPassword', 'javax.jdo.option.ConnectionDriverName', 'javax.jdo.option.ConnectionURL'],
KERBEROS: ['kdc_hosts'],
RANGER: ranger && ranger.compareCurrentVersion('0.5') > -1 ?
['db_user', 'db_password', 'db_name', 'ranger.jpa.jdbc.url', 'ranger.jpa.jdbc.driver'] :
['db_user', 'db_password', 'db_name', 'ranger_jdbc_connection_url', 'ranger_jdbc_driver'],
RANGER_KMS: ['db_user', 'db_password', 'ranger.ks.jpa.jdbc.url', 'ranger.ks.jpa.jdbc.driver']
};
return propertiesMap[this.get('parentView.content.serviceName')];
}.property(),
getConnectionProperty: function (regexp, isGetName) {
var serviceName = this.get('config.serviceName');
var serviceConfigs = this.get('controller.stepConfigs').findProperty('serviceName', serviceName).get('configs');
var propertyName = this.get('requiredProps').filter(function (item) {
return regexp.test(item);
})[0];
return (isGetName) ? propertyName : serviceConfigs.findProperty('name', propertyName).get('value');
},
propertiesPattern: function () {
var patterns = {
db_connection_url: /jdbc\.url|connection_url|connectionurl|kdc_hosts/ig
};
if (this.get('parentView.service.serviceName') != "KERBEROS") {
patterns.user_name = /(username|dblogin|db_user)$/ig;
patterns.user_passwd = /(dbpassword|password|db_password)$/ig;
}
return patterns;
}.property('parentView.service.serviceName'),
getTaskInfoSuccess: function (data) {
var task = data.Tasks;
this.set('responseFromServer', {
stderr: task.stderr,
stdout: task.stdout
});
if (task.status === 'COMPLETED') {
var structuredOut = task.structured_out.db_connection_check;
if (structuredOut.exit_code != 0) {
this.set('responseFromServer', {
stderr: task.stderr,
stdout: task.stdout,
structuredOut: structuredOut.message
});
this.setResponseStatus('failed');
} else {
App.db.set('tmp', this.get('db_connection_url.serviceName') + '_connection', this.get('preparedDBProperties'));
this.setResponseStatus('success');
}
}
if (task.status === 'FAILED') {
this.setResponseStatus('failed');
}
if (/PENDING|QUEUED|IN_PROGRESS/.test(task.status)) {
Em.run.later(this, function () {
this.startPolling();
}, this.get('pollInterval'));
}
},
onCreateActionError: function (jqXhr, status, errorMessage) {
this.setResponseStatus('failed');
this.set('responseFromServer', errorMessage);
},
setResponseStatus: function (isSuccess) {
var db_type = this.dbInfo.dpPropertiesMap[dbUtils.getDBType(this.get('db_type').value)].db_type.toUpperCase();
var isSuccess = isSuccess == 'success';
this.setConnectingStatus(false);
this.set('responseCaption', isSuccess ? Em.I18n.t('services.service.config.database.connection.success') : Em.I18n.t('services.service.config.database.connection.failed'));
this.set('isConnectionSuccess', isSuccess);
this.set('isRequestResolved', true);
if (this.get('logsPopup')) {
var statusString = isSuccess ? 'common.success' : 'common.error';
this.set('logsPopup.header', Em.I18n.t('services.service.config.connection.logsPopup.header').format(db_type, Em.I18n.t(statusString)));
}
},
/**
* Switch captions and statuses for active/non-active request.
*
* @method setConnectionStatus
* @param {Boolean} [active]
*/
setConnectingStatus: function (active) {
if (active) {
this.set('responseCaption', Em.I18n.t('services.service.config.database.connection.inProgress'));
}
this.set('controller.testConnectionInProgress', !!active);
this.set('btnCaption', !!active ? Em.I18n.t('services.service.config.database.btn.connecting') : Em.I18n.t('services.service.config.database.btn.idle'));
this.set('isConnecting', !!active);
},
/**
* Set view to init status.
*
* @method restore
**/
restore: function () {
if (this.get('request')) {
this.get('request').abort();
this.set('request', null);
}
this.set('responseCaption', null);
this.set('responseFromServer', null);
this.setConnectingStatus(false);
this.set('isRequestResolved', false);
},
/**
* `Action` method for showing response from server in popup.
*
* @method showLogsPopup
**/
showLogsPopup: function () {
if (this.get('isConnectionSuccess')) return;
var _this = this;
var db_type = this.dbInfo.dpPropertiesMap[dbUtils.getDBType(this.get('db_type').value)].db_type.toUpperCase();
var statusString = this.get('isRequestResolved') ? 'common.error' : 'common.testing';
var popup = App.showAlertPopup(Em.I18n.t('services.service.config.connection.logsPopup.header').format(db_type, Em.I18n.t(statusString)), null, function () {
_this.set('logsPopup', null);
});
popup.reopen({
onClose: function () {
this._super();
_this.set('logsPopup', null);
}
});
if (typeof this.get('responseFromServer') == 'object') {
popup.set('bodyClass', Em.View.extend({
checkDBConnectionView: _this,
templateName: require('templates/common/error_log_body'),
openedTask: function () {
return this.get('checkDBConnectionView.responseFromServer');
}.property('checkDBConnectionView.responseFromServer.stderr', 'checkDBConnectionView.responseFromServer.stdout', 'checkDBConnectionView.responseFromServer.structuredOut')
}));
} else {
popup.set('body', this.get('responseFromServer'));
}
this.set('logsPopup', popup);
return popup;
}
});
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
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
# 2.4 交互逻辑与自定义组件集成思路
- 组件集成要点
TestDbConnection 按钮的点击、UI反馈、属性组装等,全部在前端自定义代码内完成,主题文件只需声明
widget.type
和依赖属性即可。
# 步骤一:装配配置
注:自定义组件时,很多配置项依赖关系和 UI 控件展现,都需要前端代码参与组装,theme 配置仅是声明和触发条件。
requiredProps: function () {
var ranger = App.StackService.find().findProperty('serviceName', 'RANGER');
var propertiesMap = {
OOZIE: [...],
HIVE: [...],
KERBEROS: [...],
RANGER: ranger && ranger.compareCurrentVersion('0.5') > -1 ?
[...] : [...],
RANGER_KMS: [...]
};
return propertiesMap[this.get('parentView.content.serviceName')];
}
.
property(),
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 步骤二:定位请求入口
跟踪源码可定位到 createCustomAction 方法,负责参数拼装和 AJAX 交互。
- 执行结果处理:点击测试后页面自动长轮询,最终根据任务状态返回成功或失败反馈,并更新页面 UI。
# 2.5 组件模板代码说明
模板路径:
app/templates/common/configs/widgets/test_db_connection_widget.hbs
模板源码:
{{!
* 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.
}}
{{#unless view.isNewSelected}}
<div class="entry-row db-connection form-group">
<div class="control-group">
<div class="row">
<div class="col-md-10">
<span {{bindAttr class=":pull-left :btn :btn-primary view.isBtnDisabled:disabled" }} {{action
connectToDatabase target="view" }}>{{view.btnCaption}}</span>
<div class="pull-left connection-result mll">
<a {{bindAttr class="view.isConnectionSuccess:mute:action" }} {{action showLogsPopup target="view"
}}>{{view.responseCaption}}</a>
</div>
{{#if view.isConnecting}}
{{view App.SpinnerView classNames="mll pull-left"}}
{{/if}}
<i {{bindAttr
class=":pull-right view.isConnectionSuccess:glyphicon-ok-sign:glyphicon-warning-sign :glyphicon view.isRequestResolved::hide"
}}></i>
</div>
</div>
</div>
</div>
{{/unless}}
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
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