-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.ts
1111 lines (1068 loc) · 46.9 KB
/
index.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 { Tables } from 'fortigate-autoscale-core/db-definitions';
import { Firestore, FieldValue } from '@google-cloud/firestore';
import * as AutoScaleCore from 'fortigate-autoscale-core';
import Compute from '@google-cloud/compute';
import { Storage } from '@google-cloud/storage';
import { CloudPlatform, LicenseRecord } from 'fortigate-autoscale-core';
import { AutoscaleHandler } from 'fortigate-autoscale-core/autoscale-handler';
import * as Platform from 'fortigate-autoscale-core/cloud-platform';
import { URL } from 'url';
import { GoogleAuth } from 'google-auth-library';
import { sleep } from 'fortigate-autoscale-core/core-functions';
const {
FIRESTORE_DATABASE,
ASSET_STORAGE_NAME,
FORTIGATE_PSK_SECRET,
TRIGGER_URL,
PROJECT_ID,
SCRIPT_TIMEOUT,
REGION,
ELASTIC_IP_NAME //TODO: can move to DB item once core is updated.
} = process.env,
SCRIPT_EXECUTION_TIME_CHECKPOINT = Date.now(),
ELASTIC_IP_NIC = 'nic0', // GCP will only use nic0 at the moment. May change in the future.
ATTACH_EIP_TIME_LIMIT = 45000;
namespace GCPPlatform {
export interface Filter {
Name: string;
Value: string;
}
export interface NetworkInterface {
NetworkInterfaceId: string;
}
// tslint:disable-next-line: no-empty-interface
export interface CreateNetworkInterfaceRequest {}
export interface Vpc {
VpcId: string;
}
export interface Subnet {
VpcId: string;
SubnetId: string;
}
export interface Instance {
instanceId: string;
PrivateIpAddress: string;
PublicIpAddress: string;
SubnetId: string;
VpcId: string;
zone?: string;
}
export interface DeleteRequest {
data: Data;
}
export interface Data {
id: string;
name: string;
zone: string;
operationType?: string;
targetLink?: string;
targetId?: string;
status?: string;
user?: string;
progress?: number;
insertTime?: string;
startTime?: string;
selfLink: string;
kind?: string;
}
}
interface GCPVirtualMachineDescriptor extends AutoScaleCore.VirtualMachineLike, GCPPlatform.Instance {
InstanceId: string;
PrivateIpAddress: string;
PublicIpAddress: string;
SubnetId: string;
VpcId: string;
zone?: string;
}
export interface GCPNetworkInterface extends AutoScaleCore.NetworkInterfaceLike, GCPPlatform.NetworkInterface {}
class GCPVirtualMachine extends AutoScaleCore.VirtualMachine<GCPVirtualMachineDescriptor, GCPNetworkInterface> {
constructor(o: GCPVirtualMachineDescriptor) {
super(o.InstanceId, o.scalingGroupName || null, 'gcp', o as GCPVirtualMachineDescriptor);
}
get primaryPrivateIpAddress() {
return this.sourceData.PrivateIpAddress;
}
get primaryPublicIpAddress() {
return this.sourceData.PublicIpAddress;
}
get subnetId() {
return this.sourceData.SubnetId;
}
get virtualNetworkId() {
return this.sourceData.VpcId;
}
}
export class GCPRuntimeAgent extends AutoScaleCore.RuntimeAgent<GCPPlatformRequest, GCPPlatformContext, Console> {
public body: any;
public instance: any;
public headers: GCPRuntimeAgent;
public respond(response: AutoScaleCore.ErrorDataPairLike): Promise<any> {
throw new Error('Method not implemented.');
}
public async processResponse(response): Promise<string> {
return 'processed response string as return';
}
}
// tslint:disable-next-line: no-empty-interface
export interface GCPPlatformRequest extends AutoScaleCore.HttpRequest {}
export interface GCPPlatformContext {}
export interface GCPNameValuesPair extends GCPPlatform.Filter {}
export interface HttpRequest extends Platform.HttpRequestLike {
httpMethod(): Platform.HttpMethodType;
}
interface GCPBlobStorageItemDescriptor extends AutoScaleCore.BlobStorageItemDescriptor {
storageName: string;
keyPrefix: string;
fileName?: string;
}
export class GCP extends CloudPlatform<
GCPPlatformRequest,
GCPPlatformContext,
Console,
GCPNameValuesPair,
GCPVirtualMachineDescriptor,
GCPVirtualMachine,
GCPRuntimeAgent
> {
public logger = new AutoScaleCore.Functions.DefaultLogger(console);
public compute = new Compute();
public blobStorage = new Storage({
projectId: PROJECT_ID
});
private fireStoreClient = new Firestore();
public respond(response: AutoScaleCore.ErrorDataPairLike, httpStatusCode?: number): Promise<void> {
throw new Error('Method not implemented.');
}
public describeScalingGroup(
decriptor: AutoScaleCore.ScalingGroupDecriptor
): Promise<AutoScaleCore.ScalingGroupLike> {
throw new Error('Method not implemented.');
}
public getTgwVpnAttachmentRecord(_selfInstance: GCPVirtualMachine) {
throw new Error('Method not implemented.');
}
public async getSettingItems(keyFilter?: string[], valueOnly?: boolean) {
let item;
let settingItem: AutoScaleCore.SettingItem;
const fireStoreDocument = this.fireStoreClient.doc(`${FIRESTORE_DATABASE}/SETTINGS`);
try {
const getDoc: any = await fireStoreDocument.get();
const formattedItems: AutoScaleCore.SettingItems = {};
const filteredItems: AutoScaleCore.SettingItems = {};
if (getDoc && getDoc._fieldsProto) {
console.log('Getting Setting Items.');
// tslint:disable-next-line: forin
for (item in getDoc._fieldsProto) {
// An empty String in FireStore counts as undefined
if (!item.mapValue) {
settingItem = new AutoScaleCore.SettingItem(
item,
getDoc._fieldsProto[item].mapValue.fields.settingValue.stringValue,
getDoc._fieldsProto[item].mapValue.fields.editable.booleanValue,
getDoc._fieldsProto[item].mapValue.fields.jsonEncoded.booleanValue,
getDoc._fieldsProto[item].mapValue.fields.description.stringValue
);
formattedItems[item] = settingItem;
filteredItems[item] = settingItem;
} else {
settingItem = new AutoScaleCore.SettingItem(
item,
getDoc._fieldsProto[item].mapValue.fields.settingValue.stringValue,
getDoc._fieldsProto[item].mapValue.fields.editable.booleanValue,
getDoc._fieldsProto[item].mapValue.fields.jsonEncoded.booleanValue,
getDoc._fieldsProto[item].mapValue.fields.description.stringValue
);
formattedItems[item] = settingItem;
filteredItems[item] = settingItem;
}
}
this.__settings = formattedItems;
this._initialized = true;
return (keyFilter && filteredItems) || formattedItems;
}
} catch (err) {
console.log('Error Getting Setting Items', err);
throw err;
}
throw console.error('Could Not Retreive Setting items. From Firestore');
}
public getLicenseFileContent(descriptor: AutoScaleCore.BlobStorageItemDescriptor): Promise<string> {
throw new Error('Method not implemented.');
}
// No DB initilization needed. Return true,
// DB settings handled in the autoscale handler init
public async init(): Promise<boolean> {
return true;
}
public async getAllAutoScaleInstanceIds() {
console.log('Called AutoScaler');
const getAutoscaler = await this.compute.getAutoscalers();
return getAutoscaler;
}
// Get config file from Storage and return as object
public async getBlobFromStorage(parameters: GCPBlobStorageItemDescriptor) {
console.log('Getting Config From Blob Storage');
const files = await this.blobStorage.bucket(parameters.storageName);
const file = files.file(parameters.fileName);
const fileData = { content: (await file.download()).toString() };
return fileData;
}
public async putMasterRecord(
candidateInstance: GCPVirtualMachine,
voteState: AutoScaleCore.MasterElection.VoteState,
method: AutoScaleCore.MasterElection.VoteMethod
): Promise<boolean> {
console.log('Updating Master Record Database', candidateInstance);
const datetoInt = Date.now();
const masterUpdateClient = this.fireStoreClient;
const document = masterUpdateClient.doc(`${FIRESTORE_DATABASE}/FORTIGATEMASTERELECTION`);
const fieldName = 'masterRecord';
try {
await document.update({
[fieldName]: {
MasterIP: candidateInstance.primaryPrivateIpAddress,
InstanceId: candidateInstance.instanceId,
VpcId: candidateInstance.virtualNetworkId,
SubnetId: 'null',
voteEndTime: datetoInt + 90 * 1000, // TODO:script timeout
VoteState: voteState
}
});
return true;
} catch (err) {
console.log(`Error in updating master record. ${err}`);
}
return false;
}
public async getMasterRecord(): Promise<AutoScaleCore.MasterElection.MasterRecord> {
console.log('getting Master record');
// First assign the doc to the table name or path. Then Call get to retrieve data.
const fireStoreDocument = this.fireStoreClient.doc(`${FIRESTORE_DATABASE}/FORTIGATEMASTERELECTION`);
let getDoc;
try {
getDoc = await fireStoreDocument.get();
} catch (err) {
console.log(`Error in getting master record ${err}`);
}
if (
getDoc &&
getDoc._fieldsProto &&
getDoc._fieldsProto.masterRecord &&
getDoc._fieldsProto.masterRecord.mapValue.fields &&
getDoc._fieldsProto.masterRecord.mapValue.fields.MasterIP &&
getDoc._fieldsProto.masterRecord.mapValue.fields.InstanceId
) {
const docData = {
ip: getDoc._fieldsProto.masterRecord.mapValue.fields.MasterIP.stringValue,
instanceId: getDoc._fieldsProto.masterRecord.mapValue.fields.InstanceId.stringValue,
scalingGroupName: null,
subnetId: getDoc._fieldsProto.masterRecord.mapValue.fields.SubnetId.stringValue,
voteEndTime: getDoc._fieldsProto.masterRecord.mapValue.fields.voteEndTime.integerValue,
voteState: getDoc._fieldsProto.masterRecord.mapValue.fields.VoteState.stringValue,
vpcId: getDoc._fieldsProto.masterRecord.mapValue.fields.VpcId.stringValue
};
console.log(`Master Record + ${docData}`);
return docData;
} else {
console.log('No Master record found in DB returning Null');
return null;
}
}
public async removeMasterRecord(): Promise<void> {
const fireStoreDocument = this.fireStoreClient.doc(`${FIRESTORE_DATABASE}/FORTIGATEMASTERELECTION`);
try {
await fireStoreDocument.update({
masterRecord: FieldValue.delete()
});
console.log('Removing master Record');
} catch (err) {
console.log('Error in removing Master Record', err);
}
}
public async getInstanceHealthCheck(
descriptor: AutoScaleCore.VirtualMachineDescriptor,
heartBeatInterval?: number
): Promise<AutoScaleCore.HealthCheck> {
if (descriptor && descriptor.instanceId) {
console.log('getting Record from AutoScale Table');
var recordId = descriptor.instanceId;
} else {
console.log('No Instance ID provided to getInstanceHealthCheck. Returning Null');
return null;
}
const fireStoreDocument = this.fireStoreClient.doc(`${FIRESTORE_DATABASE}/FORTIGATEAUTOSCALE`);
let getDoc;
try {
getDoc = await fireStoreDocument.get();
} catch (err) {
console.log(`Error in getInstanceHealthCheck. Could not retrieve instance record ${err}`);
throw err;
}
if (
getDoc &&
getDoc._fieldsProto &&
getDoc._fieldsProto[recordId] &&
getDoc._fieldsProto[recordId].mapValue.fields
) {
var docData: AutoScaleCore.HealthCheck = {
instanceId: recordId,
inSync: getDoc._fieldsProto[recordId].mapValue.fields.inSync.booleanValue,
healthy: getDoc._fieldsProto[recordId].mapValue.fields.healthy.booleanValue,
masterIp: getDoc._fieldsProto[recordId].mapValue.fields.masterIp.stringValue,
// In the case that HeartBeatLoss is not yet defined return 0. Only occurs on first set up.
heartBeatLossCount: getDoc._fieldsProto[recordId].mapValue.fields.heartBeatLossCount.integerValue || 0,
heartBeatInterval: getDoc._fieldsProto[recordId].mapValue.fields.heartBeatInterval.integerValue || 25,
nextHeartBeatTime: getDoc._fieldsProto[recordId].mapValue.fields.nextHeartBeatTime.integerValue,
ip: getDoc._fieldsProto[recordId].mapValue.fields.ip.stringValue,
syncState: getDoc._fieldsProto[recordId].mapValue.fields.syncState.stringValue
};
}
return docData;
}
public async updateInstanceHealthCheck(
healthCheck: AutoScaleCore.HealthCheck,
heartBeatInterval: number,
masterIp: string,
checkPointTime: number,
forceOutOfSync?: boolean
): Promise<boolean> {
const datetoInt = checkPointTime || Date.now();
const autoScaleRecordUpdate = this.fireStoreClient;
const document = autoScaleRecordUpdate.doc(`${FIRESTORE_DATABASE}/FORTIGATEAUTOSCALE`);
const fieldName = healthCheck.instanceId;
var instanceRecord: AutoScaleCore.HealthCheck = {
instanceId: healthCheck.instanceId,
ip: healthCheck.ip,
inSync: healthCheck.inSync,
heartBeatLossCount: healthCheck.heartBeatLossCount || 0,
heartBeatInterval,
masterIp,
syncState: healthCheck.syncState,
nextHeartBeatTime: datetoInt,
healthy: healthCheck.healthy
};
try {
await document.update({
[fieldName]: instanceRecord
});
return true;
} catch (err) {
console.log(
`Error in updateInstanceHealthCheck. Could not updateAutoScale Record. for ${healthCheck.ip} Error: ${err}`
);
throw err;
}
}
public async deleteInstanceHealthCheck(instanceId: string): Promise<boolean> {
const fireStoreDocument = this.fireStoreClient.doc(`${FIRESTORE_DATABASE}/FORTIGATEAUTOSCALE`);
try {
await fireStoreDocument.update({
[instanceId]: FieldValue.delete()
});
} catch (err) {
console.log('Error in removing AutoScale Record', err);
return false;
}
console.log('Removed AutoScale Record');
return true;
}
//
public async attachEIPtoMaster(instanceId, instanceZone) {
// Won't break the cluster if there is no EIP but should report as an error.
if (!instanceId || !instanceZone) {
console.error(
`Error in Attaching EIP to primary instance: IntanceId and InstanceZone must be specified: instanceId: ${instanceId} instanceZone: ${instanceZone}`
);
}
console.log('Updating Master Instance External IP');
console.log(
`InstanceID data passed to the attachEIPtoMaster Function: ${instanceId} instanceZone: ${instanceZone}`
);
// Google's auth client should be able to determine whether you are running locally, or in a cloud function.
// We use it here since we need to use their api, not the Node library to change addressconfigs.
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform'
});
const client = await auth.getClient();
const getAddressURL = `https://compute.googleapis.com/compute/v1/projects/${PROJECT_ID}/regions/${REGION}/addresses/${ELASTIC_IP_NAME}`;
const deleteAddressConfigURL = `https://compute.googleapis.com/compute/v1/projects/${PROJECT_ID}/zones/${instanceZone}/instances/${instanceId}/deleteAccessConfig`;
const addAddressConfigURL = `https://compute.googleapis.com/compute/v1/projects/${PROJECT_ID}/zones/${instanceZone}/instances/${instanceId}/addAccessConfig/`;
const getAddressReq: any = await client.request({
method: 'GET',
url: getAddressURL
});
// First must delete the ephemeral address on a host.
// Then we can add the EIP(or static address in the case of GCP)
try {
const deleteReq: GCPPlatform.DeleteRequest = await client.request({
method: 'POST',
url: deleteAddressConfigURL,
params: {
networkInterface: ELASTIC_IP_NIC,
accessConfig: 'external-nat'
}
});
// Troubleshooting data:
console.log(`Delete EIP request ${JSON.stringify(deleteReq.data)}`);
// If the request has been queued check the VM for the current accessConfig
if (deleteReq.data.status !== 'SUCCEEDED') {
console.warn(`Delete has queued. Waiting for it to finish before adding Static IP`);
let running = true;
let startTime = Date.now();
const attachEIPTimeLimit = ATTACH_EIP_TIME_LIMIT; // Default 45 seconds max.
while (running === true && startTime + attachEIPTimeLimit > Date.now()) {
const getInstanceInfo = await this.getInstanceInfo(instanceId);
// Check if there is an access config
// If there isn't then we are done running and can continue
if (!getInstanceInfo.networkInterfaces[0].accessConfigs) {
running = false;
} else {
console.log(
`Waiting 2 seconds before Calling getInstanceInfo again. Time waited (Milliseconds) ${Date.now() -
startTime}`
);
// sleep for 2 seconds.
await sleep(2000);
}
}
}
} catch (err) {
console.error(`Error in delete request ${err}`);
}
// Add the EIP to the new primary.
try {
console.log('Attaching EIP to new Primary.');
const addAddressReq = await client.request({
method: 'POST',
url: addAddressConfigURL,
params: {
networkInterface: ELASTIC_IP_NIC
},
data: {
type: 'EXTERNAL',
name: ELASTIC_IP_NAME,
natIP: getAddressReq.data.address,
networkTier: getAddressReq.data.networkTier, // 'PREMIUM'
kind: getAddressReq.data.kind // 'compute#accessConfig'
}
});
let running = true;
let attachEIPTimeLimit = 45; // Default 45 seconds max.
console.log(addAddressReq.data);
let startTime = Date.now();
while (running === true && startTime + attachEIPTimeLimit > Date.now()) {
console.log('Looking for new EIP attachment');
const getInstanceInfo = await this.getInstanceInfo(instanceId);
// Check if there is an access config
// If there isn't then we are done running and can continue
if (getInstanceInfo.networkInterfaces[0].accessConfigs) {
running = false;
} else {
console.log(
`Waiting 2 seconds before Calling getInstanceInfo again. Time waited (Milliseconds) ${Date.now() -
startTime}`
);
// sleep for 2 seconds.
await sleep(2000);
}
}
} catch (err) {
console.error(`Error in attaching EIP ${err}`);
}
}
public async getInstanceInfo(instanceId) {
// Primary purpose here is to return the zone. Which is not included in the older core.
let compute = new Compute();
try {
console.log('Fetching VMs');
const [vms] = await compute.getVMs();
for (let vmData of vms) {
if (vmData.metadata.id === instanceId) {
console.log('VM data' + JSON.stringify(vmData.metadata));
return vmData.metadata;
}
}
} catch (err) {
console.error(`Error Fetching VM's from GCP. Error: ${err}`);
throw err;
}
}
public async finalizeMasterElection(): Promise<boolean> {
console.log('Finalizing Primary Election');
// this._masterRecord is undefined at this point and doesn't contain Zone property.
// As a temporary fix we must grab the instanceId that has been set in firestore then
// lookup the data and retrieve the instaceId/zone etc.
// TODO: update when changing core.
const autoScaleRecordUpdate = this.fireStoreClient;
const document = autoScaleRecordUpdate.doc(`${FIRESTORE_DATABASE}/FORTIGATEMASTERELECTION`);
let getDoc;
try {
getDoc = await document.get();
} catch (err) {
console.error(`Error in getting Primary record ${err}`);
}
if (getDoc?._fieldsProto?.masterRecord?.mapValue?.fields?.InstanceId) {
const primaryInstanceId = getDoc._fieldsProto.masterRecord.mapValue.fields.InstanceId.stringValue;
// Includes all info needed to change the EIP, but we really just need the zone.
const resourceInfo = await this.getInstanceInfo(primaryInstanceId);
console.log(`Primary Election ${primaryInstanceId}, Zone: ${this.gcpSplitURL(resourceInfo.zone)}`);
console.log(`Attaching static address to Primary Instance`);
// Grab the zone from the GCP url and send to attachEIP
await this.attachEIPtoMaster(primaryInstanceId, this.gcpSplitURL(resourceInfo.zone));
}
try {
// Updates a nested object without removing the entire object.
await document.update({
['masterRecord.' + 'VoteState']: 'done'
});
} catch (err) {
console.error(`Error in finializing Primary record in election could not update Primary record. ${err}`);
}
return true;
}
public async setSettingItem(
key: string,
value: string | {},
description?: string,
jsonEncoded?: boolean,
editable?: boolean
): Promise<boolean> {
console.log('Updating Setting Database');
const document = this.fireStoreClient.doc(`${FIRESTORE_DATABASE}/SETTINGS`);
console.log(key, value);
try {
await document.update({
[key]: {
settingValue: value ? value : null,
editable: editable ? editable : false,
jsonEncoded: jsonEncoded ? jsonEncoded : false,
description: description ? description : 'No Description'
}
});
} catch (err) {
console.error(`Error in Updating Setting Table ${err}`);
}
return true;
}
// Parses the GCP request and returns the instanceId, HeartBeat Interval and status
public extractRequestInfo(runtimeAgent: GCPRuntimeAgent): AutoScaleCore.RequestInfo {
let interval = parseInt(process.env.HEARTBEAT_INTERVAL, 10) || 25;
if (runtimeAgent && runtimeAgent.headers && runtimeAgent.headers['fos-instance-id']) {
var instanceId = runtimeAgent.headers['fos-instance-id'];
} else if (runtimeAgent) {
// FortiGate does not send encoding, so a request must be parsed as follows:
const parseReq = JSON.parse(Object.keys(runtimeAgent.body)[0]);
instanceId = parseReq.instance;
interval = parseReq.interval;
} else if (runtimeAgent) {
try {
var instanceId = runtimeAgent.instance;
} catch (ex) {
this.logger.info('calling extractRequestInfo: unexpected body content format ', ex);
}
} else {
this.logger.error('calling extractRequestInfo: no request body found.');
}
console.log('Extracted instanceID:', instanceId);
return {
instanceId,
interval,
status: null
};
}
// Takes instanceID and returns IP etc.
public async describeInstance(descriptor: AutoScaleCore.VirtualMachineDescriptor): Promise<GCPVirtualMachine> {
const options = {
// Filter Options can be found here:
// https://cloud.google.com/nodejs/docs/reference/compute/0.10.x/Compute#getVMs
};
try {
console.log('Fetching VMs');
const [vms] = await this.compute.getVMs(options);
for (let vmData of vms) {
if (vmData.metadata.id === descriptor.instanceId) {
// TODO: look into additional values of the VM types.
var vmReturn: any = {
instanceId: vmData.metadata.id,
PrivateIpAddress: vmData.metadata.networkInterfaces[2].networkIP,
primaryPrivateIpAddress: vmData.metadata.networkInterfaces[2].networkIP,
SubnetId: vmData.metadata.networkInterfaces[2].subnetwork,
virtualNetworkId: 'empty',
zone: this.gcpSplitURL(vmData.metadata.zone)
};
return vmReturn;
}
}
} catch (err) {
console.error(`Error Fetching VM's from GCP. Error ${err}`);
throw err;
}
return null;
}
public gcpSplitURL(indexItem: string): string {
const lastindex = indexItem.lastIndexOf('/');
const result = indexItem.substring(lastindex + 1);
return result;
}
public async getCallbackEndpointUrl(processor?: AutoScaleCore.DataProcessor<GCPRuntimeAgent, URL>): Promise<URL> {
const functionURL = new URL(TRIGGER_URL);
console.log('CallbackURL', functionURL);
return functionURL;
}
public async terminateInstanceInAutoScalingGroup(instance: GCPVirtualMachine): Promise<boolean> {
try {
const vm = await this.compute.vm(instance).delete();
console.log(`Deleted instance: ${instance.instanceId}`);
return true;
} catch (err) {
console.log(`Failed to Delete instance: ${err}`);
return false;
}
}
public deleteInstances(parameters: AutoScaleCore.VirtualMachineDescriptor[]): Promise<boolean> {
throw new Error('Method not implemented.');
}
public createNetworkInterface(
parameters: AutoScaleCore.NetworkInterfaceDescriptor
): Promise<boolean | AutoScaleCore.NetworkInterfaceLike> {
throw new Error('Method not implemented.');
}
public deleteNetworkInterface(parameters: AutoScaleCore.NetworkInterfaceDescriptor): Promise<boolean> {
throw new Error('Method not implemented.');
}
public describeNetworkInterface(
parameters: AutoScaleCore.NetworkInterfaceDescriptor
): Promise<AutoScaleCore.NetworkInterfaceLike> {
throw new Error('Method not implemented.');
}
public listNetworkInterfaces(
parameters: AutoScaleCore.FilterLikeResourceQuery<GCPNameValuesPair>,
statusToInclude?: string[]
): Promise<AutoScaleCore.NetworkInterfaceLike[]> {
throw new Error('Method not implemented.');
}
public attachNetworkInterface(
instance: GCPVirtualMachine,
nic: AutoScaleCore.NetworkInterfaceLike
): Promise<string | boolean> {
throw new Error('Method not implemented.');
}
public detachNetworkInterface(
instance: GCPVirtualMachine,
nic: AutoScaleCore.NetworkInterfaceLike
): Promise<boolean> {
throw new Error('Method not implemented.');
}
public listNicAttachmentRecord(): Promise<AutoScaleCore.NicAttachmentRecord[]> {
throw new Error('Method not implemented.');
}
public getNicAttachmentRecord(instanceId: string): Promise<AutoScaleCore.NicAttachmentRecord> {
throw new Error('Method not implemented.');
}
public updateNicAttachmentRecord(
instanceId: string,
nicId: string,
state: AutoScaleCore.NicAttachmentState,
conditionState?: AutoScaleCore.NicAttachmentState
): Promise<boolean> {
throw new Error('Method not implemented.');
}
public deleteNicAttachmentRecord(
instanceId: string,
conditionState?: AutoScaleCore.NicAttachmentState
): Promise<boolean> {
throw new Error('Method not implemented.');
}
public listBlobFromStorage(parameters: AutoScaleCore.BlobStorageItemDescriptor): Promise<AutoScaleCore.Blob[]> {
throw new Error('Method not implemented.');
}
public listLicenseFiles(
parameters?: AutoScaleCore.BlobStorageItemDescriptor
): Promise<Map<string, AutoScaleCore.LicenseItem>> {
throw new Error('Method not implemented.');
}
public updateLicenseUsage(licenseRecord: AutoScaleCore.LicenseRecord, replace?: boolean): Promise<boolean> {
throw new Error('Method not implemented.');
}
public listLicenseUsage(): Promise<Map<string, AutoScaleCore.LicenseRecord>> {
throw new Error('Method not implemented.');
}
public listLicenseStock(): Promise<Map<string, AutoScaleCore.LicenseRecord>> {
throw new Error('Method not implemented.');
}
public updateLicenseStock(licenseItem: AutoScaleCore.LicenseItem, replace?: boolean): Promise<boolean> {
throw new Error('Method not implemented.');
}
public deleteLicenseStock(licenseItem: AutoScaleCore.LicenseItem): Promise<boolean> {
throw new Error('Method not implemented.');
}
public getVmInfoCache(scaleSetName: string, instanceId: string, vmId?: string): Promise<{}> {
throw new Error('Method not implemented.');
}
public setVmInfoCache(scaleSetName: string, info: {}, cacheTime?: number): Promise<void> {
throw new Error('Method not implemented.');
}
public getExecutionTimeRemaining(): number {
return Number(SCRIPT_TIMEOUT) - AutoScaleCore.Functions.getTimeLapse();
}
public describeVirtualNetwork(
parameters: AutoScaleCore.VirtualNetworkDescriptor
): Promise<AutoScaleCore.VirtualNetworkLike> {
throw new Error('Method not implemented.');
}
public listSubnets(parameters: AutoScaleCore.VirtualNetworkDescriptor): Promise<AutoScaleCore.SubnetLike[]> {
throw new Error('Method not implemented.');
}
public getLifecycleItems(instanceId: string): Promise<AutoScaleCore.LifecycleItem[]> {
throw new Error('Method not implemented.');
}
public updateLifecycleItem(item: AutoScaleCore.LifecycleItem): Promise<boolean> {
throw new Error('Method not implemented.');
}
public removeLifecycleItem(item: AutoScaleCore.LifecycleItem): Promise<boolean> {
throw new Error('Method not implemented.');
}
public cleanUpDbLifeCycleActions(
items: AutoScaleCore.LifecycleItem[]
): Promise<boolean | AutoScaleCore.LifecycleItem[]> {
throw new Error('Method not implemented.');
}
}
export class GCPAutoScaleHandler extends AutoscaleHandler<
GCPPlatformRequest,
GCPPlatformContext,
Console,
GCPNameValuesPair,
GCPPlatform.Instance,
GCPVirtualMachine,
GCPRuntimeAgent,
GCP
> {
constructor(platform: GCP) {
super(platform);
this._step = '';
this._selfInstance = null;
this._masterRecord = null;
this._selfHealthCheck = null;
this.scalingGroupName = process.env.AUTO_SCALING_GROUP_NAME;
this.compute = new Compute();
}
public logger: AutoScaleCore.Logger<Console>;
// tslint:disable-next-line: variable-name
public _step: string;
public compute: object;
private fireStoreClient = new Firestore();
public async removeInstance(instance: GCPVirtualMachine): Promise<boolean> {
return await this.platform.terminateInstanceInAutoScalingGroup(instance);
}
public async init(): Promise<boolean> {
const requiredSettings = {
'asset-storage-name': ASSET_STORAGE_NAME,
'fortigate-psk-secret': FORTIGATE_PSK_SECRET,
'asset-storage-key-prefix': process.env.ASSET_STORAGE_KEY_PREFIX,
'fortigate-default-password': 'empty',
'required-configset': 'empty',
'fortigate-autoscale-vpc-id': 'empty',
'settings-initialized': 'true',
'project-id': PROJECT_ID,
'trigger-url': TRIGGER_URL,
'resource-tag-prefix': process.env.RESOURCE_TAG_PREFIX,
'payg-scaling-group-name': process.env.PAYG_SCALING_GROUP_NAME,
'byol-scaling-group-name': process.env.BYOL_SCALING_GROUP_NAME,
'master-scaling-group-name': process.env.MASTER_SCALING_GROUP_NAME,
'required-config-set': process.env.REQUIRED_CONFIG_SET,
'unique-id': process.env.UNIQUE_ID,
'custom-id': process.env.CUSTOM_ID,
'autoscale-handler-url': process.env.AUTOSCALE_HANDLER_URL,
'deployment-settings-saved': process.env.DEPLOYMENT_SETTINGS_SAVED,
'enable-fortigate-elb': process.env.ENABLE_FORTIGATE_ELB,
'enable-dynamic-nat-gateway': process.env.ENABLE_DYNAMIC_NAT_GATEWAY,
'enable-hybrid-licensing': process.env.ENABLE_HYBRID_LICENSING,
'enable-internal-elb': process.env.ENABLE_INTERNAL_ELB,
'enable-second-nic': process.env.ENABLE_SECOND_NIC,
'enable-vm-info-cache': process.env.ENABLE_VM_INFO_CACHE,
'fortigate-admin-port': process.env.FORTIGATE_ADMIN_PORT,
'fortigate-sync-interface': process.env.FORTIGATE_SYNC_INTERFACE,
'master-election-no-wait': process.env.MASTER_ELECTION_NO_WAIT,
'heartbeat-interval': process.env.HEARTBEAT_INTERVAL,
'heart-beat-delay-allowance': process.env.HEART_BEAT_DELAY_ALLOWANCE
};
const db = await getTables();
const fireStoreDocument = this.fireStoreClient.doc(`${FIRESTORE_DATABASE}/SETTINGS`);
const tableArray = [
db.FORTIGATEAUTOSCALE,
db.FORTIGATEMASTERELECTION,
db.LIFECYCLEITEM,
db.FORTIANALYZER,
db.SETTINGS
];
// Check if "settings-initialized" == true and if not Initilize the empty collections
try {
const getDoc: any = await fireStoreDocument.get();
if (
getDoc &&
getDoc._fieldsProto &&
getDoc._fieldsProto['deployment-settings-saved'] &&
getDoc._fieldsProto['deployment-settings-saved'].mapValue.fields &&
getDoc._fieldsProto['deployment-settings-saved'].mapValue.fields.settingValue &&
getDoc._fieldsProto['deployment-settings-saved'].mapValue.fields.settingValue.stringValue &&
getDoc._fieldsProto['deployment-settings-saved'].mapValue.fields.settingValue.stringValue === 'true'
) {
console.log('Settings already exist');
await this.loadSettings();
} else {
for (const table of tableArray) {
console.log(`Initializing FireStore Document ${table}`);
const tableCreate = await this.fireStoreClient.doc(`${FIRESTORE_DATABASE}/${table}`);
await tableCreate.set({});
}
await this.saveSettings(requiredSettings);
await this.saveSettings({
'deployment-settings-saved': 'true'
});
await this.loadSettings();
}
} catch (err) {
console.log('Error in getting record: ', err);
}
return true;
}
public async saveSettings(settings: { [key: string]: any }) {
settings = {};
Object.entries(process.env).forEach(entry => {
settings[entry[0].replace(new RegExp('_', 'g'), '')] = entry[1];
});
settings.deploymentsettingssaved = 'true';
return await super.saveSettings(settings);
}
public updateCapacity(
scalingGroupName: string,
desiredCapacity: number,
minSize: number,
maxSize: number
): Promise<boolean> {
throw new Error('Method not implemented.');
}
public checkAutoScalingGroupState(scalingGroupName: string): Promise<string> {
throw new Error('Method not implemented.');
}
public findRecyclableLicense(
stockRecords: Map<string, LicenseRecord>,
usageRecords: Map<string, LicenseRecord>,
limit?: number | 'all'
): Promise<LicenseRecord[]> {
throw new Error('Method not implemented.');
}
public async addInstanceToMonitor(
instance: GCPVirtualMachine,
heartBeatInterval: number,
masterIp?: string
): Promise<boolean> {
console.log(`Adding Instance to monitor (FORTIGATEAUTOSCALE) ${instance.instanceId}`);
const datetoInt = Date.now();
const nextHeartBeat = Date.now() + heartBeatInterval * 1000;
const autoScaleRecordUpdate = this.fireStoreClient;
const document = autoScaleRecordUpdate.doc(`${FIRESTORE_DATABASE}/FORTIGATEAUTOSCALE`);
const fieldName = instance.instanceId;
try {
await document.update({
[fieldName]: {
heartBeatInterval: 0,
heartBeatLossCount: 0,
masterIp,
checkPointTime: datetoInt,
ip: instance.primaryPrivateIpAddress,
primaryPrivateIpAddress: instance.primaryPrivateIpAddress,
inSync: true,
syncState: 'in-sync',
nextHeartBeatTime: nextHeartBeat || 0,
healthy: true
}
});
} catch (err) {
console.log(
`Error in addInstanceToMonitor. Could not add instance ${instance.instanceId} to Database, ${err}`
);
return false;
}
return true;
}
public async handle(event: any, context: any, callback: any) {
await super.handle(event, context, callback);
}
public async handleGetConfig(event?: any): Promise<AutoScaleCore.ErrorDataPairLike> {
const instanceId = this._requestInfo.instanceId;
this._selfInstance =
this._selfInstance ||
(await this.platform.describeInstance({
instanceId,
scalingGroupName: this.scalingGroupName
} as Platform.VirtualMachineDescriptor));
const platform = this.platform;
let config;
let masterInfo;
let masterIp;
let duplicatedGetConfigCall;
let hbSyncEndpoint: URL;
const moreConfigSets: AutoScaleCore.ConfigSetParser[] = [];
const promiseEmitter = this.checkMasterElection.bind(this),
validator = result => {
if (
this._masterRecord &&
this._masterRecord.voteState === 'pending' &&
this._selfInstance &&
this._masterRecord.instanceId === this._selfInstance.instanceId &&
this._masterRecord.scalingGroupName === this.masterScalingGroupName
) {
duplicatedGetConfigCall = true;
masterIp = this._masterRecord.ip;
return true;
}
if (result) {
if (result.primaryPrivateIpAddress === this._selfInstance.primaryPrivateIpAddress) {
masterIp = this._selfInstance.primaryPrivateIpAddress;
return true;
} else if (this._masterRecord) {
if (this._masterRecord.voteState === 'done') {
// master election done
return true;
} else if (this._masterRecord.voteState === 'pending') {
this._masterRecord = null;
return false;
} else {
return false;
}
} else {
this.logger.warn('master info found but master record not found. retry.');
return false;
}
} else {
return this._settings['master-election-no-wait'].toString() === 'false';
}
},
counter = () => {
// if script is about to timeout
if (platform.getExecutionTimeRemaining() < 3000) {
return false;
}
this.logger.warn('script execution is about to expire');
return true;
};
try {
masterInfo = await AutoScaleCore.Functions.waitFor(promiseEmitter, validator, 5000, 25);
} catch (error) {
console.log('HandlegetConfig Error: ', error);
this._masterRecord = this._masterRecord || (await this.platform.getMasterRecord());
if (
this._masterRecord &&
this._masterRecord.instanceId === this._selfInstance.instanceId &&
this._masterRecord.scalingGroupName === this._selfInstance.scalingGroupName