forked from airbnb/streamalert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanage.py
executable file
·1690 lines (1249 loc) · 57.6 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, RawTextHelpFormatter, SUPPRESS as ARGPARSE_SUPPRESS
import os
import string
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 metrics
from stream_alert_cli.logger import LOGGER_CLI
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)
class NormalizeFunctionAction(UniqueSetAction):
"""Subclass of argparse.Action -> UniqueSetAction that will return a unique set of
normalized lambda function names.
"""
def __call__(self, parser, namespace, values, option_string=None):
super(NormalizeFunctionAction, self).__call__(parser, namespace, values, option_string)
values = getattr(namespace, self.dest)
normalized_map = {
'rule': metrics.RULE_PROCESSOR_NAME,
'alert': metrics.ALERT_PROCESSOR_NAME,
'athena': metrics.ATHENA_PARTITION_REFRESH_NAME
}
for func, normalize_func in normalized_map.iteritems():
if func in values:
values.remove(func)
values.add(normalize_func)
setattr(namespace, self.dest, values)
def _generate_subparser(parser, name, usage, description, subcommand=False):
"""Helper function to return a subparser with the given options"""
subparser = parser.add_parser(
name,
description=description,
formatter_class=RawTextHelpFormatter,
help=ARGPARSE_SUPPRESS,
usage=usage,
)
# allow verbose output with the --debug option
subparser.add_argument('--debug', action='store_true', help=ARGPARSE_SUPPRESS)
if subcommand:
subparser.set_defaults(subcommand=name)
else:
subparser.set_defaults(command=name)
return subparser
def _add_output_subparser(subparsers):
"""Add the output subparser: manage.py output [subcommand] [options]"""
usage = 'manage.py output [subcommand] [options]'
outputs = sorted(StreamAlertOutput.get_all_outputs().keys())
description = """
StreamAlertCLI v{}
Define new StreamAlert outputs to send alerts to
Available Subcommands:
manage.py output new [options] Create a new StreamAlert output
Examples:
manage.py output new --service aws-s3
manage.py output new --service pagerduty
manage.py output new --service slack
The following outputs are supported:
{}
""".format(version, '\n'.join('{:>4}{}'.format('', output) for output in outputs))
output_parser = _generate_subparser(subparsers, 'output', usage, description)
# Output parser arguments
# The CLI library handles all configuration logic
output_parser.add_argument('subcommand', choices=['new'], help=ARGPARSE_SUPPRESS)
# Output service options
output_parser.add_argument(
'--service',
choices=outputs,
required=True,
help=ARGPARSE_SUPPRESS)
def _add_live_test_subparser(subparsers):
"""Add the live-test subparser: manage.py live-test [options]"""
usage = 'manage.py live-test [options]'
description = """
StreamAlertCLI v{}
Run end-to-end tests that will attempt to send alerts
Required Arguments:
--cluster The cluster name to use for live testing
Optional Arguments:
--rules Name of rules to test, separated by spaces
--debug Enable debug logger output
Examples:
manage.py live-test --cluster prod
manage.py live-test --rules
""".format(version)
live_test_parser = _generate_subparser(subparsers, 'live-test', usage, description)
# add clusters for user to pick from
live_test_parser.add_argument(
'-c', '--cluster', choices=CLUSTERS, help=ARGPARSE_SUPPRESS, required=True)
# add the optional ability to test against a rule/set of rules
live_test_parser.add_argument(
'-r', '--rules', nargs='+', help=ARGPARSE_SUPPRESS, action=UniqueSetAction, default=set())
def _add_validate_schema_subparser(subparsers):
"""Add the validate-schemas subparser: manage.py validate-schemas [options]"""
usage = 'manage.py validate-schemas [options]'
description = """
StreamAlertCLI v{}
Run validation of schemas in logs.json using configured integration test files. Validation
does not actually run the rules engine on test events.
Available Options:
--test-files Name(s) of test files to validate, separated by spaces (not full path).
These files should be located within 'tests/integration/rules/'. The
contents should be json, in the form of:
`{{"records": [ <records as maps> ]}}`.
See the sample test files in 'tests/integration/rules/' for an example.
This flag supports the full file name, with extension, or the base file
name, without extension (ie: test_file_name.json or test_file_name)
Optional Arguments:
--debug Enable debug logger output
Examples:
manage.py validate-schemas --test-files <test_file_name_01.json> <test_file_name_02.json>
""".format(version)
schema_validation_parser = _generate_subparser(
subparsers, 'validate-schemas', usage, description)
# add the optional ability to test against specific files
schema_validation_parser.add_argument(
'-f',
'--test-files',
dest='files',
nargs='+',
help=ARGPARSE_SUPPRESS,
action=UniqueSetAction,
default=set())
def _add_app_subparser(subparsers):
"""Add the app integration subparser: manage.py app [subcommand] [options]"""
usage = 'manage.py app [subcommand] [options]'
description = """
StreamAlertCLI v{}
Create, list, or update a StreamAlert app integration function to poll logs from various services
Available Subcommands:
manage.py app new Configure a new app integration for collecting logs
manage.py app update-auth Update the authentication information for an
existing app integration
""".format(version)
app_parser = _generate_subparser(subparsers, 'app', usage, description)
app_subparsers = app_parser.add_subparsers()
_add_app_list_subparser(app_subparsers)
_add_app_new_subparser(
app_subparsers,
sorted(StreamAlertApp.get_all_apps()),
CLUSTERS
)
_add_app_update_auth_subparser(app_subparsers, CLUSTERS)
def _add_app_list_subparser(subparsers):
"""Add the app list subparser: manage.py app list"""
usage = 'manage.py app list'
description = """
StreamAlertCLI v{}
List all configured StreamAlert app integration functions, grouped by cluseter
Command:
manage.py app list List all configured app functions, grouped by cluster
Optional Arguments:
--debug Enable debug logger output
""".format(version)
_generate_subparser(subparsers, 'list', usage, description, True)
def _add_app_new_subparser(subparsers, types, clusters):
"""Add the app new subparser: manage.py app new [options]"""
usage = 'manage.py app new [options]'
types_block = '\n'.join('{:>26}{}'.format('', app_type) for app_type in types)
cluster_choices_block = '\n'.join('{:>28}{}'.format('', cluster) for cluster in clusters)
description = """
StreamAlertCLI v{}
Create a new StreamAlert app integration function to poll logs from various services
Command:
manage.py app new [options] Configure a new app for collecting logs
Required Arguments:
--type Type of app integration function being configured. Choices are:
{}
--cluster Applicable cluster this function should be configured against.
Choices are:
{}
--name Unique name to be assigned to the App. This is useful when
configuring multiple accounts per service.
--timeout The AWS Lambda function timeout value, in seconds. This should
be an integer between 10 and 300.
--memory The AWS Lambda function max memory value, in megabytes. This should
be an integer between 128 and 1536.
--interval The interval, defined using a 'rate' expression, at
which this app integration function should execute. Examples of
acceptable input are:
'rate(1 hour)' # Every hour (note the singular 'hour')
'rate(2 days)' # Every 2 days
'rate(20 minutes)' # Every 20 minutes
See the link in the Resources section below for more information.
Optional Arguments:
--debug Enable debug logger output
Examples:
manage.py app new \\
--type duo_auth \\
--cluster prod \\
--name duo_prod_collector \\
--interval 'rate(2 hours)' \\
--timeout 60 \\
--memory 256
Resources:
AWS: {}
""".format(version, types_block, cluster_choices_block, AWS_RATE_HELPER)
app_new_parser = _generate_subparser(subparsers, 'new', usage, description, True)
_add_default_app_args(app_new_parser, clusters)
# App type options
app_new_parser.add_argument('--type', choices=types, required=True, help=ARGPARSE_SUPPRESS)
# Validate the rate at which this should run
def _validate_scheduled_interval(val):
"""Validate acceptable inputs for the schedule expression
These follow the format 'rate(5 minutes)'
"""
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 app_new_parser.error(err)
raise app_new_parser.error('Invalid expression \'{}\'. For help '
'see {}'.format(val, AWS_RATE_HELPER))
# App integration schedule expression (rate)
app_new_parser.add_argument(
'--interval', dest='schedule_expression',
required=True, help=ARGPARSE_SUPPRESS, type=_validate_scheduled_interval)
# Validate the timeout value to make sure it is between 10 and 300
def _validate_timeout(val):
"""Validate acceptable inputs for the timeout of the function"""
error = 'The \'timeout\' value must be an integer between 10 and 300'
try:
timeout = int(val)
except ValueError:
raise app_new_parser.error(error)
if not 10 <= timeout <= 300:
raise app_new_parser.error(error)
return timeout
# App integration function timeout
app_new_parser.add_argument(
'--timeout', required=True, help=ARGPARSE_SUPPRESS, type=_validate_timeout)
# Validate the memory value to make sure it is between 128 and 1536
def _validate_memory(val):
"""Validate acceptable inputs for the memory of the function"""
error = 'The \'memory\' value must be an integer between 128 and 1536'
try:
memory = int(val)
except ValueError:
raise app_new_parser.error(error)
if not 128 <= memory <= 1536:
raise app_new_parser.error(error)
return memory
# App integration function max memory
app_new_parser.add_argument(
'--memory', required=True, help=ARGPARSE_SUPPRESS, type=_validate_memory)
def _add_app_update_auth_subparser(subparsers, clusters):
"""Add the app update-auth subparser: manage.py app update-auth [options]"""
usage = 'manage.py app update-auth [options]'
cluster_choices_block = '\n'.join('{:>28}{}'.format('', cluster) for cluster in clusters)
description = """
StreamAlertCLI v{}
Update a StreamAlert app integration function's authentication information in Parameter Store
Command:
manage.py app update-auth [options] Update the authentication information for an
existing app integration within Parameter Store
Required Arguments:
--cluster Applicable cluster this function should be configured against.
Choices are:
{}
--name Unique name to be assigned to the App. This is useful when
configuring multiple accounts per service.
Optional Arguments:
--debug Enable debug logger output
Examples:
manage.py app update-auth \\
--cluster prod \\
--name duo_prod_collector
""".format(version, cluster_choices_block)
app_update_parser = _generate_subparser(subparsers, 'update-auth', usage, description, True)
_add_default_app_args(app_update_parser, clusters)
def _add_default_app_args(app_parser, clusters):
"""Add the default arguments to the app integration parsers"""
# App integration cluster options
app_parser.add_argument('--cluster', choices=clusters, required=True, help=ARGPARSE_SUPPRESS)
# 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(
'--name', dest='app_name', required=True, help=ARGPARSE_SUPPRESS, type=_validate_name)
def _add_metrics_subparser(subparsers):
"""Add the metrics subparser: manage.py metrics [options]"""
usage = 'manage.py metrics [options]'
cluster_choices_block = '\n'.join('{:>28}{}'.format('', cluster) for cluster in CLUSTERS)
description = """
StreamAlertCLI v{}
Enable or disable metrics for all lambda functions. This toggles the creation of metric filters.
Available Options:
-e/--enable Enable CloudWatch metrics through logging and metric filters
-d/--disable Disable CloudWatch metrics through logging and metric filters
-f/--functions Space delimited list of functions to enable metrics for
Choices are:
rule
alert (not implemented)
athena (not implemented)
--debug Enable debug logger output
Optional Arguemnts:
-c/--clusters Space delimited list of clusters to enable metrics for. If
omitted, this will enable metrics for all clusters. Choices are:
{}
Examples:
manage.py metrics --enable --functions rule
""".format(version, cluster_choices_block)
metrics_parser = _generate_subparser(subparsers, 'metrics', usage, description)
# allow the user to select 1 or more functions to enable metrics for
metrics_parser.add_argument(
'-f',
'--functions',
choices=['rule', 'alert', 'athena'],
help=ARGPARSE_SUPPRESS,
nargs='+',
action=NormalizeFunctionAction,
required=True)
# get the metric toggle value
toggle_group = metrics_parser.add_mutually_exclusive_group(required=True)
toggle_group.add_argument('-e', '--enable', dest='enable_metrics', action='store_true')
toggle_group.add_argument('-d', '--disable', dest='enable_metrics', action='store_false')
# allow the user to select 0 or more clusters to enable metrics for
metrics_parser.add_argument(
'-c',
'--clusters',
choices=CLUSTERS,
help=ARGPARSE_SUPPRESS,
nargs='+',
action=UniqueSetAction,
default=CLUSTERS)
def _add_metric_alarm_subparser(subparsers):
"""Add the create-alarm subparser: manage.py create-alarm [options]"""
usage = 'manage.py create-alarm [options]'
# get the available metrics to be used
available_metrics = metrics.MetricLogger.get_available_metrics()
all_metrics = [metric for func in available_metrics for metric in available_metrics[func]]
metric_choices_block = '\n'.join('{:>35}{}'.format('', metric) for metric in all_metrics)
cluster_choices_block = '\n'.join('{:>37}{}'.format('', cluster) for cluster in CLUSTERS)
description = """
StreamAlertCLI v{}
Add a CloudWatch alarm for predefined metrics. These are save in the config and
Terraform is used to create the alarms.
Required Arguments:
-m/--metric The predefined metric to assign this alarm to. Choices are:
{}
-mt/--metric-target The target of this metric alarm, meaning either the cluster metric
or the aggrea metric. Choices are:
cluster
aggregate
all
-co/--comparison-operator Comparison operator to use for this metric. Choices are:
GreaterThanOrEqualToThreshold
GreaterThanThreshold
LessThanThreshold
LessThanOrEqualToThreshold
-an/--alarm-name The name for the alarm. This name must be unique within the AWS
account
-ep/--evaluation-periods The number of periods over which data is compared to the specified
threshold. The minimum value for this is 1. Also see the 'Other
Constraints' section below
-p/--period The period, in seconds, over which the specified statistic is
applied. Valid values are any multiple of 60. Also see the
'Other Constraints' section below
-t/--threshold The value against which the specified statistic is compared. This
value should be a double.
Optional Arguments:
-ad/--alarm-description The description for the alarm
-c/--clusters Space delimited list of clusters to apply this metric to. This is
ignored if the --metric-target of 'aggregate' is used.
Choices are:
{}
-s/--statistic The statistic for the metric associated with the alarm.
Choices are:
SampleCount
Average
Sum
Minimum
Maximum
--debug Enable debug logger output
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.
Examples:
manage.py create-alarm \\
--metric FailedParses \\
--metric-target cluster \\
--comparison-operator GreaterThanOrEqualToThreshold \\
--alarm-name FailedParsesAlarm \\
--evaluation-periods 1 \\
--period 300 \\
--threshold 1.0 \\
--alarm-description 'Alarm for any failed parses that occur within a 5 minute period in the prod cluster' \\
--clusters prod \\
--statistic Sum
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
""".format(version, metric_choices_block, cluster_choices_block)
metric_alarm_parser = _generate_subparser(subparsers, 'create-alarm', usage, description)
# add all the required parameters
# add metrics for user to pick from. Will be mapped to 'metric_name' in terraform
metric_alarm_parser.add_argument(
'-m',
'--metric',
choices=all_metrics,
dest='metric_name',
help=ARGPARSE_SUPPRESS,
required=True)
# check to see what the user wants to apply this metric to (cluster, aggregate, or both)
metric_alarm_parser.add_argument(
'-mt',
'--metric-target',
choices=['cluster', 'aggregate', 'all'],
help=ARGPARSE_SUPPRESS,
required=True)
# get the comparison type for this metric
metric_alarm_parser.add_argument(
'-co',
'--comparison-operator',
choices=[
'GreaterThanOrEqualToThreshold', 'GreaterThanThreshold', 'LessThanThreshold',
'LessThanOrEqualToThreshold'
],
help=ARGPARSE_SUPPRESS,
required=True)
# get the name of the alarm
def _alarm_name_validator(val):
if not 1 <= len(val) <= 255:
raise metric_alarm_parser.error('alarm name length must be between 1 and 255')
return val
metric_alarm_parser.add_argument(
'-an', '--alarm-name', help=ARGPARSE_SUPPRESS, required=True, type=_alarm_name_validator)
# 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 metric_alarm_parser.error(error)
if period <= 0:
raise metric_alarm_parser.error(error)
return period
metric_alarm_parser.add_argument(
'-ep',
'--evaluation-periods',
help=ARGPARSE_SUPPRESS,
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 metric_alarm_parser.error(error)
if period <= 0 or period % 60 != 0:
raise metric_alarm_parser.error(error)
return period
metric_alarm_parser.add_argument(
'-p', '--period', help=ARGPARSE_SUPPRESS, required=True, type=_alarm_period_validator)
# get the threshold for this alarm
metric_alarm_parser.add_argument(
'-t', '--threshold', help=ARGPARSE_SUPPRESS, required=True, type=float)
# all other optional flags
# get the optional alarm description
def _alarm_description_validator(val):
if len(val) > 1024:
raise metric_alarm_parser.error('alarm description length must be less than 1024')
return val
metric_alarm_parser.add_argument(
'-ad',
'--alarm-description',
help=ARGPARSE_SUPPRESS,
type=_alarm_description_validator,
default='')
# allow the user to select 0 or more clusters to apply this alarm to
metric_alarm_parser.add_argument(
'-c',
'--clusters',
choices=CLUSTERS,
help=ARGPARSE_SUPPRESS,
nargs='+',
action=UniqueSetAction,
default=set())
### Commenting out the below until we can support 'extended-statistic' metrics
### alongside 'statistic' metrics. Currently only 'statistic' are supported
# # get the extended statistic or statistic value
# statistic_group = metric_alarm_parser.add_mutually_exclusive_group()
# def _extended_stat_validator(val):
# if not re.search(r'p(\d{1,2}(\.\d{0,2})?|100)$', val):
# raise metric_alarm_parser.error('extended statistic values must start with \'p\' '
# 'and be followed by a percentage value (ie: p0.0, '
# 'p10, p55.5, p100)')
# return val
#
# statistic_group.add_argument(
# '-es', '--extended-statistic',
# help=ARGPARSE_SUPPRESS,
# type=_extended_stat_validator
# )
#
# statistic_group.add_argument(
# '-s', '--statistic',
# choices=['SampleCount', 'Average', 'Sum', 'Minimum', 'Maximum'],
# help=ARGPARSE_SUPPRESS
# )
metric_alarm_parser.add_argument(
'-s',
'--statistic',
choices=['SampleCount', 'Average', 'Sum', 'Minimum', 'Maximum'],
help=ARGPARSE_SUPPRESS,
default='')
def _add_lambda_subparser(subparsers):
"""Add the Lambda subparser: manage.py lambda [subcommand] [options]"""
usage = 'manage.py lambda [subcommand] [options]'
description = """
StreamAlertCLI v{}
Deploy, Rollback, and Test StreamAlert Lambda functions
Available Subcommands:
manage.py lambda deploy Deploy Lambda functions
manage.py lambda rollback Rollback Lambda functions
manage.py lambda test Run rule tests
""".format(version)
lambda_parser = _generate_subparser(subparsers, 'lambda', usage, description)
lambda_subparsers = lambda_parser.add_subparsers()
_add_lambda_deploy_subparser(lambda_subparsers)
_add_lambda_rollback_subparser(lambda_subparsers)
_add_lambda_test_subparser(lambda_subparsers)
def _add_lambda_deploy_subparser(subparsers):
"""Add the lambda deploy subparser: manage.py lambda deploy"""
usage = 'manage.py lambda deploy'
description = """
StreamAlertCLI v{}
Deploy Lambda functions
Command:
manage.py lambda deploy Deploy Lambda functions
Required Arguments:
-p/--processor A list of the Lambda functions to deploy.
Valid options include: rule, alert, athena, apps,
rule_promo, threat_intel_downloader, all,
or any combination of these.
Optional Arguments:
--skip-rule-staging Skip staging of new rules so they go directly into
production.
--stage-rules Stage the rules provided in a space-separated list
--unstage-rules Unstage the rules provided in a space-separated list
--debug Enable debug logger output
Examples:
manage.py lambda deploy --processor rule alert
""".format(version)
lambda_deploy_parser = _generate_subparser(subparsers, 'deploy', usage, description, True)
# Flag to manually bypass rule staging for new rules upon deploy
# This only has an effect if rule staging is enabled
lambda_deploy_parser.add_argument(
'--skip-rule-staging',
action='store_true',
help=ARGPARSE_SUPPRESS
)
# flag to manually demote specific rules to staging during deploy
lambda_deploy_parser.add_argument(
'--stage-rules',
action=MutuallyExclusiveStagingAction,
default=set(),
help=ARGPARSE_SUPPRESS,
nargs='+'
)
# flag to manually bypass rule staging for specific rules during deploy
lambda_deploy_parser.add_argument(
'--unstage-rules',
action=MutuallyExclusiveStagingAction,
default=set(),
help=ARGPARSE_SUPPRESS,
nargs='+'
)
_add_default_lambda_args(lambda_deploy_parser)
def _add_lambda_rollback_subparser(subparsers):
"""Add the lambda rollback subparser: manage.py lambda rollback"""
usage = 'manage.py lambda rollback'
description = """
StreamAlertCLI v{}
Rollback Lambda functions
Command:
manage.py lambda rollback Rollback Lambda functions
Required Arguments:
-p/--processor A list of the Lambda functions to rollback.
Valid options include: rule, alert, athena, apps,
all, or any combination of these.
Optional Arguments:
--debug Enable debug logger output
Examples:
manage.py lambda rollback --processor rule alert
""".format(version)
lambda_rollback_parser = _generate_subparser(subparsers, 'rollback', usage, description, True)
_add_default_lambda_args(lambda_rollback_parser)
def _add_lambda_test_subparser(subparsers):
"""Add the lambda test subparser: manage.py lambda test"""
usage = 'manage.py lambda test'
description = """
StreamAlertCLI v{}
Run rule tests
Command:
manage.py lambda test Run rule tests
Required Arguments:
-p/--processor A list of the Lambda functions to test.
Valid options include: rule, alert, all, or
any combination of these.
-r/--test-rules List of rules to test, separated by spaces.
Cannot be used in conjunction with `--test-files`
-f/--test-files List of files to test, separated by spaces.
Cannot be used in conjunction with `--test-rules`
This flag supports the full file name, with extension,
or the base file name, without extension
(ie: test_file_name.json or test_file_name).
Optional Arguments:
--debug Enable debug logger output
Example:
manage.py lambda test --processor rule --test-rules lateral_movement root_logins
""".format(version)
lambda_test_parser = _generate_subparser(subparsers, 'test', usage, description, True)
# require the name of the processor being tested
lambda_test_parser.add_argument(
'-p',
'--processor',
choices=['alert', 'all', 'rule'],
help=ARGPARSE_SUPPRESS,
nargs='+',
action=UniqueSetAction,
required=True)
# flag to run additional stats during testing
lambda_test_parser.add_argument(
'-s',
'--stats',
action='store_true',
help=ARGPARSE_SUPPRESS
)
# 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 lambda_test_parser.error(err)
if not 1 <= count <= 1000:
raise lambda_test_parser.error(err)
return count
# flag to run these tests a given number of times
lambda_test_parser.add_argument(
'-n',
'--repeat',
default=1,
type=_validate_repitition,
help=ARGPARSE_SUPPRESS
)
test_filter_group = lambda_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',
nargs='+',
help=ARGPARSE_SUPPRESS,
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=ARGPARSE_SUPPRESS,
action=UniqueSetAction,
default=set())
def _add_default_lambda_args(lambda_parser):
"""Add the default arguments to the lambda parsers"""
# require the name of the processor being deployed/rolled back
lambda_parser.add_argument(
'-p', '--processor',
choices=['all', 'alert', 'alert_merger', 'apps', 'athena', 'rule',
'rule_promo', 'threat_intel_downloader'],
help=ARGPARSE_SUPPRESS,
nargs='+',
action=UniqueSetAction,
required=True)
lambda_parser.add_argument(
'--clusters',
help=ARGPARSE_SUPPRESS,
nargs='+')
def _add_terraform_subparser(subparsers):
"""Add Terraform subparser: manage.py terraform [subcommand] [options]"""
usage = 'manage.py terraform [subcommand] [options]'
description = """
StreamAlertCLI v{}
Plan and Apply StreamAlert Infrastructure with Terraform
Available Subcommands:
manage.py terraform init Initialize StreamAlert infrastructure
manage.py terraform init-backend Initialize the Terraform backend
manage.py terraform build [options] Run Terraform on all StreamAlert modules
manage.py terraform clean Remove Terraform files (only use this when destroying all infrastructure)
manage.py terraform destroy [options] Destroy StreamAlert infrastructure
manage.py terraform generate Generate Terraform files from JSON cluster files
manage.py terraform status Show cluster health, and other currently configured infrastructure information
Available Options:
--target The Terraform module name to apply.
Valid options: stream_alert, kinesis, kinesis_events,
cloudtrail, monitoring, and s3_events.