-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathtasks.ts
1553 lines (1429 loc) · 52.2 KB
/
tasks.ts
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as R from 'ramda';
import {
connect,
AmqpConnectionManager,
ChannelWrapper
} from 'amqp-connection-manager';
import { ConfirmChannel, ConsumeMessage } from 'amqplib';
import { logger } from './logs/local-logger';
import {
EnvKeyValue,
EnvVariableScope,
Kubernetes,
Project,
getEnvironmentsForProject,
getOpenShiftInfoForProject,
getOpenShiftInfoForEnvironment,
getEnvironmentByIdWithVariables,
addOrUpdateEnvironment,
getEnvironmentByName,
addDeployment,
getOrganizationByIdWithEnvs,
getOrganizationById,
} from './api';
import {
deployTargetBranches,
deployTargetPullrequest,
deployTargetPromote
} from './deploy-tasks';
import { InternalEnvVariableScope } from './types';
import sha1 from 'sha1';
import crypto from 'crypto';
import moment from 'moment';
import { jsonMerge } from './util/func'
interface MessageConsumer {
(msg: ConsumeMessage): Promise<void>;
}
interface RetryHandler {
(
msg: ConsumeMessage,
error: Error,
retryCount: number,
retryExpirationSecs: number
): void;
}
interface DeathHandler {
(msg: ConsumeMessage, error: Error): void;
}
export let sendToLagoonTasks = function(
task: string,
payload?: any
) {
// TODO: Actually do something here?
return payload && undefined;
};
export let sendToLagoonTasksMonitor = function sendToLagoonTasksMonitor(
task: string,
payload?: any
) {
// TODO: Actually do something here?
return payload && undefined;
};
export let sendToLagoonActions = function(
task: string,
payload?: any
) {
// TODO: Actually do something here?
return payload && undefined;
};
// TODO: This is weird, why do we need an empty default connection? Or is there
// a better way to type this?
const defaultConnection: AmqpConnectionManager = {
// Default function for Event
removeListener: (() => {}) as any,
off: (() => {}) as any,
removeAllListeners: (() => {}) as any,
setMaxListeners: (() => {}) as any,
getMaxListeners: (() => {}) as any,
listeners: (() => {}) as any,
rawListeners: (() => {}) as any,
emit: (() => {}) as any,
eventNames: (() => {}) as any,
listenerCount: (() => {}) as any,
// Default functions for AmqpConnectionManager
addListener: (() => {}) as any,
on: (() => {}) as any,
once: (() => {}) as any,
prependListener: (() => {}) as any,
prependOnceListener: (() => {}) as any,
createChannel: (() => {}) as any,
isConnected: (() => {}) as any,
close: (() => {}) as any
};
export let connection: AmqpConnectionManager = defaultConnection;
const rabbitmqHost = process.env.RABBITMQ_HOST || 'broker';
const rabbitmqUsername = process.env.RABBITMQ_USERNAME || 'guest';
const rabbitmqPassword = process.env.RABBITMQ_PASSWORD || 'guest';
const taskPrefetch = process.env.TASK_PREFETCH_COUNT ? Number(process.env.TASK_PREFETCH_COUNT) : 2;
const taskMonitorPrefetch = process.env.TASKMONITOR_PREFETCH_COUNT ? Number(process.env.TASKMONITOR_PREFETCH_COUNT) : 1;
// these are required for the builddeploydata creation
// they match what are used in the kubernetesbuilddeploy service
// @TODO: INFO
// some of these variables will need to be added to webhooks2tasks in the event that overwriting is required
// deploys received by that webhooks2tasks will use functions exported by tasks, where previously they would be passed to a seperate service
// this is because there is no single service handling deploy tasks when the controller is used
// currently the services that may need to use these variables are:
// * `api`
// * `webhooks2tasks`
const CI = process.env.CI || "false"
const lagoonGitSafeBranch = process.env.LAGOON_GIT_SAFE_BRANCH || "master"
const lagoonVersion = process.env.LAGOON_VERSION
const lagoonEnvironmentType = process.env.LAGOON_ENVIRONMENT_TYPE || "development"
const defaultBuildDeployImage = process.env.DEFAULT_BUILD_DEPLOY_IMAGE
const edgeBuildDeployImage = process.env.EDGE_BUILD_DEPLOY_IMAGE
const overwriteActiveStandbyTaskImage = process.env.OVERWRITE_ACTIVESTANDBY_TASK_IMAGE
const jwtSecretString = process.env.JWTSECRET || "super-secret-string"
const projectSeedString = process.env.PROJECTSEED || "super-secret-string"
class NoNeedToRemoveBranch extends Error {
constructor(message) {
super(message);
this.name = 'NoNeedToRemoveBranch';
}
}
class DeployTargetDisabled extends Error {
constructor(message) {
super(message);
this.name = 'DeployTargetDisabled';
}
}
class CannotDeleteProductionEnvironment extends Error {
constructor(message) {
super(message);
this.name = 'CannotDeleteProductionEnvironment';
}
}
class EnvironmentLimit extends Error {
constructor(message) {
super(message);
this.name = 'EnvironmentLimit';
}
}
class OrganizationEnvironmentLimit extends Error {
constructor(message) {
super(message);
this.name = 'OrganizationEnvironmentLimit';
}
}
// add the lagoon actions queue publisher functions
export const initSendToLagoonActions = function() {
connection = connect(
[`amqp://${rabbitmqUsername}:${rabbitmqPassword}@${rabbitmqHost}`],
// @ts-ignore
{ json: true }
);
connection.on('connect', ({ url }) =>
logger.verbose('lagoon-actions: Connected to %s', url, {
action: 'connected',
url
})
);
connection.on('disconnect', params =>
// @ts-ignore
logger.error('lagoon-actions: Not connected, error: %s', params.err.code, {
action: 'disconnected',
reason: params
})
);
const channelWrapperTasks: ChannelWrapper = connection.createChannel({
setup(channel: ConfirmChannel) {
return Promise.all([
// Our main Exchange for all lagoon-actions
channel.assertExchange('lagoon-actions', 'direct', { durable: true }),
channel.assertExchange('lagoon-actions-delay', 'x-delayed-message', {
durable: true,
arguments: { 'x-delayed-type': 'fanout' }
}),
channel.bindExchange('lagoon-actions', 'lagoon-actions-delay', ''),
]);
}
});
sendToLagoonActions = async (
task: string,
payload: any
): Promise<string> => {
try {
const buffer = Buffer.from(JSON.stringify(payload));
await channelWrapperTasks.publish('lagoon-actions', '', buffer, {
persistent: true,
appId: task
});
logger.debug(
`lagoon-actions: Successfully created action '${task}'`,
payload
);
return `lagoon-actions: Successfully created action '${task}': ${JSON.stringify(
payload
)}`;
} catch (error) {
logger.error('lagoon-actions: Error send to lagoon-actions exchange', {
payload,
error
});
throw error;
}
};
}
export const initSendToLagoonTasks = function() {
connection = connect(
[`amqp://${rabbitmqUsername}:${rabbitmqPassword}@${rabbitmqHost}`],
// @ts-ignore
{ json: true }
);
connection.on('connect', ({ url }) =>
logger.verbose('lagoon-tasks: Connected to %s', url, {
action: 'connected',
url
})
);
connection.on('disconnect', params =>
// @ts-ignore
logger.error('lagoon-tasks: Not connected, error: %s', params.err.code, {
action: 'disconnected',
reason: params
})
);
const channelWrapperTasks: ChannelWrapper = connection.createChannel({
setup(channel: ConfirmChannel) {
return Promise.all([
// Our main Exchange for all lagoon-tasks
channel.assertExchange('lagoon-tasks', 'direct', { durable: true }),
channel.assertExchange('lagoon-tasks-delay', 'x-delayed-message', {
durable: true,
arguments: { 'x-delayed-type': 'fanout' }
}),
channel.bindExchange('lagoon-tasks', 'lagoon-tasks-delay', ''),
// Exchange for task monitoring
channel.assertExchange('lagoon-tasks-monitor', 'direct', {
durable: true
}),
channel.assertExchange(
'lagoon-tasks-monitor-delay',
'x-delayed-message',
{ durable: true, arguments: { 'x-delayed-type': 'fanout' } }
),
channel.bindExchange(
'lagoon-tasks-monitor',
'lagoon-tasks-monitor-delay',
''
)
]);
}
});
sendToLagoonTasks = async (
task: string,
payload: any
): Promise<string> => {
try {
const buffer = Buffer.from(JSON.stringify(payload));
await channelWrapperTasks.publish('lagoon-tasks', task, buffer, {
persistent: true
});
logger.debug(
`lagoon-tasks: Successfully created task '${task}'`,
payload
);
return `lagoon-tasks: Successfully created task '${task}': ${JSON.stringify(
payload
)}`;
} catch (error) {
logger.error('lagoon-tasks: Error send to lagoon-tasks exchange', {
payload,
error
});
throw error;
}
};
sendToLagoonTasksMonitor = async (
task: string,
payload: any
): Promise<string> => {
try {
const buffer = Buffer.from(JSON.stringify(payload));
await channelWrapperTasks.publish('lagoon-tasks-monitor', task, buffer, {
persistent: true
});
logger.debug(
`lagoon-tasks-monitor: Successfully created monitor '${task}'`,
payload
);
return `lagoon-tasks-monitor: Successfully created task monitor '${task}': ${JSON.stringify(
payload
)}`;
} catch (error) {
logger.error(
'lagoon-tasks-monitor: Error send to lagoon-tasks-monitor exchange',
{
payload,
error
}
);
throw error;
}
};
}
export const createTaskMonitor = async function(task: string, payload: any) {
return sendToLagoonTasksMonitor(task, payload);
}
// makes strings "safe" if it is to be used in something dns related
export const makeSafe = string => string.toLocaleLowerCase().replace(/[^0-9a-z-]/g,'-')
// @TODO: make sure if it fails, it does so properly
export const getControllerBuildData = async function(deployData: any) {
const {
projectName,
branchName,
sha,
type,
pullrequestTitle,
headBranchName: headBranch,
headSha,
baseBranchName: baseBranch,
baseSha,
promoteSourceEnvironment,
deployTarget,
buildName, // buildname now comes from where the deployments are created, this is so it can be returned to the user when it is triggered
buildPriority,
bulkId,
bulkName,
buildVariables,
sourceUser,
sourceType,
} = deployData;
var environmentName = makeSafe(branchName)
const result = await getOpenShiftInfoForProject(projectName);
const lagoonProjectData = result.project
var overlength = 58 - projectName.length;
if ( environmentName.length > overlength ) {
var hash = sha1(environmentName).substring(0,4)
environmentName = environmentName.substring(0, overlength-5)
environmentName = environmentName.concat('-' + hash)
}
var environmentType = 'development'
if (
lagoonProjectData.productionEnvironment === environmentName
|| lagoonProjectData.standbyProductionEnvironment === environmentName
) {
environmentType = 'production'
}
var priority = buildPriority // set the priority to one provided from the build
// if no build priority is provided, then try and source the one from the project
// or default to 5 or 6
if ( priority == null ) {
priority = lagoonProjectData.developmentBuildPriority || 5
if (environmentType == 'production') {
priority = lagoonProjectData.productionBuildPriority || 6
}
}
var gitSha = sha as string
var deployPrivateKey = lagoonProjectData.privateKey
var gitUrl = lagoonProjectData.gitUrl
var projectProductionEnvironment = lagoonProjectData.productionEnvironment
var projectStandbyEnvironment = lagoonProjectData.standbyProductionEnvironment
var subfolder = lagoonProjectData.subfolder || ""
var prHeadBranch = headBranch || ""
var prHeadSha = headSha || ""
var prBaseBranch = baseBranch || ""
var prBaseSha = baseSha || ""
var prPullrequestTitle = pullrequestTitle || ""
var prPullrequestNumber = branchName.replace('pr-','')
var graphqlEnvironmentType = environmentType.toUpperCase()
var graphqlGitType = type.toUpperCase()
var openshiftPromoteSourceProject = promoteSourceEnvironment ? `${projectName}-${makeSafe(promoteSourceEnvironment)}` : ""
// A secret seed which is the same across all Environments of this Lagoon Project
var projectSeedVal = projectSeedString || jwtSecretString
var projectSecret = crypto.createHash('sha256').update(`${projectName}-${projectSeedVal}`).digest('hex');
var alertContactHA = ""
var alertContactSA = ""
var uptimeRobotStatusPageIds = []
var alertContact = ""
if (alertContactHA != undefined && alertContactSA != undefined){
if (availability == "HIGH") {
alertContact = alertContactHA
} else {
alertContact = alertContactSA
}
} else {
alertContact = "unconfigured"
}
var uptimeRobotStatusPageId = uptimeRobotStatusPageIds.join('-')
var pullrequestData: any = {};
var promoteData: any = {};
var gitRef = gitSha ? gitSha : `origin/${branchName}`
switch (type) {
case "branch":
// if we have a sha given, we use that, if not we fall back to the branch (which needs be prefixed by `origin/`
var gitRef = gitSha ? gitSha : `origin/${branchName}`
var deployBaseRef = branchName
var deployHeadRef = null
var deployTitle = null
break;
case "pullrequest":
var gitRef = gitSha
var deployBaseRef = prBaseBranch
var deployHeadRef = prHeadBranch
var deployTitle = prPullrequestTitle
pullrequestData = {
pullrequest: {
headBranch: prHeadBranch,
headSha: prHeadSha,
baseBranch: prBaseBranch,
baseSha: prBaseSha,
title: prPullrequestTitle,
number: prPullrequestNumber,
},
};
break;
case "promote":
var gitRef = `origin/${promoteSourceEnvironment}`
var deployBaseRef = promoteSourceEnvironment
var deployHeadRef = null
var deployTitle = null
promoteData = {
promote: {
sourceEnvironment: promoteSourceEnvironment,
sourceProject: openshiftPromoteSourceProject,
}
};
break;
}
// Get the target information
// get the projectpattern and id from the target
// this is only used on the initial deployment
var openshiftProjectPattern = deployTarget.openshiftProjectPattern;
// check if this environment already exists in the API so we can get the openshift target it is using
// this is even valid for promotes if it isn't the first time time it is being deployed
try {
const apiEnvironment = await getEnvironmentByName(branchName, lagoonProjectData.id, false);
let envId = apiEnvironment.environmentByName.id
const environmentOpenshift = await getOpenShiftInfoForEnvironment(envId);
deployTarget.openshift = environmentOpenshift.environment.openshift
openshiftProjectPattern = environmentOpenshift.environment.openshiftProjectPattern
} catch (err) {
//do nothing
}
// end working out the target information
let openshiftId = deployTarget.openshift.id;
if (deployTarget.openshift.disabled) {
logger.error(`Couldn't deploy environment, the selected deploytarget '${deployTarget.openshift.name}' is disabled`)
throw new DeployTargetDisabled(`Couldn't deploy environment, the selected deploytarget '${deployTarget.openshift.name}' is disabled`)
}
var openshiftProject = openshiftProjectPattern ? openshiftProjectPattern.replace('${environment}',environmentName).replace('${project}', projectName) : `${projectName}-${environmentName}`
var deployTargetName = deployTarget.openshift.name
var monitoringConfig: any = {};
try {
monitoringConfig = JSON.parse(deployTarget.openshift.monitoringConfig) || "invalid"
} catch (e) {
logger.error('Error parsing openshift.monitoringConfig from openshift: %s, continuing with "invalid"', deployTarget.openshift.name, { error: e })
monitoringConfig = "invalid"
}
if (monitoringConfig != "invalid"){
alertContactHA = monitoringConfig.uptimerobot.alertContactHA || ""
alertContactSA = monitoringConfig.uptimerobot.alertContactSA || ""
if (monitoringConfig.uptimerobot.statusPageId) {
uptimeRobotStatusPageIds.push(monitoringConfig.uptimerobot.statusPageId)
}
}
let buildImage = ""
// if a default build image is defined by `DEFAULT_BUILD_DEPLOY_IMAGE` in api and webhooks2tasks, use it
if (defaultBuildDeployImage) {
buildImage = defaultBuildDeployImage
}
if (edgeBuildDeployImage) {
// if an edge build image is defined by `EDGE_BUILD_DEPLOY_IMAGE` in api and webhooks2tasks, use it
buildImage = edgeBuildDeployImage
}
// otherwise work out the build image from the deploytarget if defined
if (deployTarget.openshift.buildImage != null && deployTarget.openshift.buildImage != "") {
// set the build image here if one is defined in the api
buildImage = deployTarget.openshift.buildImage
}
// otherwise work out the build image from the project if defined
if (lagoonProjectData.buildImage != null && lagoonProjectData.buildImage != "") {
// set the build image here if one is defined in the api
buildImage = lagoonProjectData.buildImage
}
// if no build image is determined, the `remote-controller` defined default image will be used
// once it reaches the remote cluster.
var alertContact = ""
if (alertContactHA != undefined && alertContactSA != undefined){
if (availability == "HIGH") {
alertContact = alertContactHA
} else {
alertContact = alertContactSA
}
} else {
alertContact = "unconfigured"
}
var availability = lagoonProjectData.availability || "STANDARD"
// @TODO: openshiftProject here can't be generated on the cluster side (it should be) but the addOrUpdate mutation doesn't allow for openshiftProject to be optional
// maybe need to have this generate a random uid initially?
let environment;
try {
environment = await addOrUpdateEnvironment(branchName,
lagoonProjectData.id,
graphqlGitType,
deployBaseRef,
graphqlEnvironmentType,
openshiftProject,
openshiftId,
openshiftProjectPattern,
deployHeadRef,
deployTitle)
logger.info(`${openshiftProject}: Created/Updated Environment in API`)
} catch (err) {
logger.error(`Couldn't addOrUpdateEnvironment: ${err.message}`)
throw new Error
}
let deployment;
let environmentId;
try {
const now = moment.utc();
const apiEnvironment = await getEnvironmentByName(branchName, lagoonProjectData.id, false);
environmentId = apiEnvironment.environmentByName.id
deployment = await addDeployment(buildName,
"NEW",
now.format('YYYY-MM-DDTHH:mm:ss'),
apiEnvironment.environmentByName.id,
null, null, null, null,
buildPriority,
bulkId,
bulkName,
sourceUser,
sourceType,
);
} catch (error) {
logger.error(`Could not save deployment for project ${lagoonProjectData.id}. Message: ${error}`);
}
// encode some values so they get sent to the controllers nicely
const sshKeyBase64 = new Buffer(deployPrivateKey.replace(/\\n/g, "\n")).toString('base64')
const [routerPattern, envVars, projectVars] = await getEnvironmentsRouterPatternAndVariables(
lagoonProjectData,
environment.addOrUpdateEnvironment,
deployTarget.openshift,
bulkId, bulkName, buildPriority, buildVariables,
bulkType.Deploy
)
let organization = null;
if (lagoonProjectData.organization != null) {
const curOrg = await getOrganizationById(lagoonProjectData.organization);
organization = {
name: curOrg.name,
id: curOrg.id,
}
}
// this is what will be returned and sent to the controllers via message queue, it is the lagoonbuild controller spec
var buildDeployData: any = {
metadata: {
name: buildName,
namespace: "lagoon",
},
spec: {
build: {
type: type,
image: buildImage, // the controller will know which image to use
ci: CI,
priority: priority, // add the build priority
bulkId: bulkId, // add the bulk id if present
},
branch: {
name: branchName,
},
...pullrequestData,
...promoteData,
gitReference: gitRef,
project: {
id: lagoonProjectData.id,
name: projectName,
organization: organization,
gitUrl: gitUrl,
uiLink: deployment.addDeployment.uiLink,
environment: environmentName,
environmentType: environmentType,
environmentId: environmentId,
environmentIdling: environment.addOrUpdateEnvironment.autoIdle,
projectIdling: lagoonProjectData.autoIdle,
storageCalculator: lagoonProjectData.storageCalc,
productionEnvironment: projectProductionEnvironment,
standbyEnvironment: projectStandbyEnvironment,
subfolder: subfolder,
routerPattern: routerPattern, // @DEPRECATE: send this still for backwards compatability, but eventually this can be removed once LAGOON_SYSTEM_ROUTER_PATTERN is adopted wider
deployTarget: deployTargetName,
projectSecret: projectSecret,
key: sshKeyBase64,
monitoring: {
contact: alertContact,
statuspageID: uptimeRobotStatusPageId,
},
variables: {
project: projectVars,
environment: envVars,
},
},
}
};
return buildDeployData;
}
enum bulkType {
Task,
Deploy
}
export const getEnvironmentsRouterPatternAndVariables = async function name(
project: Pick<
Project,
'routerPattern' | 'sharedBaasBucket' | 'organization'
> & {
openshift: Pick<Kubernetes, 'routerPattern'>;
envVariables: Pick<EnvKeyValue, 'name' | 'value' | 'scope'>[];
},
environment: any,
deployTarget: Pick<Kubernetes, 'name' | 'routerPattern' | 'sharedBaasBucketName'>,
bulkId: string,
bulkName: string,
buildPriority: number,
buildVariables: any,
bulkTask: bulkType
): Promise<[string, string, string]> {
let projectVars: Array<Pick<EnvKeyValue, 'name' | 'value'> & {
scope: EnvVariableScope | InternalEnvVariableScope;
}> = [...project.envVariables];
// set routerpattern to the routerpattern of what is defined in the project scope openshift
var routerPattern = project.openshift.routerPattern
if (typeof deployTarget.routerPattern !== 'undefined') {
// if deploytargets are being provided, then use what is defined in the deploytarget
// null is a valid value for routerPatterns here...
routerPattern = deployTarget.routerPattern
}
// but if the project itself has a routerpattern defined, then this should be used
if (project.routerPattern) {
// if a project has a routerpattern defined, use it. `null` is not valid here
routerPattern = project.routerPattern
}
projectVars = [
...projectVars,
// append the routerpattern to the projects variables
// use a scope of `internal_system` which isn't available to the actual API to be added via mutations
// this way variables or new functionality can be passed into lagoon builds using the existing variables mechanism
// avoiding the needs to hardcode them into the spec to then be consumed by the build-deploy controller
{
name: 'LAGOON_SYSTEM_ROUTER_PATTERN',
value: routerPattern,
scope: InternalEnvVariableScope.INTERNAL_SYSTEM
},
// append the `LAGOON_SYSTEM_CORE_VERSION` variable as an `internal_system` variable that can be consumed by builds and
// is not user configurable, this value will eventually be consumed by `build-deploy-tool` to be able to reject
// builds that are not of a supported version of lagoon
{
name: "LAGOON_SYSTEM_CORE_VERSION",
value: lagoonVersion,
scope: InternalEnvVariableScope.INTERNAL_SYSTEM
}
];
// if the project is configured with a shared baas bucket
if (project.sharedBaasBucket) {
// we only want the shared baas bucket here if one is defined
let [sharedBaasBucket, shared] = await getBaasBucketName(project, deployTarget)
if (shared) {
projectVars = [
...projectVars,
{
name: "LAGOON_SYSTEM_PROJECT_SHARED_BUCKET",
value: sharedBaasBucket,
scope: InternalEnvVariableScope.INTERNAL_SYSTEM
}
];
}
}
if (project.organization) {
// check the environment quota, this prevents environments being deployed by the api or webhooks
const curOrg = await getOrganizationById(project.organization);
projectVars = [
...projectVars,
{
name: "LAGOON_ROUTE_QUOTA",
value: `${curOrg.quotaRoute}`,
scope: InternalEnvVariableScope.INTERNAL_SYSTEM
}
];
}
// handle any bulk deploy related injections here
let varPrefix = "LAGOON_BULK_DEPLOY"
switch (bulkTask) {
case bulkType.Task:
varPrefix = "LAGOON_BULK_TASK"
if (buildPriority != null) {
projectVars = [
...projectVars,
{
name: "LAGOON_TASK_PRIORITY",
value: buildPriority.toString(),
scope: EnvVariableScope.BUILD
}
];
}
break;
default:
if (buildPriority != null) {
projectVars = [
...projectVars,
{
name: "LAGOON_BUILD_PRIORITY",
value: buildPriority.toString(),
scope: EnvVariableScope.BUILD
}
];
}
break;
}
if (bulkId != "" && bulkId != null) {
// if this is a bulk deploy, add the associated bulk deploy build scope variables
projectVars = [
...projectVars,
{
name: varPrefix,
value: "true",
scope: EnvVariableScope.BUILD
},
{
name: `${varPrefix}_ID`,
value: bulkId,
scope: EnvVariableScope.BUILD
}
];
}
if (bulkName != "" && bulkName != null) {
projectVars = [
...projectVars,
{
name: `${varPrefix}_NAME`,
value: bulkName,
scope: EnvVariableScope.BUILD
}
];
}
// end bulk related injections
let lagoonEnvironmentVariables = environment.envVariables || []
if (buildVariables != null ) {
// add the build `scope` to all the incoming build variables for a specific build
const scopedBuildVariables = buildVariables.map(v => ({...v, scope: EnvVariableScope.BUILD}))
// check for buildvariables being passed in
// these need to be merged on top of environment level variables
// handle that here
lagoonEnvironmentVariables = jsonMerge(environment.envVariables, scopedBuildVariables, "name")
}
// encode some values so they get sent to the controllers nicely
const envVarsEncoded = new Buffer(JSON.stringify(lagoonEnvironmentVariables)).toString('base64')
const projectVarsEncoded = new Buffer(JSON.stringify(projectVars)).toString('base64')
return [routerPattern, envVarsEncoded, projectVarsEncoded]
}
/*
This `createDeployTask` is the primary entrypoint after the
API resolvers to handling a deployment creation
and the associated environment creation.
*/
export const createDeployTask = async function(deployData: any) {
const {
projectName,
branchName,
// sha,
type,
pullrequestTitle
} = deployData;
const result = await getOpenShiftInfoForProject(projectName);
const project = result.project;
const environments = await getEnvironmentsForProject(projectName);
if (project.organization) {
// if this would be a new environment, check it against the environment quota
if (!environments.project.environments.map(e => e.name).find(i => i === branchName)) {
// check the environment quota, this prevents environments being deployed by the api or webhooks
const curOrg = await getOrganizationByIdWithEnvs(project.organization);
if (curOrg.environments.length >= curOrg.quotaEnvironment && curOrg.quotaEnvironment != -1) {
throw new OrganizationEnvironmentLimit(
`'${branchName}' would exceed organization environment quota: ${curOrg.environments.length}/${curOrg.quotaEnvironment}`
);
}
}
}
// environments =
// { project:
// { environment_deployments_limit: 1,
// production_environment: 'master',
// environments: [ { name: 'develop', environment_type: 'development' }, [Object] ] } }
// we want to limit production environments, without making it configurable currently
var productionEnvironmentsLimit = 2;
// we want to make sure we can deploy the `production` env, and also the env defined as standby
if (
environments.project.productionEnvironment === branchName ||
environments.project.standbyProductionEnvironment === branchName
) {
// get a list of production environments
const prod_environments = environments.project.environments
.filter(e => e.environmentType === 'production')
.map(e => e.name);
logger.debug(
`projectName: ${projectName}, branchName: ${branchName}, existing environments are ${prod_environments}`
);
if (prod_environments.length >= productionEnvironmentsLimit) {
if (prod_environments.find(i => i === branchName)) {
logger.debug(
`projectName: ${projectName}, branchName: ${branchName}, environment already exists, no environment limits considered`
);
} else {
throw new EnvironmentLimit(
`'${branchName}' would exceed the configured limit of ${productionEnvironmentsLimit} production environments for project ${projectName}`
);
}
}
} else {
// get a list of non-production environments
const dev_environments = environments.project.environments
.filter(e => e.environmentType === 'development')
.map(e => e.name);
logger.debug(
`projectName: ${projectName}, branchName: ${branchName}, existing environments are ${dev_environments}`
);
if (
environments.project.developmentEnvironmentsLimit !== null &&
dev_environments.length >=
environments.project.developmentEnvironmentsLimit
) {
if (dev_environments.find(i => i === branchName)) {
logger.debug(
`projectName: ${projectName}, branchName: ${branchName}, environment already exists, no environment limits considered`
);
} else {
throw new EnvironmentLimit(
`'${branchName}' would exceed the configured limit of ${environments.project.developmentEnvironmentsLimit} development environments for project ${projectName}`
);
}
}
}
if (type === 'branch') {
// use deployTargetBranches function to handle
let lagoonData = {
projectId: environments.project.id,
projectName,
branchName,
project,
deployData
}
try {
let result = deployTargetBranches(lagoonData)
return result
} catch (error) {
throw error
}
} else if (type === 'pullrequest') {
// use deployTargetPullrequest function to handle
let lagoonData = {
projectId: environments.project.id,
projectName,
branchName,
project,
pullrequestTitle,
deployData
}
try {
let result = deployTargetPullrequest(lagoonData)
return result
} catch (error) {
throw error
}
}
}
export const createPromoteTask = async function(promoteData: any) {
const {
projectName
// branchName,
// promoteSourceEnvironment,
// type,
} = promoteData;
const result = await getOpenShiftInfoForProject(projectName);
const project = result.project;
// use deployTargetPromote function to handle
let lagoonData = {
projectId: project.id,
promoteData
}
return deployTargetPromote(lagoonData)
}
export const createRemoveTask = async function(removeData: any) {
const {
projectName,
branch,
branchName,
pullrequestNumber,
pullrequestTitle,
forceDeleteProductionEnvironment,
type
} = removeData;
// Load all environments that currently exist (and are not deleted).
const allEnvironments = await getEnvironmentsForProject(projectName);
// Check to see if we are deleting a production environment, and if so,
// ensure the flag is set to allow this.
if (
branch === allEnvironments.project.productionEnvironment ||
(allEnvironments.project.standbyProductionEnvironment &&
branch === allEnvironments.project.standbyProductionEnvironment)
) {
if (forceDeleteProductionEnvironment !== true) {
throw new CannotDeleteProductionEnvironment(
`'${branch}' is defined as the production environment for ${projectName}, refusing to remove.`
);
}
}
if (type === 'branch') {