forked from openshift/origin-web-console
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfromFile.js
525 lines (482 loc) · 21.3 KB
/
fromFile.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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
'use strict';
angular.module("openshiftConsole")
.directive("fromFile", function($filter,
$location,
$q,
$uibModal,
APIService,
CachedTemplateService,
DataService,
Navigate,
NotificationsService,
QuotaService,
SecurityCheckService,
TaskList,
ProjectsService) {
return {
restrict: "E",
scope: {
project: '=',
isDialog: '='
},
templateUrl: "views/directives/from-file.html",
controller: function($scope) {
var aceEditorSession;
$scope.noProjectsCantCreate = false;
var humanizeKind = $filter('humanizeKind');
var getErrorDetails = $filter('getErrorDetails');
TaskList.clear();
$scope.$on('no-projects-cannot-create', function() {
$scope.noProjectsCantCreate = true;
});
$scope.input = {
selectedProject: $scope.project
};
$scope.aceLoaded = function(editor) {
aceEditorSession = editor.getSession();
aceEditorSession.setOption('tabSize', 2);
aceEditorSession.setOption('useSoftTabs', true);
editor.setDragDelay = 0;
editor.$blockScrolling = Infinity;
};
var launchConfirmationDialog = function(alerts) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'views/modals/confirm.html',
controller: 'ConfirmModalController',
resolve: {
modalConfig: function() {
return {
alerts: alerts,
message: "We checked your application for potential problems. Please confirm you still want to create this application.",
okButtonText: "Create Anyway",
okButtonClass: "btn-danger",
cancelButtonText: "Cancel"
};
}
}
});
modalInstance.result.then(createAndUpdate);
};
var alerts = {};
var hideErrorNotifications = function() {
NotificationsService.hideNotification("from-file-error");
_.each(alerts, function(alert) {
if (alert.id && (alert.type === 'error' || alert.type === 'warning')) {
NotificationsService.hideNotification(alert.id);
}
});
};
var showWarningsOrCreate = function(result){
// Hide any previous notifications when form is resubmitted.
hideErrorNotifications();
alerts = SecurityCheckService.getSecurityAlerts($scope.createResources, $scope.input.selectedProject.metadata.name);
// Now that all checks are completed, show any Alerts if we need to
var quotaAlerts = result.quotaAlerts || [];
alerts = alerts.concat(quotaAlerts);
var errorAlerts = _.filter(alerts, {type: 'error'});
if (errorAlerts.length) {
_.each(alerts, function(alert) {
alert.id = _.uniqueId('from-file-alert-');
NotificationsService.addNotification(alert);
});
$scope.disableInputs = false;
}
else if (alerts.length) {
launchConfirmationDialog(alerts);
$scope.disableInputs = false;
}
else {
createAndUpdate();
}
};
var createProjectIfNecessary = function() {
if (_.has($scope.input.selectedProject, 'metadata.uid')) {
return $q.when($scope.input.selectedProject);
}
var newProjName = $scope.input.selectedProject.metadata.name;
var newProjDisplayName = $scope.input.selectedProject.metadata.annotations['new-display-name'];
var newProjDesc = $filter('description')($scope.input.selectedProject);
return ProjectsService.create(newProjName, newProjDisplayName, newProjDesc);
};
$scope.create = function() {
delete $scope.error;
// Trying to auto-detect what format the input is in. Since parsing JSON throws only SyntexError
// exception if the string to parse is not valid JSON, it is tried first and then the YAML parser
// is trying to parse the string. If that fails it will print the reason. In case the real reason
// is JSON related the printed reason will be "Reason: Unable to parse", in case of YAML related
// reason the true reason will be printed, since YAML parser throws an error object with needed
// data.
if (!isKindValid($scope.resource)) {
return;
}
$scope.resourceKind = $scope.resource.kind;
$scope.resourceKind.endsWith("List") ? $scope.isList = true : $scope.isList = false;
if (!isMetadataValid($scope.resource)) {
return;
}
if ($scope.isList) {
$scope.resourceList = $scope.resource.items;
$scope.resourceName = '';
} else {
$scope.resourceList = [$scope.resource];
$scope.resourceName = $scope.resource.metadata.name;
if ($scope.resourceKind === "Template") {
$scope.templateOptions = {
process: true,
add: false
};
}
}
$scope.updateResources = [];
$scope.createResources = [];
var resourceCheckPromises = [];
$scope.errorOccurred = false;
_.forEach($scope.resourceList, function(item) {
if (!isMetadataValid(item)) {
$scope.errorOccurred = true;
return false;
}
resourceCheckPromises.push(checkIfExists(item));
});
createProjectIfNecessary().then(function(project) {
$scope.input.selectedProject = project;
$q.all(resourceCheckPromises).then(function() {
if ($scope.errorOccurred) {
return;
}
// If resource is Template and it doesn't exist in the project
if ($scope.createResources.length === 1 && $scope.resourceList[0].kind === "Template") {
openTemplateProcessModal();
// Else if any resources already exist
} else if (!_.isEmpty($scope.updateResources)) {
$scope.updateTemplate = $scope.updateResources.length === 1 && $scope.updateResources[0].kind === "Template";
if ($scope.updateTemplate) {
openTemplateProcessModal();
} else {
confirmReplace();
}
} else {
QuotaService.getLatestQuotaAlerts($scope.createResources, {namespace: $scope.input.selectedProject.metadata.name}).then(showWarningsOrCreate);
}
});
}, function(e) {
NotificationsService.addNotification({
id: "import-create-project-error",
type: "error",
message: "An error occurred creating project",
details: getErrorDetails(e)
});
});
};
$scope.cancel = function() {
hideErrorNotifications();
Navigate.toProjectOverview($scope.input.selectedProject.metadata.name);
};
// Takes item that will be inspect kind field.
function isKindValid(item) {
if (!item.kind) {
$scope.error = {
message: "Resource is missing kind field."
};
return false;
}
return true;
}
// Takes item that will be inspect metadata fields and if the item is meant to be created in current namespace
function isMetadataValid(item) {
if ($scope.isList) {
return true;
}
if (!item.metadata) {
$scope.error = {
message: "Resource is missing metadata field."
};
return false;
}
if (!item.metadata.name) {
$scope.error = {
message: "Resource name is missing in metadata field."
};
return false;
}
if (item.metadata.namespace && item.metadata.namespace !== $scope.input.selectedProject.metadata.name) {
$scope.error = {
message: item.kind + " " + item.metadata.name + " can't be created in project " + item.metadata.namespace + ". Can't create resource in different projects."
};
return false;
}
return true;
}
function openTemplateProcessModal() {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'views/modals/process-or-save-template.html',
controller: 'ProcessOrSaveTemplateModalController',
scope: $scope
});
modalInstance.result.then(function() {
if ($scope.templateOptions.add) {
createAndUpdate();
} else {
CachedTemplateService.setTemplate($scope.resourceList[0]);
redirect();
}
});
}
function confirmReplace() {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'views/modals/confirm-replace.html',
controller: 'ConfirmReplaceModalController',
scope: $scope
});
modalInstance.result.then(function() {
QuotaService.getLatestQuotaAlerts($scope.createResources, {namespace: $scope.input.selectedProject.metadata.name}).then(showWarningsOrCreate);
});
}
function createAndUpdate() {
var createResourcesSum = $scope.createResources.length,
updateResourcesSum = $scope.updateResources.length;
if (!$scope.resourceKind.endsWith("List")) {
createUpdateSingleResource();
} else {
var createUpdatePromises = [];
if (updateResourcesSum > 0) {
createUpdatePromises.push(updateResourceList());
}
if (createResourcesSum > 0) {
createUpdatePromises.push(createResourceList());
}
$q.all(createUpdatePromises).then(redirect);
}
}
// Redirect to newFromTemplate page in case the resource type is Template and user wants to process it.
// When redirecting to newFromTemplate page, use the cached Template if user doesn't adds it into the
// namespace by the create process or if the template is being updated.
function redirect() {
var path, namespace;
hideErrorNotifications();
if ($scope.resourceKind === "Template" && $scope.templateOptions.process && !$scope.errorOccurred) {
if ($scope.isDialog) {
$scope.$emit('fileImportedFromYAMLOrJSON', {
project: $scope.input.selectedProject,
template: $scope.resource
});
}
else {
namespace = ($scope.templateOptions.add || $scope.updateResources.length > 0) ? $scope.input.selectedProject.metadata.name : "";
path = Navigate.createFromTemplateURL($scope.resource, $scope.input.selectedProject.metadata.name, {namespace: namespace});
$location.url(path);
}
}
else if ($scope.isDialog) {
$scope.$emit('fileImportedFromYAMLOrJSON', {
project: $scope.input.selectedProject,
resource: $scope.resource,
isList: $scope.isList
});
}
else {
path = Navigate.projectOverviewURL($scope.input.selectedProject.metadata.name);
$location.url(path);
}
}
function checkIfExists(item) {
// check for invalid and unsupported object kind and version
var resourceGroupVersion = APIService.objectToResourceGroupVersion(item);
if (!resourceGroupVersion) {
$scope.errorOccurred = true;
$scope.error = { message: APIService.invalidObjectKindOrVersion(item) };
return;
}
if (!APIService.apiInfo(resourceGroupVersion)) {
$scope.errorOccurred = true;
$scope.error = { message: APIService.unsupportedObjectKindOrVersion(item) };
return;
}
// Check if the resource already exists. If it does, replace it spec with the new one.
return DataService.get(resourceGroupVersion, item.metadata.name, {namespace: $scope.input.selectedProject.metadata.name}, {errorNotification: false}).then(
// resource does exist
function(resource) {
// All fields, except 'metadata' will be copied from the submitted file.
var updatedResource = angular.copy(item);
// Update only 'annotations' and 'labels' fields from the metadata field.
var updatedMetadata = angular.copy(resource.metadata);
updatedMetadata.annotations = item.metadata.annotations;
updatedMetadata.labels = item.metadata.labels;
updatedResource.metadata = updatedMetadata;
$scope.updateResources.push(updatedResource);
},
// resource doesn't exist with RC 404 or catch other RC
function() {
// Either it didn't exist already or we couldn't validate existence for some reason, just continue on
// and try to create it.
$scope.createResources.push(item);
});
}
// createUpdateSingleResource function will create/update just a single resource on a none-List resource kind.
function createUpdateSingleResource() {
var resource;
if (!_.isEmpty($scope.createResources)) {
resource = _.head($scope.createResources);
DataService.create(APIService.kindToResource(resource.kind), null, resource, {namespace: $scope.input.selectedProject.metadata.name}).then(
// create resource success
function() {
if (!$scope.isDialog) {
var kind = humanizeKind(resource.kind);
NotificationsService.addNotification({
type: "success",
message: _.capitalize(kind) + " " + resource.metadata.name + " was successfully created."
});
}
redirect();
},
// create resource failure
function(result) {
NotificationsService.addNotification({
id: "from-file-error",
type: "error",
message: "Unable to create the " + humanizeKind(resource.kind) + " '" + resource.metadata.name + "'.",
details: $filter('getErrorDetails')(result)
});
});
} else {
resource = _.head($scope.updateResources);
DataService.update(APIService.kindToResource(resource.kind), resource.metadata.name, resource, {namespace: $scope.input.selectedProject.metadata.name}).then(
// update resource success
function() {
if (!$scope.isDialog) {
var kind = humanizeKind(resource.kind);
NotificationsService.addNotification({
type: "success",
message: _.capitalize(kind) + " " + resource.metadata.name + " was successfully updated."
});
}
redirect();
},
// update resource failure
function(result) {
NotificationsService.addNotification({
id: "from-file-error",
type: "error",
message: "Unable to update the " + humanizeKind(resource.kind) + " '" + resource.metadata.name + "'.",
details: $filter('getErrorDetails')(result)
});
});
}
}
var displayName = $filter('displayName');
function createResourceList(){
var titles = {
started: "Creating resources in project " + displayName($scope.input.selectedProject),
success: "Creating resources in project " + displayName($scope.input.selectedProject),
failure: "Failed to create some resources in project " + displayName($scope.input.selectedProject)
};
var helpLinks = {};
TaskList.add(titles, helpLinks, $scope.input.selectedProject.metadata.name, function() {
var d = $q.defer();
DataService.batch($scope.createResources, {namespace: $scope.input.selectedProject.metadata.name}, "create").then(
function(result) {
var alerts = [];
var hasErrors = false;
if (result.failure.length > 0) {
hasErrors = true;
$scope.errorOccurred = true;
result.failure.forEach(
function(failure) {
alerts.push({
type: "error",
message: "Cannot create " + humanizeKind(failure.object.kind) + " \"" + failure.object.metadata.name + "\". ",
details: failure.data.message
});
}
);
result.success.forEach(
function(success) {
alerts.push({
type: "success",
message: "Created " + humanizeKind(success.kind) + " \"" + success.metadata.name + "\" successfully. "
});
}
);
} else {
var alertMsg;
if ($scope.isList) {
alertMsg = "All items in list were created successfully.";
} else {
alertMsg = humanizeKind($scope.resourceKind) + " " + $scope.resourceName + " was successfully created.";
}
alerts.push({ type: "success", message: alertMsg});
}
d.resolve({alerts: alerts, hasErrors: hasErrors});
}
);
return d.promise;
});
}
function updateResourceList(){
var titles = {
started: "Updating resources in project " + displayName($scope.input.selectedProject),
success: "Updated resources in project " + displayName($scope.input.selectedProject),
failure: "Failed to update some resources in project " + displayName($scope.input.selectedProject)
};
var helpLinks = {};
TaskList.add(titles, helpLinks, $scope.input.selectedProject.metadata.name, function() {
var d = $q.defer();
DataService.batch($scope.updateResources, {namespace: $scope.input.selectedProject.metadata.name}, "update").then(
function(result) {
var alerts = [];
var hasErrors = false;
if (result.failure.length > 0) {
hasErrors = true;
$scope.errorOccurred = true;
result.failure.forEach(
function(failure) {
alerts.push({
type: "error",
message: "Cannot update " + humanizeKind(failure.object.kind) + " \"" + failure.object.metadata.name + "\". ",
details: failure.data.message
});
}
);
result.success.forEach(
function(success) {
alerts.push({
type: "success",
message: "Updated " + humanizeKind(success.kind) + " \"" + success.metadata.name + "\" successfully. "
});
}
);
} else {
var alertMsg;
if ($scope.isList) {
alertMsg = "All items in list were updated successfully.";
} else {
alertMsg = humanizeKind($scope.resourceKind) + " " + $scope.resourceName + " was successfully updated.";
}
alerts.push({ type: "success", message: alertMsg});
}
d.resolve({alerts: alerts, hasErrors: hasErrors});
},
function(result) {
var alerts = [];
alerts.push({
type: "error",
message: "An error occurred updating the resources.",
details: "Status: " + result.status + ". " + result.data
});
d.resolve({alerts: alerts});
}
);
return d.promise;
});
}
// When the from-file component is displayed in a dialog, the create
// button is outside the component since it is in the wizard footer. Listen
// for an event for when the button is clicked.
$scope.$on('importFileFromYAMLOrJSON', $scope.create);
$scope.$on('$destroy', hideErrorNotifications);
}
};
});