forked from camunda/camunda-modeler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DeploymentTool.js
668 lines (515 loc) · 16.3 KB
/
DeploymentTool.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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
/**
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership.
*
* Camunda licenses this file to you under the MIT; you may not use this file
* except in compliance with the MIT License.
*/
import React, { PureComponent } from 'react';
import { omit } from 'min-dash';
import classNames from 'classnames';
import { default as CamundaAPI, ApiErrors, ConnectionError } from '../shared/CamundaAPI';
import AUTH_TYPES from '../shared/AuthTypes';
import CockpitDeploymentLink from '../shared/ui/CockpitDeploymentLink';
import DeploymentConfigOverlay from './DeploymentConfigOverlay';
import DeploymentConfigValidator from './validation/DeploymentConfigValidator';
import { DeploymentError } from '../shared/CamundaAPI';
import * as css from './DeploymentTool.less';
import {
generateId
} from '../../../util';
import { Fill } from '../../../app/slot-fill';
import DeployIcon from 'icons/Deploy.svg';
import { ENGINES } from '../../../util/Engines';
const DEPLOYMENT_DETAILS_CONFIG_KEY = 'deployment-tool';
const ENGINE_ENDPOINTS_CONFIG_KEY = 'camundaEngineEndpoints';
const PROCESS_DEFINITION_CONFIG_KEY = 'process-definition';
const SELF_HOSTED = 'selfHosted';
const DEFAULT_ENDPOINT = {
url: 'http://localhost:8080/rest',
authType: AUTH_TYPES.BASIC,
rememberCredentials: false
};
const TOMCAT_DEFAULT_URL = 'http://localhost:8080/engine-rest';
export default class DeploymentTool extends PureComponent {
constructor() {
super();
this.state = {
overlayState: null,
activeTab: null,
anchor: null
};
this.validator = new DeploymentConfigValidator();
this._anchorRef = React.createRef();
}
componentDidMount() {
this.props.subscribe('app.activeTabChanged', ({ activeTab }) => {
this.setState({
activeTab,
overlayState: null,
activeButton: false
});
});
this.props.subscribe('app.focus-changed', () => {
if (this.focusChangeCallback) {
this.focusChangeCallback();
}
});
}
subscribeToFocusChange = (callback) => {
this.focusChangeCallback = callback;
};
unsubscribeFromFocusChange = () => {
delete this.focusChangeCallback;
};
saveTab = (tab) => {
const {
triggerAction
} = this.props;
return triggerAction('save-tab', { tab });
};
deploy = (options = {}) => {
const {
activeTab
} = this.state;
return this.deployTab(activeTab, options, this._anchorRef);
};
async deployTab(tab, options = {}, anchor) {
const {
configure
} = options;
// (1) Open save file dialog if dirty
tab = await this.saveTab(tab);
// (1.1) Cancel deploy if file save cancelled
if (!tab) {
return;
}
// (2) Get deployment configuration
// (2.1) Try to get existing deployment configuration
let configuration = await this.getSavedConfiguration(tab);
// (2.2) Check if configuration are complete
const showConfiguration = configure || !this.canDeployWithConfiguration(configuration);
if (showConfiguration) {
// (2.3) Open modal to enter deployment configuration
const {
action,
configuration: userConfiguration
} = await this.getConfigurationFromUserInput(tab, configuration, { anchor });
// (2.3.1) Handle user cancelation
if (action === 'cancel') {
return;
}
configuration = await this.saveConfiguration(tab, userConfiguration);
if (action === 'save') {
return;
}
}
// (3) Trigger deployment
let version;
try {
// (3.1) Retrieve version we deploy to via API
try {
version = (await this.getVersion(configuration)).version;
} catch (error) {
if (!(error instanceof ConnectionError)) {
throw error;
}
version = null;
}
// (3.2) Deploy via API
const deployment = await this.deployWithConfiguration(tab, configuration);
// (3.3) save deployed process definition
await this.saveProcessDefinition(tab, deployment);
// (3.4) Handle deployment success or error
await this.handleDeploymentSuccess(tab, deployment, version, configuration);
} catch (error) {
if (!(error instanceof DeploymentError)) {
throw error;
}
await this.handleDeploymentError(tab, error, version);
}
}
handleDeploymentSuccess(tab, deployment, version, configuration) {
const {
displayNotification,
triggerAction
} = this.props;
const {
endpoint
} = configuration;
const {
url
} = endpoint;
displayNotification({
type: 'success',
title: `${getDeploymentType(tab)} deployed`,
content: <CockpitDeploymentLink engineRestUrl={ url } deployment={ deployment } />,
duration: 8000
});
// notify interested parties
triggerAction('emit-event', {
type: 'deployment.done',
payload: {
deployment,
targetType: SELF_HOSTED,
deployedTo: {
executionPlatformVersion: version,
executionPlatform: ENGINES.PLATFORM
},
context: 'deploymentTool'
}
});
}
async saveProcessDefinition(tab, deployment) {
if (!deployment || !deployment.deployedProcessDefinition) {
return;
}
const {
deployedProcessDefinition: processDefinition
} = deployment;
const {
config
} = this.props;
return await config.setForFile(tab.file, PROCESS_DEFINITION_CONFIG_KEY, processDefinition);
}
handleDeploymentError(tab, error, version) {
const {
log,
displayNotification,
triggerAction
} = this.props;
const logMessage = {
category: 'deploy-error',
message: error.problems || error.details || error.message,
silent: true
};
log(logMessage);
const content = <button
onClick={ () => triggerAction('open-log') }>
See the log for further details.
</button>;
displayNotification({
type: 'error',
title: 'Deployment failed',
content,
duration: 4000
});
// If we retrieved the executionPlatformVersion, include it in event
const deployedTo = (version &&
{ executionPlatformVersion: version, executionPlatform: ENGINES.PLATFORM }) || undefined;
// notify interested parties
triggerAction('emit-event', {
type: 'deployment.error',
payload: {
error,
targetType: SELF_HOSTED,
context: 'deploymentTool',
...(deployedTo && { deployedTo: deployedTo })
}
});
}
async saveConfiguration(tab, configuration) {
const {
endpoint,
deployment
} = configuration;
await this.saveEndpoint(endpoint);
const tabConfiguration = {
deployment: withSerializedAttachments(deployment),
endpointId: endpoint.id
};
await this.setTabConfiguration(tab, tabConfiguration);
return configuration;
}
removeCredentials = async () => {
const savedConfiguration = await this.getSavedConfiguration(this.state.activeTab);
// do not remove credentials from a non existing endpoint configuration
if (!savedConfiguration || !savedConfiguration.endpoint) {
return;
}
this.saveEndpoint({
...savedConfiguration.endpoint,
rememberCredentials: false
});
};
saveCredentials = async (credentials) => {
const savedConfiguration = await this.getSavedConfiguration(this.state.activeTab);
// do not save credentials on a non existing endpoint configuration
if (!savedConfiguration || !savedConfiguration.endpoint) {
return;
}
this.saveEndpoint({
...savedConfiguration.endpoint,
rememberCredentials: true,
...credentials
});
};
async saveEndpoint(endpoint) {
const {
rememberCredentials
} = endpoint;
const endpointToSave = rememberCredentials ? endpoint : withoutCredentials(endpoint);
const existingEndpoints = await this.getEndpoints();
const updatedEndpoints = addOrUpdateById(existingEndpoints, endpointToSave);
await this.setEndpoints(updatedEndpoints);
return endpointToSave;
}
async getSavedConfiguration(tab) {
const tabConfig = await this.getTabConfiguration(tab);
if (!tabConfig) {
return undefined;
}
const {
deployment,
endpointId
} = tabConfig;
const deploymentWithAttachments = await this.withAttachments(deployment);
const endpoints = await this.getEndpoints();
return {
deployment: deploymentWithAttachments,
endpoint: endpoints.find(endpoint => endpoint.id === endpointId)
};
}
deployWithConfiguration(tab, configuration) {
const {
endpoint,
deployment
} = configuration;
const api = new CamundaAPI(endpoint);
return api.deployDiagram(tab.file, deployment);
}
getVersion(configuration) {
const { endpoint } = configuration;
const api = new CamundaAPI(endpoint);
return api.getVersion();
}
canDeployWithConfiguration(configuration) {
return this.validator.isConfigurationValid(configuration);
}
async getConfigurationFromUserInput(tab, providedConfiguration, uiOptions) {
const configuration = await this.getDefaultConfiguration(tab, providedConfiguration);
return new Promise(resolve => {
const handleClose = (action, configuration) => {
this.setState({
overlayState: null,
activeButton: false
});
// inform validator to cancel ongoing requests
this.validator.cancel();
// contract: if configuration provided, user closed with O.K.
// otherwise they canceled it
return resolve({ action, configuration });
};
this.setState({
overlayState: {
tab,
configuration,
handleClose,
...uiOptions
}
});
});
}
async withAttachments(deployment) {
const fileSystem = this.props._getGlobal('fileSystem');
const { attachments = [] } = deployment;
async function readFile(path) {
try {
// (1) try to read file from file system
const file = await fileSystem.readFile(path, { encoding: false });
// (2a) store contents as a File object
// @barmac: This is required for the performance reasons. The contents retrieved from FS
// is a Uint8Array. During the form submission, Formik builds a map of touched fields
// and it traverses all nested objects for that. The outcome was that the form would freeze
// for a couple of seconds when one tried to re-deploy a file of size >1MB, because Formik
// tried to build a map with bits' indexes as keys with all values as `true`. Wrapping the
// contents in a File object prevents such behavior.
return {
...file,
contents: new File([ file.contents ], file.name)
};
} catch {
// (2b) if read fails, return an empty file descriptor
return {
contents: null,
path,
name: basename(path)
};
}
}
const files = await Promise.all(attachments.map(({ path }) => readFile(path)));
return {
...deployment,
attachments: files
};
}
getEndpoints() {
return this.props.config.get(ENGINE_ENDPOINTS_CONFIG_KEY, []);
}
setEndpoints(endpoints) {
return this.props.config.set(ENGINE_ENDPOINTS_CONFIG_KEY, endpoints);
}
getTabConfiguration(tab) {
return this.props.config.getForFile(tab.file, DEPLOYMENT_DETAILS_CONFIG_KEY);
}
setTabConfiguration(tab, configuration) {
return this.props.config.setForFile(tab.file, DEPLOYMENT_DETAILS_CONFIG_KEY, configuration);
}
/**
* Get endpoint to be used by the current tab.
*
* @return {EndpointConfig}
*/
async getDefaultEndpoint(tab, providedEndpoint) {
let endpoint = {},
defaultUrl = DEFAULT_ENDPOINT.url;
if (providedEndpoint) {
endpoint = providedEndpoint;
} else {
const existingEndpoints = await this.getEndpoints();
if (existingEndpoints.length) {
endpoint = existingEndpoints[0];
}
}
if (!endpoint.url && (await this.isTomcatRunning())) {
defaultUrl = TOMCAT_DEFAULT_URL;
}
// since we have deprecated AUTH_TYPES.none, we should correct existing
// configurations
if (endpoint.authType !== AUTH_TYPES.BASIC && endpoint.authType !== AUTH_TYPES.BEARER) {
endpoint.authType = DEFAULT_ENDPOINT.authType;
}
return {
...DEFAULT_ENDPOINT,
url: defaultUrl,
...endpoint,
id: endpoint.id || generateId()
};
}
async getDefaultConfiguration(tab, providedConfiguration = {}) {
const endpoint = await this.getDefaultEndpoint(tab, providedConfiguration.endpoint);
const deployment = providedConfiguration.deployment || {};
return {
endpoint,
deployment: {
attachments: [],
name: withoutExtension(tab.name),
...deployment
}
};
}
async isTomcatRunning() {
const result = await this.validator.validateConnectionWithoutCredentials(TOMCAT_DEFAULT_URL);
if (!result) {
return true;
}
const { code } = result;
return (code !== ApiErrors.NO_INTERNET_CONNECTION &&
code !== ApiErrors.CONNECTION_FAILED &&
code !== ApiErrors.NOT_FOUND);
}
closeOverlay(overlayState) {
const currentModalState = overlayState || this.state.overlayState;
currentModalState.handleClose('cancel', null);
}
render() {
const {
activeTab,
overlayState
} = this.state;
// TODO(nikku): we'll remove the flag once we make re-deploy
// the primary button action: https://github.com/camunda/camunda-modeler/issues/1440
const isDeployOpen = () => {
return overlayState ? overlayState.anchor === this._anchorRef : false;
};
const onClick = () => {
if (overlayState) {
this.closeOverlay(overlayState);
} else {
this.deploy({ configure: true });
}
};
return <React.Fragment>
{ isCamundaTab(activeTab) && <Fill slot="status-bar__file" group="8_deploy">
<button
onClick={ onClick }
title="Deploy current diagram"
className={ classNames('btn', css.DeploymentTool, { 'btn--active': isDeployOpen() }) }
ref={ this._anchorRef }
>
<DeployIcon className="icon" />
</button>
</Fill> }
{ overlayState &&
<DeploymentConfigOverlay
configuration={ overlayState.configuration }
activeTab={ overlayState.tab }
title={ overlayState.title }
intro={ overlayState.intro }
primaryAction={ overlayState.primaryAction }
onClose={ overlayState.handleClose }
validator={ this.validator }
saveCredentials={ this.saveCredentials }
removeCredentials={ this.removeCredentials }
subscribeToFocusChange={ this.subscribeToFocusChange }
unsubscribeFromFocusChange={ this.unsubscribeFromFocusChange }
anchor={ overlayState ? overlayState.anchor.current : null }
/>
}
</React.Fragment>;
}
}
// helpers //////////
function withoutExtension(name) {
return name.replace(/\.[^.]+$/, '');
}
function withoutCredentials(endpoint) {
return omit(endpoint, [ 'username', 'password', 'token' ]);
}
function addOrUpdateById(collection, element) {
const index = collection.findIndex(el => el.id === element.id);
if (index !== -1) {
return [
...collection.slice(0, index),
element,
...collection.slice(index + 1)
];
}
return [
...collection,
element
];
}
function isCamundaTab(tab) {
return tab && [
'bpmn',
'cmmn',
'dmn',
'form'
].includes(tab.type);
}
function getDeploymentType(tab) {
const { type } = tab;
if (type === 'bpmn') {
return 'Process definition';
}
else if (type === 'dmn') {
return 'Decision definition';
}
else if (type === 'cmmn') {
return 'Case definition';
}
else if (type === 'form') {
return 'Form';
}
}
function withSerializedAttachments(deployment) {
const { attachments: fileList = [] } = deployment;
const attachments = fileList.map(file => ({ path: file.path }));
return { ...deployment, attachments };
}
function basename(filePath) {
return filePath.split('\\').pop().split('/').pop();
}