-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathtasks.ts
More file actions
1557 lines (1419 loc) · 52.3 KB
/
tasks.ts
File metadata and controls
1557 lines (1419 loc) · 52.3 KB
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,
AutogeneratedRouteConfig,
} from './api';
import {
deployTargetBranches,
deployTargetPullrequest,
deployTargetPromote
} from './deploy-tasks';
import { InternalEnvVariableScope, DeployData, DeployType, RemoveData, RouteSource } from './types';
// @ts-ignore
import sha1 from 'sha1';
import crypto from 'crypto';
import moment from 'moment';
import { encodeJSONBase64, encodeBase64, toNumber, jsonMerge } from './util/func';
import { getConfigFromEnv } from './util/config';
import { hasEnvVar, getEnvVarValue } from './util/lagoon';
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;
};
export let connection: AmqpConnectionManager;
const rabbitmqHost = getConfigFromEnv('RABBITMQ_HOST', 'broker');
const rabbitmqUsername = getConfigFromEnv('RABBITMQ_USERNAME', 'guest');
const rabbitmqPassword = getConfigFromEnv('RABBITMQ_PASSWORD', 'guest');
const taskPrefetch = toNumber(getConfigFromEnv('TASK_PREFETCH_COUNT', '2'));
const taskMonitorPrefetch = toNumber(getConfigFromEnv('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 = getConfigFromEnv('CI', 'false');
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 = getConfigFromEnv('JWTSECRET', 'super-secret-string');
const projectSeedString = getConfigFromEnv('PROJECTSEED', 'super-secret-string');
class NoNeedToRemoveBranch extends Error {
constructor(message?: string) {
super(message);
this.name = 'NoNeedToRemoveBranch';
}
}
class DeployTargetDisabled extends Error {
constructor(message?: string) {
super(message);
this.name = 'DeployTargetDisabled';
}
}
class CannotDeleteProductionEnvironment extends Error {
constructor(message?: string) {
super(message);
this.name = 'CannotDeleteProductionEnvironment';
}
}
class EnvironmentLimit extends Error {
constructor(message?: string) {
super(message);
this.name = 'EnvironmentLimit';
}
}
class OrganizationEnvironmentLimit extends Error {
constructor(message?: string) {
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): string =>
string.toLocaleLowerCase().replace(/[^0-9a-z-]/g,'-')
// function to truncate the environment name as required to fit within kubernetes namespace limits
export const truncateEnvironmentName = (projectName: string, environmentName: string): string => {
var envName = makeSafe(environmentName)
var overlength = 58 - projectName.length;
if ( envName.length > overlength ) {
var hash = sha1(envName).substring(0,4)
envName = envName.substring(0, overlength-5)
envName = envName.concat('-' + hash)
}
return envName;
}
// function to seed the initial namespace for use in
export const seedNamespace = (projectName: string, environmentName: string): string => {
var envName = truncateEnvironmentName(projectName, environmentName)
return makeSafe(`${projectName}-${envName}`)
}
// @TODO: make sure if it fails, it does so properly
export const getControllerBuildData = async function(deployTarget: any, deployData: DeployData) {
const {
projectName,
branchName,
sha,
type,
pullrequestTitle,
headBranchName: headBranch,
headSha,
baseBranchName: baseBranch,
baseSha,
promoteSourceEnvironment,
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,
sourceType,
buildType,
} = deployData;
const buildVariables = deployData.buildVariables || [];
const sourceUser = deployData.sourceUser || 'unknown';
var environmentName = truncateEnvironmentName(projectName, branchName)
const result = await getOpenShiftInfoForProject(projectName);
const lagoonProjectData = result.project
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 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 sourceProjectNamespace = 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: string | undefined, alertContactSA: string | undefined;
var uptimeRobotStatusPageIds: any[] = []
var pullrequestData: any = {};
var promoteData: any = {};
let gitRef: string = gitSha ? gitSha : `origin/${branchName}`
let deployHeadRef: string | null = null;
let deployBaseRef: string;
let deployTitle: string | null = null;
switch (type) {
case DeployType.BRANCH:
deployBaseRef = branchName
break;
case DeployType.PULLREQUEST:
gitRef = gitSha
deployBaseRef = prBaseBranch
deployHeadRef = prHeadBranch
deployTitle = prPullrequestTitle
pullrequestData = {
pullrequest: {
headBranch: prHeadBranch,
headSha: prHeadSha,
baseBranch: prBaseBranch,
baseSha: prBaseSha,
title: prPullrequestTitle,
number: prPullrequestNumber,
},
};
break;
case DeployType.PROMOTE:
gitRef = `origin/${promoteSourceEnvironment}`
// @ts-ignore DeployData is a catch-all, when type is promote
// promoteSourceEnvironment is a string.
deployBaseRef = promoteSourceEnvironment
promoteData = {
promote: {
sourceEnvironment: promoteSourceEnvironment,
sourceProject: sourceProjectNamespace,
}
};
break;
}
// Get the target information
// 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
} catch (err) {
//do nothing
}
// end working out the target information
let deploytargetId = 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 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 || undefined
alertContactSA = monitoringConfig.uptimerobot.alertContactSA || undefined
if (monitoringConfig.uptimerobot.statusPageId) {
uptimeRobotStatusPageIds.push(monitoringConfig.uptimerobot.statusPageId)
}
}
var availability = lagoonProjectData.availability || "STANDARD"
var alertContact = ""
if (alertContactHA != undefined && alertContactSA != undefined){
if (availability == "HIGH") {
alertContact = alertContactHA
} else {
alertContact = alertContactSA
}
} else {
alertContact = "unconfigured"
}
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.
// maybe need to have this generate a random uid initially?
let environment;
try {
environment = await addOrUpdateEnvironment(branchName,
lagoonProjectData.id,
type,
deployBaseRef,
graphqlEnvironmentType,
deploytargetId,
deployHeadRef,
deployTitle)
logger.info(`${makeSafe(`${projectName}-${environmentName}`)}: Created/Updated Environment in API`)
} catch (err) {
logger.error(`Couldn't addOrUpdateEnvironment: ${err.message}`)
throw new Error
}
let deployment;
const now = moment.utc();
const apiEnvironment = await getEnvironmentByName(branchName, lagoonProjectData.id, false);
const environmentId = apiEnvironment.environmentByName.id
try {
deployment = await addDeployment(buildName,
"NEW",
now.format('YYYY-MM-DDTHH:mm:ss'),
apiEnvironment.environmentByName.id,
null, null, null, null,
priority,
bulkId,
bulkName,
sourceUser,
sourceType,
buildType,
);
} 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 { routerPattern, appliedEnvVars: envVars } = await getEnvironmentsRouterPatternAndVariables(
lagoonProjectData,
apiEnvironment.environmentByName,
deployTarget.openshift,
bulkId || null, bulkName || null, priority, buildVariables,
bulkType.Deploy,
)
let organization: any = 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: encodeBase64(lagoonProjectData.privateKey.replace(/\\n/g, "\n")),
monitoring: {
contact: alertContact,
statuspageID: uptimeRobotStatusPageIds.join('-'),
},
variables: {
environment: envVars,
},
},
}
};
return buildDeployData;
}
enum bulkType {
Task,
Deploy
}
export const getEnvironmentsRouterPatternAndVariables = async function(
project: Pick<
Project,
'routerPattern' |
'sharedBaasBucket' |
'organization' |
'apiRoutes' |
'autogeneratedRouteConfig'
> & {
openshift: Pick<Kubernetes, 'routerPattern'>;
envVariables: Pick<EnvKeyValue, 'name' | 'value' | 'scope'>[];
},
environment: {
envVariables: Pick<EnvKeyValue, 'name' | 'value' | 'scope'>[]
apiRoutes,
autogeneratedRouteConfig,
},
deployTarget: Pick<Kubernetes, 'name' | 'routerPattern' | 'sharedBaasBucketName'>,
bulkId: string | null,
bulkName: string | null,
buildPriority: number,
buildVariables: Array<{name: string, value: string}>,
bulkTask: bulkType,
): Promise<{ routerPattern: string, appliedEnvVars: string }> {
type EnvKeyValueInternal = Pick<EnvKeyValue, 'name' | 'value'> & {
scope: EnvVariableScope | InternalEnvVariableScope;
}
/*
prepares the values to send to builds and tasks for consumption
this ensures the data is structured to match the one that the build expects when it receives the payload
this gets based64 encoded before being shipped. it is decoded during the build
*/
let apiRoutes = environment.apiRoutes
if (apiRoutes.length > 0) {
for (let i = 0; i < apiRoutes.length; i++) {
// remove any yaml/autogenerated sourced apiRoutes from the list
// these don't get send to builds from the api as they are configured by lagoon.yml
// or are created by the autogenerated route configuration
if ([RouteSource.YAML, RouteSource.AUTOGENERATED].includes(apiRoutes[i].source.toLowerCase())) {
// the environment queries have (source: API) on the environments apiRoutes request
// this check is just a fallback check
apiRoutes.splice(i, 1);
i--;
continue;
}
// the structure of annotations in the build-deploy-tool are `map[string]string`
// this converts the `key:value` type from the api to `map[string]string` for the build-deploy-tool to consume
let annotations = apiRoutes[i].annotations.reduce((acc, item) => {
acc[item.key] = item.value;
return acc;
}, {});
apiRoutes[i].annotations = annotations
// the structure of alternativeNames in the build-deploy-tool are `[]string`
// this converts to that type for the build-deploy-tool to consume
let alternativeNames = apiRoutes[i].alternativeNames.map(item => item.domain);
apiRoutes[i].alternativeNames = alternativeNames
}
}
/*
this handles creating the autogenerated route configuration if any autogenerated route settings
on the project or environment are set, this then gets setup in the required format
and base64 encoded before being sent to the build, it is decoded there
*/
let agPayload = {}
if (project.autogeneratedRouteConfig !== null) {
agPayload = project.autogeneratedRouteConfig
}
if (environment.autogeneratedRouteConfig !== null) {
agPayload = environment.autogeneratedRouteConfig
}
// Single list of env vars that apply to an environment. Env vars from multiple
// sources (organization, project, enviornment, build vars, etc) are
// consolidated based on precedence.
let appliedEnvVars: EnvKeyValueInternal[] = [];
// Appends newVar to appliedEnvVars only if newVar is unique by name.
const applyIfNotExists = (newVar: EnvKeyValueInternal): void => {
const index = appliedEnvVars.findIndex((searchVar) => searchVar.name === newVar.name)
if (index === -1) {
appliedEnvVars.push(newVar)
}
}
// Get the router pattern from the project or deploy target.
let routerPattern = project.openshift.routerPattern
// deployTarget.routerPattern allows null.
if (typeof deployTarget.routerPattern !== 'undefined') {
routerPattern = deployTarget.routerPattern
}
// project.routerPattern does now allow null.
if (project.routerPattern) {
routerPattern = project.routerPattern
}
// Load organization if project is in one.
let org;
if (project.organization) {
org = await getOrganizationById(project.organization);
}
/*
* Internal scoped env vars.
*
* Uses the env vars system to send data to lagoon-remote but should not be
* overrideable by Lagoon API env vars.
*/
applyIfNotExists({
name: "LAGOON_SYSTEM_CORE_VERSION",
value: getConfigFromEnv('LAGOON_VERSION', 'unknown'),
scope: InternalEnvVariableScope.INTERNAL_SYSTEM
});
applyIfNotExists({
name: 'LAGOON_SYSTEM_ROUTER_PATTERN',
value: routerPattern,
scope: InternalEnvVariableScope.INTERNAL_SYSTEM
});
const [bucketName, isSharedBucket] = await getBaasBucketName(project, deployTarget)
if (isSharedBucket) {
applyIfNotExists({
name: "LAGOON_SYSTEM_PROJECT_SHARED_BUCKET",
value: bucketName,
scope: InternalEnvVariableScope.INTERNAL_SYSTEM
});
}
if (org) {
applyIfNotExists({
name: "LAGOON_ROUTE_QUOTA",
value: `${org.quotaRoute}`,
scope: InternalEnvVariableScope.INTERNAL_SYSTEM
});
}
// `LAGOON_API_ROUTES` is the successor to LAGOON_ROUTES_JSON. the build-deploy-tool will
// check if `LAGOON_ROUTES_JSON` is defined, then that will be used to prevent breaking deployments
// but will produce a build warning indicating that LAGOON_ROUTES_JSON will be deprecated in the future
// and to use API defined routes instead
if (apiRoutes.length > 0) {
applyIfNotExists({
name: "LAGOON_API_ROUTES",
value: encodeJSONBase64({routes: apiRoutes}),
scope: InternalEnvVariableScope.INTERNAL_SYSTEM
});
}
if (project.apiRoutes.length > 0) {
// if the project has any apiroutes defined, then we enforce cleanup of removed routes on any environments
applyIfNotExists({
name: "LAGOON_API_ROUTES_CLEANUP",
value: "true",
scope: InternalEnvVariableScope.INTERNAL_SYSTEM
});
}
if (Object.keys(agPayload).length) {
// if there is any autogenerated route configuration to send
// set that here
// @TODO: need to figure out a better way to handle the default autogenerate insecure handling
// agPayload.autogenerate.insecure = "Redirect"
applyIfNotExists({
name: "LAGOON_API_AUTOGENERATED_CONFIG",
value: encodeJSONBase64(agPayload),
scope: InternalEnvVariableScope.INTERNAL_SYSTEM
});
}
/*
* Normally scoped env vars.
*
* Env vars that are set by users, or derived from them.
*/
// Build env vars passed to the API.
for (const buildVar of buildVariables) {
applyIfNotExists({
name: buildVar.name,
value: buildVar.value,
scope: EnvVariableScope.BUILD
})
}
// Bulk deployment env vars.
if (bulkTask === bulkType.Deploy) {
applyIfNotExists({
name: "LAGOON_BUILD_PRIORITY",
value: buildPriority.toString(),
scope: EnvVariableScope.BUILD
});
if (bulkId) {
applyIfNotExists({
name: "LAGOON_BULK_DEPLOY",
value: "true",
scope: EnvVariableScope.BUILD
});
applyIfNotExists({
name: "LAGOON_BULK_DEPLOY_ID",
value: bulkId,
scope: EnvVariableScope.BUILD
});
if (bulkName) {
applyIfNotExists({
name: "LAGOON_BULK_DEPLOY_NAME",
value: bulkName,
scope: EnvVariableScope.BUILD
});
}
}
} else if (bulkTask === bulkType.Task) {
applyIfNotExists({
name: "LAGOON_TASK_PRIORITY",
value: buildPriority.toString(),
scope: EnvVariableScope.BUILD
})
if (bulkId) {
applyIfNotExists({
name: "LAGOON_BULK_TASK",
value: "true",
scope: EnvVariableScope.BUILD
});
applyIfNotExists({
name: "LAGOON_BULK_TASK_ID",
value: bulkId,
scope: EnvVariableScope.BUILD
});
if (bulkName) {
applyIfNotExists({
name: "LAGOON_BULK_TASK_NAME",
value: bulkName,
scope: EnvVariableScope.BUILD
});
}
}
}
// Environment env vars.
for (const envVar of environment.envVariables) {
applyIfNotExists(envVar)
}
// Project env vars.
for (const projVar of project.envVariables) {
applyIfNotExists(projVar)
}
if (org) {
// Organization env vars.
for (const orgVar of org.envVariables) {
applyIfNotExists(orgVar)
}
}
return { routerPattern, appliedEnvVars: encodeJSONBase64(appliedEnvVars) }
}
/*
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: DeployData) {
const {
projectName,
branchName,
type
} = 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 === DeployType.BRANCH) {
try {
let result = deployTargetBranches(environments.project.id, deployData)
return result
} catch (error) {
throw error
}
} else if (type === DeployType.PULLREQUEST) {
try {
let result = deployTargetPullrequest(environments.project.id, deployData)
return result
} catch (error) {
throw error
}
}
}
export const createPromoteTask = async function(promoteData: DeployData) {
const result = await getOpenShiftInfoForProject(promoteData.projectName);
const project = result.project;
return deployTargetPromote(project.id, promoteData)