Bug 278 - Allow updating of NSD when there are instantiated network services
[osm/UI.git] / skyquake / plugins / composer / src / src / stores / CatalogDataStore.js
1
2 /*
3 *
4 * Copyright 2016 RIFT.IO Inc
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * 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 */
19 'use strict';
20
21 import _pick from 'lodash/pick'
22 import _isEqual from 'lodash/isEqual'
23 import _cloneDeep from 'lodash/cloneDeep'
24 import cc from 'change-case'
25 import alt from '../alt'
26 import UID from '../libraries/UniqueId'
27 import guid from '../libraries/guid'
28 import React from 'react'
29 import DescriptorModel from '../libraries/model/DescriptorModel'
30 import DescriptorModelMetaFactory from '../libraries/model/DescriptorModelMetaFactory'
31 import CatalogPackageManagerActions from '../actions/CatalogPackageManagerActions'
32 import CatalogDataSourceActions from '../actions/CatalogDataSourceActions'
33 import CatalogItemsActions from '../actions/CatalogItemsActions'
34 import ModalOverlayActions from '../actions/ModalOverlayActions'
35 import ComposerAppActions from '../actions/ComposerAppActions'
36 import CatalogDataSource from '../sources/CatalogDataSource'
37 import ComposerAppStore from '../stores/ComposerAppStore'
38 import SelectionManager from '../libraries/SelectionManager'
39
40 const defaults = {
41 catalogs: [],
42 catalogItemExportFormats: ['mano', 'rift'],
43 catalogItemExportGrammars: ['osm', 'tosca']
44 };
45
46 const areCatalogItemsMetaDataEqual = function (a, b) {
47 const metaProps = ['id', 'name', 'short-name', 'description', 'vendor', 'version'];
48 const aMetaData = _pick(a, metaProps);
49 const bMetaData = _pick(b, metaProps);
50 return _isEqual(aMetaData, bMetaData);
51 };
52
53 function createItem (type) {
54 let newItem = DescriptorModelMetaFactory.createModelInstanceForType(type);
55 if (newItem){
56 newItem.id = guid();
57 UID.assignUniqueId(newItem.uiState);
58 newItem.uiState.isNew = true;
59 newItem.uiState.modified = true;
60 }
61 return newItem;
62 }
63
64 class CatalogDataStore {
65
66 constructor() {
67 this.catalogs = defaults.catalogs;
68 this.isLoading = true;
69 this.requiresSave = false;
70 this.snapshots = {};
71 this.selectedFormat = defaults.catalogItemExportFormats[0];
72 this.selectedGrammar = defaults.catalogItemExportGrammars[0];
73 this.registerAsync(CatalogDataSource);
74 this.bindActions(CatalogDataSourceActions);
75 this.bindActions(CatalogItemsActions);
76 this.exportPublicMethods({
77 getCatalogs: this.getCatalogs,
78 getCatalogItemById: this.getCatalogItemById,
79 getCatalogItemByUid: this.getCatalogItemByUid,
80 getTransientCatalogs: this.getTransientCatalogs,
81 getTransientCatalogItemById: this.getTransientCatalogItemById,
82 getTransientCatalogItemByUid: this.getTransientCatalogItemByUid
83 });
84 }
85
86 resetSelectionState = () => {
87 this.selectedFormat = defaults.catalogItemExportFormats[0];
88 this.selectedGrammar = defaults.catalogItemExportGrammars[0];
89 }
90
91 getCatalogs() {
92 return this.catalogs || (this.catalogs = []);
93 }
94
95 getTransientCatalogs() {
96 return this.state.catalogs || (this.state.catalogs = []);
97 }
98
99 getAllSelectedCatalogItems() {
100 return this.getCatalogs().reduce((r, d) => {
101 d.descriptors.forEach(d => {
102 if (SelectionManager.isSelected(d) /*d.uiState.selected*/) {
103 r.push(d);
104 }
105 });
106 return r;
107 }, []);
108 }
109
110 getFirstSelectedCatalogItem() {
111 return this.getCatalogs().reduce((r, catalog) => {
112 return r.concat(catalog.descriptors.filter(d => SelectionManager.isSelected(d) /*d.uiState.selected*/));
113 }, [])[0];
114 }
115
116 getCatalogItemById(id) {
117 return this.getCatalogs().reduce((r, catalog) => {
118 return r.concat(catalog.descriptors.filter(d => d.id === id));
119 }, [])[0];
120 }
121
122 getTransientCatalogItemById(id) {
123 return this.getTransientCatalogs().reduce((r, catalog) => {
124 return r.concat(catalog.descriptors.filter(d => d.id === id));
125 }, [])[0];
126 }
127
128 getCatalogItemByUid(uid) {
129 return this.getCatalogs().reduce((r, catalog) => {
130 return r.concat(catalog.descriptors.filter(d => UID.from(d) === uid));
131 }, [])[0];
132 }
133
134 getTransientCatalogItemByUid(uid) {
135 return this.getTransientCatalogs().reduce((r, catalog) => {
136 return r.concat(catalog.descriptors.filter(d => UID.from(d) === uid));
137 }, [])[0];
138 }
139
140 removeCatalogItem(deleteItem = {}) {
141 this.getCatalogs().map(catalog => {
142 catalog.descriptors = catalog.descriptors.filter(d => d.id !== deleteItem.id);
143 return catalog;
144 });
145 }
146
147 addNewItemToCatalog(newItem) {
148 const type = newItem.uiState.type;
149 this.getCatalogs().filter(d => d.type === type).forEach(catalog => {
150 catalog.descriptors.push(newItem);
151 });
152 // update indexes and integrate new model into catalog
153 this.updateCatalogIndexes(this.getCatalogs());
154 return this.getCatalogItemById(newItem.id);
155 }
156
157 updateCatalogIndexes(catalogs) {
158 // associate catalog identity with individual descriptors so we can
159 // update the catalog when any given descriptor is updated also add
160 // vnfd model to the nsd object to make it easier to render an nsd
161 const vnfdLookup = {};
162 const updatedCatalogs = catalogs.map(catalog => {
163 catalog.descriptors.map(descriptor => {
164 if (typeof descriptor.meta === 'string' && descriptor.meta.trim() !== '') {
165 try {
166 descriptor.uiState = JSON.parse(descriptor.meta);
167 } catch (ignore) {
168 console.warn('Unable to deserialize the uiState property.');
169 }
170 } else if (typeof descriptor.meta === 'object') {
171 descriptor.uiState = descriptor.meta;
172 descriptor.meta = JSON.stringify(descriptor.meta);
173 }
174
175 const uiState = descriptor.uiState || (descriptor.uiState = {});
176 uiState.catalogId = catalog.id;
177 uiState.catalogName = catalog.name;
178 uiState.type = catalog.type;
179 if (!UID.hasUniqueId(uiState)) {
180 UID.assignUniqueId(uiState);
181 }
182 if (catalog.type === 'vnfd') {
183 vnfdLookup[descriptor.id] = descriptor;
184 }
185 return descriptor;
186 });
187 return catalog;
188 });
189 updatedCatalogs.filter(d => d.type === 'nsd').forEach(catalog => {
190 catalog.descriptors = catalog.descriptors.map(descriptor => {
191 if (descriptor['constituent-vnfd']) {
192 descriptor.vnfd = descriptor['constituent-vnfd'].map(d => {
193 const vnfdId = d['vnfd-id-ref'];
194 const vnfd = vnfdLookup[vnfdId];
195 if (!vnfd) {
196 throw new ReferenceError('no VNFD found in the VNFD Catalog for the constituent-vnfd: ' + d);
197 }
198 // create an instance of this vnfd to carry transient ui state properties
199 const instance = _cloneDeep(vnfd);
200 instance.uiState['member-vnf-index'] = d['member-vnf-index'];
201 instance['vnf-configuration'] = d['vnf-configuration'];
202 instance['start-by-default'] = d['start-by-default'];
203 return instance;
204 });
205 }
206 return descriptor;
207 });
208 });
209 return updatedCatalogs;
210 }
211
212 updateCatalogItem(item) {
213 // replace the given item in the catalog
214 const catalogs = this.getCatalogs().map(catalog => {
215 if (catalog.id === item.uiState.catalogId) {
216 catalog.descriptors = catalog.descriptors.map(d => {
217 if (d.id === item.id) {
218 return item;
219 }
220 return d;
221 });
222 }
223 return catalog;
224 });
225 this.setState({catalogs: catalogs});
226 }
227
228 mergeEditsIntoLatestFromServer(catalogsFromServer = []) {
229
230 // if the UI has modified items use them instead of the server items
231
232 const currentData = this.getCatalogs();
233
234 const modifiedItemsMap = currentData.reduce((result, catalog) => {
235 return result.concat(catalog.descriptors.filter(d => d.uiState.modified));
236 }, []).reduce((r, d) => {
237 r[d.uiState.catalogId + '/' + d.id] = d;
238 return r;
239 }, {});
240
241 const itemMetaMap = currentData.reduce((result, catalog) => {
242 return result.concat(catalog.descriptors.filter(d => d.uiState));
243 }, []).reduce((r, d) => {
244 r[d.uiState.catalogId + '/' + d.id] = d.uiState;
245 return r;
246 }, {});
247
248 const newItemsMap = currentData.reduce((result, catalog) => {
249 result[catalog.id] = catalog.descriptors.filter(d => d.uiState.isNew);
250 return result;
251 }, {});
252
253 catalogsFromServer.forEach(catalog => {
254 catalog.descriptors = catalog.descriptors.map(d => {
255 const key = d.uiState.catalogId + '/' + d.id;
256 if (modifiedItemsMap[key]) {
257 // use local modified item instead of the server item
258 return modifiedItemsMap[key];
259 }
260 if (itemMetaMap[key]) {
261 Object.assign(d.uiState, itemMetaMap[key]);
262 }
263 return d;
264 });
265 if (newItemsMap[catalog.id]) {
266 catalog.descriptors = catalog.descriptors.concat(newItemsMap[catalog.id]);
267 }
268 });
269
270 return catalogsFromServer;
271
272 }
273
274 loadCatalogsSuccess(context) {
275 const fromServer = this.updateCatalogIndexes(context.data);
276 const catalogs = this.mergeEditsIntoLatestFromServer(fromServer);
277 this.setState({
278 catalogs: catalogs,
279 isLoading: false
280 });
281 }
282
283 deleteCatalogItemSuccess (response) {
284 let catalogType = response.catalogType;
285 let itemId = response.itemId;
286 const catalogs = this.getCatalogs().map(catalog => {
287 if (catalog.type === catalogType) {
288 catalog.descriptors = catalog.descriptors.filter(d => d.id !== itemId);
289 }
290 return catalog;
291 });
292
293 this.setState({catalogs: catalogs});
294 }
295
296 deleteCatalogItemError (data) {
297 console.log('Unable to delete', data.catalogType, 'id:', data.itemId, 'Error:', data.error.responseText);
298 ComposerAppActions.showError.defer({
299 errorMessage: 'Unable to delete ' + data.catalogType + ' id: ' + data.itemId + '. Check if it is in use'
300 });
301 }
302
303 selectCatalogItem(item = {}) {
304 SelectionManager.select(item);
305 }
306
307 catalogItemMetaDataChanged(item) {
308 let requiresSave = false;
309 const catalogs = this.getCatalogs().map(catalog => {
310 if (catalog.id === item.uiState.catalogId) {
311 catalog.descriptors = catalog.descriptors.map(d => {
312 if (d.id === item.id) {
313 // compare just the catalog uiState data (id, name, short-name, description, etc.)
314 const modified = !areCatalogItemsMetaDataEqual(d, item);
315 if (modified) {
316 item.uiState.modified = modified;
317 requiresSave = true;
318 this.addSnapshot(item);
319 }
320 return item;
321 }
322 return d;
323 });
324 }
325 return catalog;
326 });
327 if (requiresSave) {
328 this.setState({catalogs: catalogs, requiresSave: true});
329 }
330 }
331
332 catalogItemDescriptorChanged(itemDescriptor) {
333 // when a descriptor object is modified in the canvas we have to update the catalog
334 const catalogId = itemDescriptor.uiState.catalogId;
335 const catalogs = this.getCatalogs().map(catalog => {
336 if (catalog.id === catalogId) {
337 // find the catalog
338 const descriptorId = itemDescriptor.id;
339 // replace the old descriptor with the updated one
340 catalog.descriptors = catalog.descriptors.map(d => {
341 if (d.id === descriptorId) {
342 itemDescriptor.model.uiState.modified = true;
343 this.addSnapshot(itemDescriptor.model);
344 return itemDescriptor.model;
345 }
346 return d;
347 });
348 }
349 return catalog;
350 });
351 this.setState({catalogs: catalogs, requiresSave: true})
352 }
353
354 deleteSelectedCatalogItem() {
355 SelectionManager.getSelections().forEach(selectedId => {
356 const item = this.getCatalogItemByUid(selectedId);
357 if (item) {
358 this.deleteCatalogItem(item);
359 }
360 });
361 SelectionManager.clearSelectionAndRemoveOutline();
362 }
363
364 deleteCatalogItem(item) {
365 const snapshot = JSON.stringify(item);
366 function confirmDeleteCancel(event) {
367 undo();
368 event.preventDefault();
369 ModalOverlayActions.hideModalOverlay();
370 }
371 const remove = () => {
372 // item is deleted or does not exist on server, so remove from ui
373 this.removeCatalogItem(item);
374 this.setState({catalogs: this.getCatalogs()});
375 const activeItem = ComposerAppStore.getState().item;
376 if (activeItem && activeItem.id === item.id) {
377 CatalogItemsActions.editCatalogItem.defer(null);
378 }
379 ModalOverlayActions.hideModalOverlay();
380 };
381 const undo = () => {
382 // item failed to delete on server so revert ui
383 const revertTo = JSON.parse(snapshot);
384 this.updateCatalogItem(revertTo);
385 const activeItem = ComposerAppStore.getState().item;
386 if (activeItem && activeItem.id === revertTo.id) {
387 SelectionManager.select(activeItem);
388 CatalogItemsActions.editCatalogItem.defer(revertTo);
389 SelectionManager.refreshOutline();
390 }
391 };
392 if (item) {
393 if (item.uiState.isNew) {
394 CatalogDataStore.confirmDelete(remove, confirmDeleteCancel);
395 } else {
396 const confirmDeleteOK = event => {
397 event.preventDefault();
398 item.uiState.deleted = true;
399 this.setState({catalogs: this.getCatalogs()});
400 ModalOverlayActions.showModalOverlay.defer();
401 this.getInstance().deleteCatalogItem(item.uiState.type, item.id)
402 .then(remove, undo)
403 .then(ModalOverlayActions.hideModalOverlay, ModalOverlayActions.hideModalOverlay)
404 .catch(function() {
405 console.log('overcoming ES6 unhandled rejection red herring');
406 });
407 };
408 CatalogDataStore.confirmDelete(confirmDeleteOK, confirmDeleteCancel);
409 }
410 }
411 }
412
413 static confirmDelete(onClickYes, onClickCancel) {
414 ModalOverlayActions.showModalOverlay.defer((
415 <div className="actions panel">
416 <div className="panel-header">
417 <h1>Delete the selected catalog item?</h1>
418 </div>
419 <div className="panel-body">
420 <a className="action confirm-yes primary-action Button" onClick={onClickYes}>Yes, delete selected catalog item</a>
421 <a className="action cancel secondary-action Button" onClick={onClickCancel}>No, cancel</a>
422 </div>
423 </div>
424 ));
425 }
426
427 createCatalogItem(type = 'nsd') {
428 const newItem = createItem(type);
429 this.saveItem(newItem)
430 }
431
432 duplicateSelectedCatalogItem() {
433 // make request to backend to duplicate an item
434 const srcItem = this.getFirstSelectedCatalogItem();
435 if (srcItem) {
436 CatalogPackageManagerActions.copyCatalogPackage.defer(srcItem);
437 }
438 }
439
440 addSnapshot(item) {
441 if (item) {
442 if (!this.snapshots[item.id]) {
443 this.snapshots[item.id] = [];
444 }
445 this.snapshots[item.id].push(JSON.stringify(item));
446 }
447 }
448
449 resetSnapshots(item) {
450 if (item) {
451 this.snapshots[item.id] = [];
452 this.addSnapshot(item);
453 }
454 }
455
456 editCatalogItem(item) {
457 if (item) {
458 this.addSnapshot(item);
459 // replace the given item in the catalog
460 const catalogs = this.getCatalogs().map(catalog => {
461 catalog.descriptors = catalog.descriptors.map(d => {
462 // note only one item can be "open" at a time
463 // so remove the flag from all the other items
464 d.uiState.isOpenForEdit = (d.id === item.id);
465 if (d.uiState.isOpenForEdit) {
466 return item;
467 }
468 return d;
469 });
470 return catalog;
471 });
472 this.setState({catalogs: catalogs});
473 this.catalogItemMetaDataChanged(item);
474 }
475 }
476
477 cancelCatalogItemChanges() {
478 const activeItem = ComposerAppStore.getState().item;
479 if (activeItem) {
480 const snapshots = this.snapshots[activeItem.id];
481 if (snapshots.length) {
482 const revertTo = JSON.parse(snapshots[0]);
483 this.updateCatalogItem(revertTo);
484 // TODO should the cancel action clear the undo/redo stack back to the beginning?
485 this.resetSnapshots(revertTo);
486 this.setState({requiresSave: false});
487 CatalogItemsActions.editCatalogItem.defer(revertTo);
488 }
489 }
490 }
491
492 saveCatalogItem() {
493 const activeItem = ComposerAppStore.getState().item;
494 if (activeItem) {
495 this.saveItem(activeItem);
496 }
497 }
498
499 saveItem(item) {
500 if (item) {
501 const success = () => {
502 delete item.uiState.modified;
503 if (item.uiState.isNew) {
504 this.addNewItemToCatalog(item);
505 delete item.uiState.isNew;
506 } else {
507 this.updateCatalogItem(item);
508 }
509 // TODO should the save action clear the undo/redo stack back to the beginning?
510 this.resetSnapshots(item);
511 ModalOverlayActions.hideModalOverlay.defer();
512 CatalogItemsActions.editCatalogItem.defer(item);
513 };
514 const failure = () => {
515 ModalOverlayActions.hideModalOverlay.defer();
516 CatalogItemsActions.editCatalogItem.defer(item);
517 };
518 const exception = () => {
519 console.warn('unable to save catalog item', item);
520 ModalOverlayActions.hideModalOverlay.defer();
521 CatalogItemsActions.editCatalogItem.defer(item);
522 };
523 ModalOverlayActions.showModalOverlay.defer();
524 this.getInstance().saveCatalogItem(item).then(success, failure).catch(exception);
525 }
526 }
527
528 exportSelectedCatalogItems(draggedItem) {
529 // collect the selected items and delegate to the catalog package manager action creator
530 const selectedItems = this.getAllSelectedCatalogItems();
531 if (selectedItems.length) {
532 CatalogPackageManagerActions.downloadCatalogPackage.defer({
533 selectedItems: selectedItems,
534 selectedFormat: 'mano',
535 selectedGrammar: 'osm'
536 });
537 this.resetSelectionState();
538 }
539 }
540 saveCatalogItemError(data){
541 let error = JSON.parse(data.error.responseText);
542 const errorMsg = error && error.body && error.body['rpc-reply'] && JSON.stringify(error.body['rpc-reply']['rpc-error'], null, ' ')
543 ComposerAppActions.showError.defer({
544 errorMessage: 'Unable to save the descriptor.\n' + errorMsg
545 });
546 }
547 }
548
549 export default alt.createStore(CatalogDataStore, 'CatalogDataStore');