-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.yaml
1099 lines (962 loc) · 38.7 KB
/
template.yaml
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
AWSTemplateFormatVersion: '2010-09-09'
Description: Template for Base Central Module in Stream Data Guided Hackathon
Parameters:
StreamInterval:
Description: Number of minutes between executing lambda to write to the Kinesis Stream
Type: Number
Default: 1
MinValue: 1
MaxHours:
Type: Number
Default: 8
MaxAttendees:
Type: Number
Default: 10000
TotalSocialPosts:
Type: Number
Description: Total number of posts in the social source data
Default: 160211
SocialPostObjectName:
Type: String
Default: SocialPosts.csv.gz
ExportPrefix:
Type: String
S3AssetBucket:
Type: String
S3AssetPrefix:
Type: String
Resources:
StaticDataBucket:
Type: AWS::S3::Bucket
GenerateStaticDataLambdaLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${GenerateStaticDataLambda}'
RetentionInDays: 7
GenerateStaticDataLambdaCustom:
Type: Custom::GenerateStaticDataLambda
Properties:
ServiceToken: !Sub '${GenerateStaticDataLambda.Arn}'
BadgeScanStream:
Type: AWS::Kinesis::Stream
Properties:
StreamModeDetails:
StreamMode: ON_DEMAND
EventStartTimeParameter:
Type: AWS::SSM::Parameter
Properties:
Type: String
Value: Not Started
WriteStreamBadgeScansLambdaLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${WriteStreamBadgeScansLambda}'
RetentionInDays: 7
SocialPostTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: Id
AttributeType: N
KeySchema:
- AttributeName: Id
KeyType: HASH
ImportSourceSpecification:
S3BucketSource:
S3Bucket: !Ref 'S3AssetBucket'
S3KeyPrefix: !Sub '${S3AssetPrefix}/${SocialPostObjectName}'
InputFormat: CSV
InputFormatOptions:
Csv:
Delimiter: ','
InputCompressionType: GZIP
SocialPostsStream:
Type: AWS::Kinesis::Stream
Properties:
StreamModeDetails:
StreamMode: ON_DEMAND
WriteSocialPostsLambdaLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${WriteSocialPostsLambda}'
RetentionInDays: 7
BlockParticipantAccessIAMPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Deny
Action: dynamodb:*
Resource:
- !Sub '${ScannedAttendeeTable.Arn}'
- !Sub '${SocialPostTable.Arn}'
- Effect: Deny
Action: lambda:*
Resource:
- !Sub '${WriteSocialPostsLambda.Arn}'
- !Sub '${WriteStreamBadgeScansLambda.Arn}'
- !Sub '${GenerateStaticDataLambda.Arn}'
- Effect: Deny
Action: s3:DeleteBucket
Resource:
- !Sub '${StaticDataBucket.Arn}'
- Effect: Deny
Action:
- s3:PutObject
- s3:DeleteObject
- s3:DeleteObjetVersion
Resource:
- !Sub '${StaticDataBucket.Arn}/*'
StartEventLambdaLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${StartEventLambda}'
RetentionInDays: 7
GenerateStaticDataLambda:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
import cfnresponse
import logging
import os
from faker import Faker
import json
import csv
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
s3_client = boto3.client('s3')
s3_resource = boto3.resource('s3')
FILE_NAME = 'registrations.csv'
LOCAL_PATH = '/tmp/' + FILE_NAME
S3_PREFIX = 'registrations/' + FILE_NAME
MAX_ATTENDEES = int(os.environ['MAX_ATTENDEES'])
ASSET_BUCKET = os.environ['ASSET_BUCKET']
fake = Faker()
Faker.seed(345345)
def lambda_handler(event, context):
logger.info('This is the event: ' + json.dumps(event))
if event.get('RequestType') == 'Create':
responseData = {}
responseData['message'] = "About to start the generating the static dat"
logger.info('Sending %s to cloudformation', responseData['message'])
try:
dummy_registrations = generate_dummy_registrations(MAX_ATTENDEES)
save_to_csv(dummy_registrations, LOCAL_PATH)
copy_to_s3(ASSET_BUCKET, LOCAL_PATH, FILE_NAME)
responseData['message'] = "Generated the static data"
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
except Exception as e:
responseData['message'] = str(e)
logger.error('Exception encountered: %s', responseData['message'])
cfnresponse.send(event, context, cfnresponse.FAILED, responseData)
elif event.get('RequestType') == 'Delete':
responseData = {}
responseData['message'] = "Emptying the bucket"
try:
empty_bucket(ASSET_BUCKET)
responseData['message'] = "Bucket %s emptied", ASSET_BUCKET
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
except Exception as e:
responseData['message'] = str(e)
logger.error('Exception encountered: %s', responseData['message'])
cfnresponse.send(event, context, cfnresponse.FAILED, responseData)
else:
logger.error('Unknown operation: %s', event.get('RequestType'))
def generate_dummy_registrations(num_records):
data = []
for _ in range(num_records):
registration_date = fake.date_between(start_date='-6m', end_date='today')
first_name = fake.first_name().replace(",", "")
last_name = fake.last_name().replace(",", "")
company_name = fake.company().replace(",", "")
title = fake.job().replace(",", "")
industry = fake.random_element(elements=('Technology', 'Finance', 'Healthcare', 'Retail', 'Manufacturing', 'Public Sector'))
event_expectations = fake.paragraphs(nb=2)
data.append((registration_date, first_name, last_name, company_name, title, industry, event_expectations))
return data
def save_to_csv(data, filename):
with open(filename, 'w', newline='') as csvfile:
logger.info('Writing data to csv file: ' + filename)
writer = csv.writer(csvfile)
writer.writerow(['id', 'registration_date', 'first_name', 'last_name', 'company_name', 'title', 'industry', 'event_expectations'])
for i, row in enumerate(data):
writer.writerow([i+1] + list(row))
def copy_to_s3(bucket, local_path, filename):
logger.info('Copying file to S3 bucket: ' + bucket)
s3_client.upload_file(local_path, bucket, S3_PREFIX)
def empty_bucket(bucket_name):
logging.info('About to delete the files in S3 bucket ' + bucket_name)
bucket = s3_resource.Bucket(bucket_name)
bucket.object_versions.delete()
Handler: index.lambda_handler
MemorySize: 256
Role: !GetAtt 'GenerateStaticDataLambdaRole.Arn'
Runtime: python3.10
Timeout: 120
Environment:
Variables:
MAX_ATTENDEES: !Ref 'MaxAttendees'
ASSET_BUCKET: !Ref 'StaticDataBucket'
TracingConfig:
Mode: Active
Architectures:
- arm64
GenerateStaticDataLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
- arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess
Policies:
- PolicyName: GenerateStaticDataLambdaRolePolicy0
PolicyDocument:
Statement:
- Action:
- s3:GetObject
- s3:ListBucket
- s3:GetBucketLocation
- s3:GetObjectVersion
- s3:PutObject
- s3:PutObjectAcl
- s3:GetLifecycleConfiguration
- s3:PutLifecycleConfiguration
- s3:DeleteObject
Effect: Allow
Resource:
- !Sub
- arn:${AWS::Partition}:s3:::${bucketName}
- bucketName: !Ref 'StaticDataBucket'
- !Sub
- arn:${AWS::Partition}:s3:::${bucketName}/*
- bucketName: !Ref 'StaticDataBucket'
- PolicyName: GenerateStaticDataLambdaRolePolicy1
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:ListObjectVersions
- s3:DeleteObjectVersion
Resource: !Sub '${StaticDataBucket.Arn}/*'
- Effect: Allow
Action:
- s3:ListBucketVersions
Resource:
- !Sub '${StaticDataBucket.Arn}'
WriteStreamBadgeScansLambda:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
import os
import time
import datetime as dt
import random
import json
import logging
import threading
import math
import boto3
STREAM_ARN = os.environ["STREAM_ARN"]
PARAM_NAME = os.environ["PARAM_NAME"]
# DB_NAME = os.environ['DB_NAME']
TABLE_NAME = os.environ['TABLE_NAME']
MAX_HOURS = int(os.environ['MAX_HOURS'])
MAX_ATTENDEES = int(os.environ['MAX_ATTENDEES'])
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# logger.setLevel(logging.DEBUG)
kinesis_client = boto3.client("kinesis")
ssm_client = boto3.client("ssm")
timestream_client = boto3.client("timestream-query")
ddb_client = boto3.client('dynamodb')
def lambda_handler(event, context):
event_running_hours = get_event_running_hours()
logger.info("Event Running Hours: %s", event_running_hours)
# attendees_arrived = attendees_scanned()
current_attendees = get_attendees()
current_attendees_count = len(current_attendees)
logger.info('Current number of attendees: %s', current_attendees_count)
# if len(current_attendees) > 0:
# current_attendees = get_attendees()
# current_attendees_count = len(current_attendees)
if event_running_hours != 'Not Started' and event_running_hours <= MAX_HOURS:
registration_scanning_thread = threading.Thread(target=registration_scanning, args=(event_running_hours, current_attendees_count, ))
registration_scanning_thread.start()
if current_attendees_count > 0:
booth_scanning_thread = threading.Thread(target=booth_scanning, args=(event_running_hours, current_attendees, current_attendees_count, ))
booth_scanning_thread.start()
if event_running_hours > 0:
exit_scanning_thread = threading.Thread(target=exit_scanning, args=(event_running_hours, current_attendees, current_attendees_count, ))
exit_scanning_thread.start()
exit_scanning_thread.join()
booth_scanning_thread.join()
registration_scanning_thread.join()
def get_event_running_hours():
response = ssm_client.get_parameter(Name=PARAM_NAME, WithDecryption=False)
event_start_time = response['Parameter']['Value']
if event_start_time == 'Not Started':
return event_start_time
else:
event_start_time = dt.datetime.fromisoformat(event_start_time)
event_elapsed_time = dt.datetime.now() - event_start_time
event_running_hours = int(event_elapsed_time / dt.timedelta(hours=1))
return event_running_hours
def attendees_scanned():
query_string = f'SELECT * FROM "{DB_NAME}"."{TABLE_NAME}" LIMIT 1'
paginator = timestream_client.get_paginator('query')
page_iterator = paginator.paginate(QueryString=query_string)
row_found = False
for page in page_iterator:
for row in page["Rows"]:
row_found = True
return row_found
def get_attendees():
response = ddb_client.scan(
TableName=TABLE_NAME,
Select='ALL_ATTRIBUTES'
)
logger.debug('get_attendees response %s', json.dumps(response, indent=4))
return response['Items']
def registration_scanning(event_running_hours, current_attendees_count):
random_scan_count = random.randint(1, (20))
logger.debug('Registration Scanning Random Scan Count: %s', random_scan_count)
scan_count = int(random_scan_count * math.floor(MAX_HOURS - event_running_hours))
if event_running_hours >= (MAX_HOURS - 1) or current_attendees_count >= MAX_ATTENDEES:
scan_count = 0
elif scan_count > 60:
scan_count = 60 + random.randint(1, 20)
logger.info('Registration Scanning Scan Count: %s', scan_count)
for _ in range(scan_count):
time.sleep(math.floor(60 / scan_count) + 1)
badge_scan = create_badge_scan()
response = write_to_stream(badge_scan)
logger.debug(response)
response = write_to_ddb(badge_scan)
logger.debug(json.dumps(response, indent=4))
def booth_scanning(event_running_hours, current_attendees, current_attendees_count):
random_scan_count = random.randint(1, (40))
logger.debug('Booth Scanning Random Scan Count: %s', random_scan_count)
if event_running_hours == 0 or event_running_hours > 7:
scan_count = int(random_scan_count / 2)
elif event_running_hours > 2:
scan_count = random_scan_count * int(event_running_hours / 2)
else:
scan_count = random_scan_count * event_running_hours
if scan_count > 120:
scan_count = 120
logger.info('Booth Scanning Scan Count: %s', scan_count)
for _ in range(scan_count):
time.sleep(1)
booth_scan = create_booth_scan(current_attendees, current_attendees_count)
response = write_to_stream(booth_scan)
logger.debug(response)
def exit_scanning(event_running_hours, current_attendees, current_attendees_count):
random_scan_count = random.randint(1, (20))
logger.debug('Exit Scanning Random Scan Count: %s', random_scan_count)
scan_count = math.floor((random_scan_count * event_running_hours) * math.ceil(current_attendees_count / 3000))
if scan_count > current_attendees_count:
scan_count = current_attendees_count
if scan_count > 60:
scan_count = 60
logger.info('Exit Scanning Scan Count: %s', scan_count)
for _ in range(scan_count):
time.sleep(random.randint(1, 3))
exit_scan = create_exit_scan(current_attendees, current_attendees_count)
response = write_to_stream(exit_scan)
logger.debug(response)
response = delete_from_ddb(exit_scan)
logger.debug(json.dumps(response, indent=4))
def create_badge_scan():
badge_id = random.randint(1, MAX_ATTENDEES)
response = ddb_client.get_item(
TableName=TABLE_NAME,
Key={
'id': {
'S': str(badge_id)
}
}
)
i = 1
while 'Item' in response:
i = i + 1
logger.info('Badge found generated another random id: %s', badge_id)
badge_id = random.randint(1, MAX_ATTENDEES)
response = ddb_client.get_item(
TableName=TABLE_NAME,
Key={
'id': {
'S': str(badge_id)
}
}
)
if i > 500:
logger.info('Tried 500 times to get a badge id, giving up')
break
logger.debug('DDB Response for unique badge id check: %s', json.dumps(response, indent=4))
desk_no = random.randint(1, 6)
current_time = _current_milli_time()
dimensions = [
{'Name': 'location','Value': 'sign-in-desk-' + str(desk_no)},
{'Name': 'scan_type','Value': 'entry'},
{'Name': 'badge_id','Value': str(badge_id)}
]
badge_scan = [{
'Dimensions': dimensions,
'MeasureName': 'scan',
'MeasureValue': '1',
'MeasureValueType': 'BIGINT',
'Time': current_time
}]
return badge_scan
def create_booth_scan(current_attendees, current_attendees_count):
badge_id = current_attendees[random.randint(0, current_attendees_count - 1)]['id']['S']
booth_no = random.randint(1, 50)
current_time = _current_milli_time()
dimensions = [
{'Name': 'location','Value': 'booth-' + format(booth_no, '02d')},
{'Name': 'scan_type','Value': 'booth'},
{'Name': 'badge_id','Value': str(badge_id)}
]
badge_scan = [{
'Dimensions': dimensions,
'MeasureName': 'scan',
'MeasureValue': '1',
'MeasureValueType': 'BIGINT',
'Time': current_time
}]
return badge_scan
def create_exit_scan(current_attendees, current_attendees_count):
# badge_id = current_attendees[random.randint(0, current_attendees_count - 1)]['Data'][0]['ScalarValue']
badge_id = current_attendees[random.randint(0, current_attendees_count - 1)]['id']['S']
exit_no = random.randint(1, 50)
current_time = _current_milli_time()
dimensions = [
{'Name': 'location','Value': 'exit-point-' + str(exit_no)},
{'Name': 'scan_type','Value': 'exit'},
{'Name': 'badge_id','Value': str(badge_id)}
]
badge_scan = [{
'Dimensions': dimensions,
'MeasureName': 'scan',
'MeasureValue': '1',
'MeasureValueType': 'BIGINT',
'Time': current_time
}]
return badge_scan
def write_to_stream(badge_scan):
response = kinesis_client.put_record(
StreamARN=STREAM_ARN,
Data=json.dumps(badge_scan),
PartitionKey=badge_scan[0]['Dimensions'][2]['Value']
)
if response['ResponseMetadata']['HTTPStatusCode'] != 200:
logger.error('Error writing to Kinesis: %s', json.dumps(response, indent=4))
raise Exception('Error writing to Kinesis')
return response
def write_to_ddb(badge_scan):
logger.debug('Data to be written to DDB: %s', json.dumps(badge_scan, indent=4))
item = {'id': {'S': badge_scan[0]['Dimensions'][2]['Value']}}
response = ddb_client.put_item(
TableName=TABLE_NAME,
Item=item
)
if response['ResponseMetadata']['HTTPStatusCode'] != 200:
logger.error('Error writing to DDB: %s', json.dumps(response, indent=4))
raise Exception('Error writing to DDB')
return response
def delete_from_ddb(exit_scan):
logger.debug('Data to be deleted from DDB: %s', json.dumps(exit_scan, indent=4))
item = {'id': {'S': exit_scan[0]['Dimensions'][2]['Value']}}
response = ddb_client.delete_item(
TableName=TABLE_NAME,
Key=item
)
if response['ResponseMetadata']['HTTPStatusCode'] != 200:
logger.error('Error deleting from DDB: %s', json.dumps(response, indent=4))
raise Exception('Error deleting from DDB')
return response
def _current_milli_time():
return str(int(round(time.time() * 1000)))
Handler: index.lambda_handler
Role: !GetAtt 'WriteStreamBadgeScansLambdaRole.Arn'
Runtime: python3.10
Timeout: 240
Environment:
Variables:
STREAM_ARN: !Sub '${BadgeScanStream.Arn}'
PARAM_NAME: !Ref 'EventStartTimeParameter'
TABLE_NAME: !Ref 'ScannedAttendeeTable'
MAX_HOURS: !Ref 'MaxHours'
MAX_ATTENDEES: !Ref 'MaxAttendees'
TracingConfig:
Mode: Active
Architectures:
- arm64
WriteStreamBadgeScansLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
- arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess
Policies:
- PolicyName: WriteStreamBadgeScansLambdaRolePolicy0
PolicyDocument:
Statement:
- Action:
- kinesis:AddTagsToStream
- kinesis:CreateStream
- kinesis:DecreaseStreamRetentionPeriod
- kinesis:DeleteStream
- kinesis:DescribeStream
- kinesis:DescribeStreamSummary
- kinesis:GetShardIterator
- kinesis:IncreaseStreamRetentionPeriod
- kinesis:ListTagsForStream
- kinesis:MergeShards
- kinesis:PutRecord
- kinesis:PutRecords
- kinesis:SplitShard
- kinesis:RemoveTagsFromStream
Effect: Allow
Resource: !Sub
- arn:${AWS::Partition}:kinesis:${AWS::Region}:${AWS::AccountId}:stream/${streamName}
- streamName: !Ref 'BadgeScanStream'
- PolicyName: WriteStreamBadgeScansLambdaRolePolicy1
PolicyDocument:
Statement:
- Action:
- ssm:DescribeParameters
Effect: Allow
Resource: '*'
- Action:
- ssm:GetParameters
- ssm:GetParameter
- ssm:GetParametersByPath
Effect: Allow
Resource: !Sub
- arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${parameterName}
- parameterName: !Ref 'EventStartTimeParameter'
WriteStreamBadgeScansLambdaScheduleEvent:
Type: AWS::Scheduler::Schedule
Properties:
ScheduleExpression: !Sub 'rate(${StreamInterval} minute)'
FlexibleTimeWindow:
Mode: 'OFF'
Name: !Sub '${AWS::StackName}-WriteStreamBadgeScansLambda-ScheduleEvent'
Target:
Arn: !GetAtt 'WriteStreamBadgeScansLambda.Arn'
RoleArn: !GetAtt 'WriteStreamBadgeScansLambdaScheduleEventRole.Arn'
WriteStreamBadgeScansLambdaScheduleEventRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- scheduler.amazonaws.com
Policies:
- PolicyName: WriteStreamBadgeScansLambdaScheduleEventLambdaPolicy
PolicyDocument:
Statement:
- Action: lambda:InvokeFunction
Effect: Allow
Resource: !GetAtt 'WriteStreamBadgeScansLambda.Arn'
WriteSocialPostsLambda:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
import os
import datetime as dt
import random
import json
import logging
import math
import boto3
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all
patch_all()
STREAM_ARN = os.environ["STREAM_ARN"]
PARAM_NAME = os.environ["PARAM_NAME"]
SOCIAL_POST_TABLE_NAME = os.environ['SOCIAL_POST_TABLE_NAME']
SCANNED_ATTENDEE_TABLE_NAME = os.environ['SCANNED_ATTENDEE_TABLE_NAME']
TOTAL_SOCIAL_POSTS=os.environ['TOTAL_SOCIAL_POSTS']
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# logger.setLevel(logging.DEBUG)
kinesis_client = boto3.client("kinesis")
ssm_client = boto3.client("ssm")
ddb_client = boto3.client('dynamodb')
def lambda_handler(event, context):
event_running_hours = get_event_running_hours()
logger.info("Event Running Hours: %s", event_running_hours)
current_attendees = get_attendees()
current_attendees_count = len(current_attendees)
logger.info('Current number of attendees: %s', current_attendees_count)
if current_attendees_count > 0 and event_running_hours > 0:
logger.info('Event is running and attendees have arrived')
number_of_posts = math.ceil(current_attendees_count / 3000) * random.randint(1, 4)
logger.info('Number of posts: %s', number_of_posts)
for _ in range(number_of_posts):
post = create_social_post()
logger.debug('Post created: %s', json.dumps(post, indent=4))
response = kinesis_client.put_record(
StreamARN=STREAM_ARN,
Data=json.dumps(post),
PartitionKey=post['id']
)
if response['ResponseMetadata']['HTTPStatusCode'] != 200:
logger.error('Response: %s', json.dumps(response, indent=4))
def create_social_post():
post_id = random.randint(1, int(TOTAL_SOCIAL_POSTS))
logger.info('Creating social post with id: %s', post_id)
response = ddb_client.get_item(
TableName=SOCIAL_POST_TABLE_NAME,
Key={
'Id': {
'N': str(post_id)
}
}
)
ddb_post = response['Item']
post = {
'id': ddb_post['Postid']['S'],
'source': 'Twitter',
'user': ddb_post['user']['S'],
'message': ddb_post['post']['S'],
'timestamp': str(dt.datetime.now())
}
return post
def get_event_running_hours():
response = ssm_client.get_parameter(Name=PARAM_NAME, WithDecryption=False)
event_start_time = response['Parameter']['Value']
if event_start_time == 'Not Started':
return event_start_time
else:
event_start_time = dt.datetime.fromisoformat(event_start_time)
event_elapsed_time = dt.datetime.now() - event_start_time
event_running_hours = int(event_elapsed_time / dt.timedelta(hours=1))
return event_running_hours
def get_attendees():
response = ddb_client.scan(
TableName=SCANNED_ATTENDEE_TABLE_NAME,
Select='ALL_ATTRIBUTES'
)
return response['Items']
Handler: index.lambda_handler
Role: !GetAtt 'WriteSocialPostsLambdaRole.Arn'
Runtime: python3.10
Timeout: 240
Environment:
Variables:
STREAM_ARN: !Sub '${SocialPostsStream.Arn}'
PARAM_NAME: !Ref 'EventStartTimeParameter'
SOCIAL_POST_TABLE_NAME: !Ref 'SocialPostTable'
SCANNED_ATTENDEE_TABLE_NAME: !Ref 'ScannedAttendeeTable'
TOTAL_SOCIAL_POSTS: !Ref 'TotalSocialPosts'
TracingConfig:
Mode: Active
Layers:
- !Ref 'XRayLayer40fc5eb8f3'
Architectures:
- arm64
WriteSocialPostsLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
- arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess
Policies:
- PolicyName: WriteSocialPostsLambdaRolePolicy0
PolicyDocument:
Statement:
- Action:
- kinesis:AddTagsToStream
- kinesis:CreateStream
- kinesis:DecreaseStreamRetentionPeriod
- kinesis:DeleteStream
- kinesis:DescribeStream
- kinesis:DescribeStreamSummary
- kinesis:GetShardIterator
- kinesis:IncreaseStreamRetentionPeriod
- kinesis:ListTagsForStream
- kinesis:MergeShards
- kinesis:PutRecord
- kinesis:PutRecords
- kinesis:SplitShard
- kinesis:RemoveTagsFromStream
Effect: Allow
Resource: !Sub
- arn:${AWS::Partition}:kinesis:${AWS::Region}:${AWS::AccountId}:stream/${streamName}
- streamName: !Ref 'SocialPostsStream'
- PolicyName: WriteSocialPostsLambdaRolePolicy1
PolicyDocument:
Statement:
- Action:
- ssm:DescribeParameters
Effect: Allow
Resource: '*'
- Action:
- ssm:GetParameters
- ssm:GetParameter
- ssm:GetParametersByPath
Effect: Allow
Resource: !Sub
- arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${parameterName}
- parameterName: !Ref 'EventStartTimeParameter'
WriteSocialPostsLambdaScheduleEvent:
Type: AWS::Scheduler::Schedule
Properties:
ScheduleExpression: !Sub 'rate(${StreamInterval} minute)'
FlexibleTimeWindow:
Mode: 'OFF'
Name: !Sub '${AWS::StackName}-WriteSocialPostsLambda-ScheduleEvent'
Target:
Arn: !GetAtt 'WriteSocialPostsLambda.Arn'
RoleArn: !GetAtt 'WriteSocialPostsLambdaScheduleEventRole.Arn'
WriteSocialPostsLambdaScheduleEventRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- scheduler.amazonaws.com
Policies:
- PolicyName: WriteSocialPostsLambdaScheduleEventLambdaPolicy
PolicyDocument:
Statement:
- Action: lambda:InvokeFunction
Effect: Allow
Resource: !GetAtt 'WriteSocialPostsLambda.Arn'
StartEventLambda:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
import os
from datetime import datetime as dt
import boto3
PARAM_NAME = os.environ["PARAM_NAME"]
ssm_client = boto3.client("ssm")
def lambda_handler(event, context):
response = ssm_client.put_parameter(
Name=PARAM_NAME,
Value=dt.now().isoformat(),
Overwrite=True
)
return response
Handler: index.lambda_handler
Role: !GetAtt 'StartEventLambdaRole.Arn'
Runtime: python3.10
Environment:
Variables:
PARAM_NAME: !Ref 'EventStartTimeParameter'
TracingConfig:
Mode: Active
Architectures:
- arm64
StartEventLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
- arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess
Policies:
- PolicyName: StartEventLambdaRolePolicy0
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ssm:PutParameter
- ssm:GetParameter
Resource: !Sub 'arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${EventStartTimeParameter}'
XRayLayer40fc5eb8f3:
Type: AWS::Lambda::LayerVersion
DeletionPolicy: Retain
Properties:
Content:
S3Bucket: !Ref 'None'
S3Key: !Sub '214612b2-513d-427e-9638-67d348d6d121/cfn/4096067a82ee490eb449921f654820f2'
LayerName: XRayLayer
CompatibleRuntimes:
- python3.10
ScannedAttendeeTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
BillingMode: PAY_PER_REQUEST
WriteStreamBadgeScansLambdaWriteDDBConnPolicy:
Type: AWS::IAM::ManagedPolicy
Metadata:
aws:sam:connectors:
WriteStreamBadgeScansLambdaWriteDDBConn:
Source:
Type: AWS::Serverless::Function
Destination:
Type: AWS::Serverless::SimpleTable
Properties:
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- dynamodb:GetItem
- dynamodb:Query
- dynamodb:Scan
- dynamodb:BatchGetItem
- dynamodb:ConditionCheckItem
- dynamodb:PartiQLSelect
Resource:
- !GetAtt 'ScannedAttendeeTable.Arn'
- !Sub
- ${DestinationArn}/index/*
- DestinationArn: !GetAtt 'ScannedAttendeeTable.Arn'
- Effect: Allow