forked from airbnb/streamalert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manage.py
executable file
·1510 lines (1238 loc) · 44.3 KB
/
manage.py
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
#! /usr/bin/env python
"""
Copyright 2017-present, Airbnb Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
---------------------------------------------------------------------------
This script builds StreamAlert AWS infrastructure, is responsible for
deploying to AWS Lambda, and publishing production versions.
To run terraform by hand, change to the terraform directory and run:
terraform <cmd>
"""
# pylint: disable=too-many-lines
from argparse import Action, ArgumentParser, RawDescriptionHelpFormatter
import os
import string
import sys
import textwrap
from stream_alert import __version__ as version
from stream_alert.alert_processor.outputs.output_base import StreamAlertOutput
from stream_alert.apps import StreamAlertApp
from stream_alert.apps.config import AWS_RATE_RE, AWS_RATE_HELPER
from stream_alert.shared import CLUSTERED_FUNCTIONS, metrics
from stream_alert_cli.test import DEFAULT_TEST_FILES_DIRECTORY
from stream_alert_cli.runner import cli_runner
CLUSTERS = [
os.path.splitext(cluster)[0] for _, _, files in os.walk('conf/clusters')
for cluster in files
]
class UniqueSetAction(Action):
"""Subclass of argparse.Action to avoid multiple of the same choice from a list"""
def __call__(self, parser, namespace, values, option_string=None):
unique_items = set(values)
setattr(namespace, self.dest, unique_items)
class MutuallyExclusiveStagingAction(Action):
"""Subclass of argparse.Action to avoid staging and unstaging the same rules"""
def __call__(self, parser, namespace, values, option_string=None):
unique_items = set(values)
error = (
'The following rules cannot be within both the \'--stage-rules\' argument '
'and the \'--unstage-rules\' argument: {}'
)
if namespace.unstage_rules:
offending_rules = unique_items.intersection(namespace.unstage_rules)
if offending_rules:
raise parser.error(error.format(', '.join(list(offending_rules))))
if namespace.stage_rules:
offending_rules = unique_items.intersection(namespace.stage_rules)
if offending_rules:
raise parser.error(error.format(', '.join(list(offending_rules))))
setattr(namespace, self.dest, unique_items)
def add_timeout_arg(parser):
"""Add the timeout argument to a parser"""
def _validator(val):
"""Validate acceptable inputs for the timeout of the function"""
error = 'Value for \'timeout\' must be an integer between 10 and 900'
try:
timeout = int(val)
except ValueError:
raise parser.error(error)
if not 10 <= timeout <= 900:
raise parser.error(error)
return timeout
parser.add_argument(
'-t',
'--timeout',
required=True,
help=(
'The AWS Lambda function timeout value, in seconds. '
'This should be an integer between 10 and 900.'
),
type=_validator
)
def add_memory_arg(parser):
"""Add the memory argument to a parser"""
def _validator(val):
"""Validate the memory value to ensure it is between 128 and 3008 and a multiple of 64"""
error = (
'Value for \'memory\' must be an integer between 128 and 3008, and be a multiple of 64'
)
try:
memory = int(val)
except ValueError:
raise parser.error(error)
if not 128 <= memory <= 3008:
raise parser.error(error)
if memory % 64 != 0:
raise parser.error(error)
return memory
parser.add_argument(
'-m',
'--memory',
required=True,
help=(
'The AWS Lambda function max memory value, in megabytes. '
'This should be an integer between 128 and 3008, and be a multiple of 64.'
),
type=_validator
)
def add_schedule_expression_arg(parser):
"""Add the schedule expression argument to a parser"""
def _validator(val):
"""Validate the schedule expression rate value for acceptable input"""
rate_match = AWS_RATE_RE.match(val)
if rate_match:
return val
if val.startswith('rate('):
err = ('Invalid rate expression \'{}\'. For help see {}'
.format(val, '{}#RateExpressions'.format(AWS_RATE_HELPER)))
raise parser.error(err)
raise parser.error('Invalid expression \'{}\'. For help '
'see {}'.format(val, AWS_RATE_HELPER))
schedule_help = (
'The interval, defined using a \'rate\' expression, at which this function should '
'execute. Examples of acceptable input are: \'rate(1 hour)\', \'rate(2 days)\', and '
'\'rate(20 minutes)\'. For more information, see: {}'
).format(AWS_RATE_HELPER)
parser.add_argument(
'-s',
'--schedule-expression',
required=True,
help=schedule_help,
type=_validator
)
def add_clusters_arg(parser, required=False):
"""Add ability to select 0 or more clusters to act against"""
kwargs = {
'choices': CLUSTERS,
'help': (
'One or more clusters to target. '
'If omitted, this action will be performed against all clusters.'
) if not required else 'One or more clusters to target',
'nargs': '+',
'action': UniqueSetAction,
'required': required
}
if not required:
kwargs['default'] = CLUSTERS
parser.add_argument(
'-c',
'--clusters',
**kwargs
)
def _set_parser_epilog(parser, epilog):
"""Set the epilog on the given parser. This will typically be an 'Example' block"""
parser.epilog = textwrap.dedent(epilog) if epilog else None
def _generate_subparser(parser, name, description=None, subcommand=False):
"""Helper function to return a subparser with the given options"""
subparser = parser.add_parser(
name,
description=description,
formatter_class=RawDescriptionHelpFormatter
)
if subcommand:
subparser.set_defaults(subcommand=name)
else:
subparser.set_defaults(command=name)
return subparser
def _setup_output_subparser(subparser):
"""Add the output subparser: manage.py output SERVICE"""
outputs = sorted(StreamAlertOutput.get_all_outputs().keys())
# Output parser arguments
subparser.add_argument(
'service',
choices=outputs,
metavar='SERVICE',
help='Create a new StreamAlert output for one of the available services: {}'.format(
', '.join(outputs)
)
)
def _setup_app_subparser(subparser):
"""Add the app integration subparser: manage.py app [subcommand] [options]"""
app_subparsers = subparser.add_subparsers()
_setup_app_list_subparser(app_subparsers)
_setup_app_new_subparser(app_subparsers)
_setup_app_update_auth_subparser(app_subparsers)
def _setup_app_list_subparser(subparsers):
"""Add the app list subparser: manage.py app list"""
_generate_subparser(
subparsers,
'list',
description='List all configured app functions, grouped by cluster',
subcommand=True
)
def _setup_app_new_subparser(subparsers):
"""Add the app new subparser: manage.py app new [options]"""
app_new_parser = _generate_subparser(
subparsers,
'new',
description='Create a new StreamAlert app to poll logs from various services',
subcommand=True
)
_set_parser_epilog(
app_new_parser,
epilog=(
'''\
Example:
manage.py app new \\
duo_auth \\
--cluster prod \\
--name duo_prod_collector \\
--schedule-expression 'rate(2 hours)' \\
--timeout 60 \\
--memory 256
'''
)
)
_add_default_app_args(app_new_parser)
app_types = sorted(StreamAlertApp.get_all_apps())
# App type options
app_new_parser.add_argument(
'type',
choices=app_types,
metavar='APP_TYPE',
help='Type of app being configured: {}'.format(', '.join(app_types))
)
# Function schedule expression (rate) arg
add_schedule_expression_arg(app_new_parser)
# Function timeout arg
add_timeout_arg(app_new_parser)
# Function memory arg
add_memory_arg(app_new_parser)
def _setup_app_update_auth_subparser(subparsers):
"""Add the app update-auth subparser: manage.py app update-auth [options]"""
app_update_parser = _generate_subparser(
subparsers,
'update-auth',
description='Update the authentication information for an existing app',
subcommand=True
)
_set_parser_epilog(
app_update_parser,
epilog=(
'''\
Example:
manage.py app update-auth \\
--cluster prod \\
--name duo_prod_collector
'''
)
)
_add_default_app_args(app_update_parser)
def _add_default_app_args(app_parser):
"""Add the default arguments to the app integration parsers"""
# App integration cluster options
app_parser.add_argument(
'-c',
'--cluster',
choices=CLUSTERS,
required=True,
help='Cluster to perform this action against'
)
# Validate the name being used to make sure it does not contain specific characters
def _validate_name(val):
"""Validate acceptable inputs for the name of the function"""
acceptable_chars = ''.join([string.digits, string.letters, '_-'])
if not set(str(val)).issubset(acceptable_chars):
raise app_parser.error('Name must contain only letters, numbers, '
'hyphens, or underscores.')
return val
# App integration name to be used for this instance that must be unique per cluster
app_parser.add_argument(
'-n',
'--name',
dest='app_name',
required=True,
help='Unique name for this app',
type=_validate_name
)
def _setup_custom_metrics_subparser(subparser):
"""Add the metrics subparser: manage.py custom-metrics [options]"""
_set_parser_epilog(
subparser,
epilog=(
'''\
Example:
manage.py custom-metrics --enable --functions rule
'''
)
)
available_metrics = metrics.MetricLogger.get_available_metrics()
available_functions = [func for func, value in available_metrics.iteritems() if value]
# allow the user to select 1 or more functions to enable metrics for
subparser.add_argument(
'-f',
'--functions',
choices=available_functions,
metavar='FUNCTION',
help='One or more of the following functions for which to enable metrics: {}'.format(
', '.join(available_functions)
),
nargs='+',
required=True
)
# get the metric toggle value
toggle_group = subparser.add_mutually_exclusive_group(required=True)
toggle_group.add_argument(
'-e',
'--enable',
dest='enable_custom_metrics',
help='Enable custom CloudWatch metrics',
action='store_true'
)
toggle_group.add_argument(
'-d',
'--disable',
dest='enable_custom_metrics',
help='Disable custom CloudWatch metrics',
action='store_false'
)
# Add the option to specify cluster(s)
add_clusters_arg(subparser)
def _add_default_metric_alarms_args(alarm_parser, clustered=False):
"""Add the default arguments to the metric alarm parsers"""
# Name for this alarm
def _alarm_name_validator(val):
if not 1 <= len(val) <= 255:
raise alarm_parser.error('alarm name length must be between 1 and 255')
return val
alarm_parser.add_argument(
'alarm_name',
help='Name for the alarm. Each alarm name must be unique within the AWS account.',
type=_alarm_name_validator
)
# get the available metrics to be used
available_metrics = metrics.MetricLogger.get_available_metrics()
if clustered:
available_functions = [
func for func, value in available_metrics.iteritems()
if func in CLUSTERED_FUNCTIONS and value
]
else:
available_functions = [func for func, value in available_metrics.iteritems() if value]
all_metrics = [metric for func in available_functions for metric in available_metrics[func]]
# add metrics for user to pick from. Will be mapped to 'metric_name' in terraform
alarm_parser.add_argument(
'-m',
'--metric',
choices=all_metrics,
dest='metric_name',
metavar='METRIC_NAME',
help=(
'One of the following predefined metrics to assign this alarm to for a '
'given function: {}'
).format(', '.join(sorted(all_metrics))),
required=True
)
# Get the function to apply this alarm to
alarm_parser.add_argument(
'-f',
'--function',
metavar='FUNCTION',
choices=available_functions,
help=(
'One of the following Lambda functions to which to apply this alarm: {}'
).format(', '.join(sorted(available_functions))),
required=True
)
operators = sorted([
'GreaterThanOrEqualToThreshold', 'GreaterThanThreshold', 'LessThanThreshold',
'LessThanOrEqualToThreshold'
])
# get the comparison type for this metric
alarm_parser.add_argument(
'-co',
'--comparison-operator',
metavar='OPERATOR',
choices=operators,
help=(
'One of the following comparison operator to use for this metric: {}'
).format(', '.join(operators)),
required=True
)
# get the evaluation period for this alarm
def _alarm_eval_periods_validator(val):
error = 'evaluation periods must be an integer greater than 0'
try:
period = int(val)
except ValueError:
raise alarm_parser.error(error)
if period <= 0:
raise alarm_parser.error(error)
return period
alarm_parser.add_argument(
'-e',
'--evaluation-periods',
help=(
'The number of periods over which data is compared to the specified threshold. '
'The minimum value for this is 1. See the \'Other Constraints\' section below for '
'more information'
),
required=True,
type=_alarm_eval_periods_validator
)
# get the period for this alarm
def _alarm_period_validator(val):
error = 'period must be an integer in multiples of 60'
try:
period = int(val)
except ValueError:
raise alarm_parser.error(error)
if period <= 0 or period % 60 != 0:
raise alarm_parser.error(error)
return period
alarm_parser.add_argument(
'-p',
'--period',
help=(
'The period, in seconds, over which the specified statistic is applied. '
'Valid values are any multiple of 60. See the \'Other Constraints\' section below for '
'more information'
),
required=True,
type=_alarm_period_validator
)
# get the threshold for this alarm
alarm_parser.add_argument(
'-t',
'--threshold',
help=(
'The value against which the specified statistic is compared. '
'This value should be a double/float.'
),
required=True,
type=float
)
# all other optional flags
# get the optional alarm description
def _alarm_description_validator(val):
if len(val) > 1024:
raise alarm_parser.error('alarm description length must be less than 1024')
return val
alarm_parser.add_argument(
'-d',
'--alarm-description',
help='A description for the alarm',
type=_alarm_description_validator,
default=''
)
statistics = sorted(['SampleCount', 'Average', 'Sum', 'Minimum', 'Maximum'])
alarm_parser.add_argument(
'-s',
'--statistic',
metavar='STATISTIC',
choices=statistics,
help=(
'One of the following statistics to use for the metric associated with the alarm: {}'
).format(', '.join(statistics)),
default='Sum'
)
def _setup_cluster_metric_alarm_subparser(subparser):
"""Add the create-cluster-alarm subparser: manage.py create-cluster-alarm [options]"""
_set_parser_epilog(
subparser,
epilog=(
'''\
Other Constraints:
The product of the value for period multiplied by the value for evaluation
periods cannot exceed 86,400. 86,400 is the number of seconds in one day and
an alarm's total current evaluation period can be no longer than one day.
Example:
manage.py create-cluster-alarm FailedParsesAlarm \\
--metric FailedParses \\
--comparison-operator GreaterThanOrEqualToThreshold \\
--evaluation-periods 1 \\
--period 300 \\
--threshold 1.0 \\
--clusters prod \\
--statistic Sum \\
--alarm-description 'Alarm for any failed parses that occur \
within a 5 minute period in the prod cluster'
Resources:
AWS: https://docs.aws.amazon.com/AmazonCloudWatch/\
latest/APIReference/API_PutMetricAlarm.html
Terraform: https://www.terraform.io/docs/providers/aws/r/\
cloudwatch_metric_alarm.html
'''
)
)
_add_default_metric_alarms_args(subparser, clustered=True)
# Add the option to specify cluster(s)
add_clusters_arg(subparser, required=True)
def _setup_metric_alarm_subparser(subparser):
"""Add the create-alarm subparser: manage.py create-alarm [options]"""
_set_parser_epilog(
subparser,
epilog=(
'''\
Other Constraints:
The product of the value for period multiplied by the value for evaluation
periods cannot exceed 86,400. 86,400 is the number of seconds in one day and
an alarm's total current evaluation period can be no longer than one day.
Example:
manage.py create-alarm FailedParsesAlarm \\
--metric FailedParses \\
--comparison-operator GreaterThanOrEqualToThreshold \\
--evaluation-periods 1 \\
--period 300 \\
--threshold 1.0 \\
--statistic Sum \\
--alarm-description 'Global alarm for any failed parses that occur \
within a 5 minute period in the classifier'
Resources:
AWS: https://docs.aws.amazon.com/AmazonCloudWatch/\
latest/APIReference/API_PutMetricAlarm.html
Terraform: https://www.terraform.io/docs/providers/aws/r/\
cloudwatch_metric_alarm.html
'''
)
)
_add_default_metric_alarms_args(subparser)
def _setup_deploy_subparser(subparser):
"""Add the deploy subparser: manage.py deploy [options]"""
_set_parser_epilog(
subparser,
epilog=(
'''\
Example:
manage.py deploy --function rule alert
'''
)
)
# Flag to manually bypass rule staging for new rules upon deploy
# This only has an effect if rule staging is enabled
subparser.add_argument(
'--skip-rule-staging',
action='store_true',
help='Skip staging of new rules so they go directly into production'
)
# flag to manually demote specific rules to staging during deploy
subparser.add_argument(
'--stage-rules',
action=MutuallyExclusiveStagingAction,
default=set(),
help='Stage the rules provided in a space-separated list',
nargs='+'
)
# flag to manually bypass rule staging for specific rules during deploy
subparser.add_argument(
'--unstage-rules',
action=MutuallyExclusiveStagingAction,
default=set(),
help='Unstage the rules provided in a space-separated list',
nargs='+'
)
_add_default_lambda_args(subparser)
def _setup_rollback_subparser(subparser):
"""Add the rollback subparser: manage.py rollback [options]"""
_set_parser_epilog(
subparser,
epilog=(
'''\
Example:
manage.py rollback --function rule
'''
)
)
_add_default_lambda_args(subparser)
def _setup_test_subparser(subparser):
"""Add the test subparser: manage.py test"""
test_subparsers = subparser.add_subparsers()
_setup_test_classifier_subparser(test_subparsers)
_setup_test_rules_subparser(test_subparsers)
_setup_test_live_subparser(test_subparsers)
def _setup_test_classifier_subparser(subparsers):
"""Add the test validation subparser: manage.py test classifier [options]"""
test_validate_parser = _generate_subparser(
subparsers,
'classifier',
description='Validate defined log schemas using integration test files',
subcommand=True
)
_add_default_test_args(test_validate_parser)
def _setup_test_rules_subparser(subparsers):
"""Add the test rules subparser: manage.py test rules [options]"""
test_rules_parser = _generate_subparser(
subparsers,
'rules',
description='Test rules using integration test files',
subcommand=True
)
# Flag to run additional stats during testing
test_rules_parser.add_argument(
'-s',
'--stats',
action='store_true',
help='Enable outputing of statistical information on rules that run'
)
# Validate the provided repitition value
def _validate_repitition(val):
"""Make sure the input is between 1 and 1000"""
err = ('Invalid repitition value [{}]. Must be an integer between 1 '
'and 1000').format(val)
try:
count = int(val)
except TypeError:
raise test_rules_parser.error(err)
if not 1 <= count <= 1000:
raise test_rules_parser.error(err)
return count
# flag to run these tests a given number of times
test_rules_parser.add_argument(
'-n',
'--repeat',
default=1,
type=_validate_repitition,
help='Number of times to repeat the tests, to be used as a form performance testing'
)
_add_default_test_args(test_rules_parser)
def _setup_test_live_subparser(subparsers):
"""Add the test live subparser: manage.py test live [options]"""
test_live_parser = _generate_subparser(
subparsers,
'live',
description='Run end-to-end tests that will attempt to send alerts to each rule\'s outputs',
subcommand=True
)
_add_default_test_args(test_live_parser)
def _add_default_test_args(test_parser):
"""Add the default arguments to the test parsers"""
test_filter_group = test_parser.add_mutually_exclusive_group(required=False)
# add the optional ability to test against a rule/set of rules
test_filter_group.add_argument(
'-f',
'--test-files',
dest='files',
metavar='FILENAMES',
nargs='+',
help='One or more file to test, separated by spaces',
action=UniqueSetAction,
default=set()
)
# add the optional ability to test against a rule/set of rules
test_filter_group.add_argument(
'-r',
'--test-rules',
dest='rules',
nargs='+',
help='One or more rule to test, separated by spaces',
action=UniqueSetAction,
default=set()
)
# add the optional ability to change the test files directory
test_parser.add_argument(
'-d',
'--files-dir',
help='Path to directory containing test files',
default=DEFAULT_TEST_FILES_DIRECTORY
)
# Add the optional ability to log verbosely or use quite logging for tests
verbose_group = test_parser.add_mutually_exclusive_group(required=False)
verbose_group.add_argument(
'-v',
'--verbose',
action='store_true',
help='Output additional information during testing'
)
verbose_group.add_argument(
'-q',
'--quiet',
action='store_true',
help='Suppress output for passing tests, only logging if there is a failure'
)
def _add_default_lambda_args(lambda_parser):
"""Add the default arguments to the deploy and rollback parsers"""
functions = sorted([
'alert', 'alert_merger', 'apps', 'athena', 'classifier',
'rule', 'rule_promo', 'threat_intel_downloader'
])
# require the name of the function being deployed/rolled back
lambda_parser.add_argument(
'-f', '--function',
choices=functions + ['all'],
metavar='FUNCTION',
help=(
'One or more of the following functions to perform this action against: {}. '
'Use \'all\' to act against all functions.'
).format(', '.join(functions)),
nargs='+',
action=UniqueSetAction,
required=True
)
# Add the option to specify cluster(s)
add_clusters_arg(lambda_parser)
def _setup_init_subparser(subparser):
"""Add init subparser: manage.py init [options]"""
subparser.add_argument(
'-b',
'--backend',
action='store_true',
help=(
'Initialize the Terraform backend (S3). '
'Useful for refreshing a pre-existing deployment'
)
)
def _add_default_tf_args(tf_parser):
"""Add the default terraform parser options"""
tf_parser.add_argument(
'-t',
'--target',
metavar='TARGET',
help=(
'One or more Terraform module name to target. Use `list-targets` for a list '
'of available targets'
),
action=UniqueSetAction,
default=set(),
nargs='+'
)
# Add the option to specify cluster(s)
add_clusters_arg(tf_parser)
def _setup_build_subparser(subparser):
"""Add build subparser: manage.py build [options]"""
_set_parser_epilog(
subparser,
epilog=(
'''\
Example:
manage.py build --target alert_processor_lambda
'''
)
)
_add_default_tf_args(subparser)
def _setup_destroy_subparser(subparser):
"""Add destroy subparser: manage.py destroy [options]"""
_set_parser_epilog(
subparser,
epilog=(
'''\
Example:
manage.py destroy --target aws_s3_bucket.streamalerts
'''
)
)
_add_default_tf_args(subparser)
def _setup_kinesis_subparser(subparser):
"""Add kinesis subparser: manage.py kinesis [options]"""
_set_parser_epilog(
subparser,
epilog=(
'''\
Example:
manage.py kinesis disable-events --clusters corp prod
'''
)
)
actions = ['disable-events', 'enable-events']
subparser.add_argument(
'action',
metavar='ACTION',
choices=actions,
help='One of the following actions to be performed: {}'.format(', '.join(actions))
)
# Add the option to specify cluster(s)
add_clusters_arg(subparser)
subparser.add_argument(
'-s',
'--skip-terraform',
action='store_true',
help='Only update the config options and do not run Terraform'
)
def _setup_configure_subparser(subparser):
"""Add configure subparser: manage.py configure key value"""
_set_parser_epilog(
subparser,
epilog=(
'''\
Example:
manage.py configure prefix orgname
'''
)
)
subparser.add_argument(
'key',
choices=['prefix', 'aws_account_id'],
help='Value of key being configured'
)
subparser.add_argument(
'value',
help='Value to assign to key being configured'
)
def _setup_athena_subparser(subparser):
"""Add athena subparser: manage.py athena [subcommand]"""
athena_subparsers = subparser.add_subparsers()
_setup_athena_create_table_subparser(athena_subparsers)
_setup_athena_rebuild_subparser(athena_subparsers)
_setup_athena_drop_all_subparser(athena_subparsers)
def _setup_athena_create_table_subparser(subparsers):
"""Add the athena create-table subparser: manage.py athena create-table [options]"""
athena_create_table_parser = _generate_subparser(
subparsers,
'create-table',
description='Create an Athena table',
subcommand=True
)
_set_parser_epilog(
athena_create_table_parser,
epilog=(
'''\
Examples:
manage.py athena create-table \\
--bucket s3.bucket.name \\
--table-name my_athena_table
'''
)