/
cli.py
executable file
·181 lines (152 loc) · 6.8 KB
/
cli.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
from __future__ import absolute_import, division, print_function, unicode_literals
import argparse
import functools
import logging
import boto3
import jsonschema
from c7n_mailer import deploy, utils
from c7n_mailer.azure.azure_queue_processor import MailerAzureQueueProcessor
from c7n_mailer.azure import deploy as azure_deploy
from c7n_mailer.sqs_queue_processor import MailerSqsQueueProcessor
from ruamel import yaml
CONFIG_SCHEMA = {
'type': 'object',
'additionalProperties': False,
'required': ['queue_url'],
'properties': {
'queue_url': {'type': 'string'},
'from_address': {'type': 'string'},
'contact_tags': {'type': 'array', 'items': {'type': 'string'}},
'org_domain': {'type': 'string'},
# Standard Lambda Function Config
'region': {'type': 'string'},
'role': {'type': 'string'},
'runtime': {'type': 'string'},
'memory': {'type': 'integer'},
'timeout': {'type': 'integer'},
'subnets': {'type': 'array', 'items': {'type': 'string'}},
'security_groups': {'type': 'array', 'items': {'type': 'string'}},
'dead_letter_config': {'type': 'object'},
'lambda_name': {'type': 'string'},
'lambda_description': {'type': 'string'},
'lambda_tags': {'type': 'object'},
'lambda_schedule': {'type': 'string'},
# Azure Function Config
'function_name': {'type': 'string'},
'function_servicePlanName': {'type': 'string'},
'function_location': {'type': 'string'},
'function_appInsightsLocation': {'type': 'string'},
'function_schedule': {'type': 'string'},
'function_skuCode': {'type': 'string'},
'function_sku': {'type': 'string'},
# Mailer Infrastructure Config
'cache_engine': {'type': 'string'},
'smtp_server': {'type': 'string'},
'smtp_port': {'type': 'integer'},
'smtp_ssl': {'type': 'boolean'},
'smtp_username': {'type': 'string'},
'smtp_password': {'type': 'string'},
'ldap_email_key': {'type': 'string'},
'ldap_uid_tags': {'type': 'array', 'items': {'type': 'string'}},
'debug': {'type': 'boolean'},
'ldap_uid_regex': {'type': 'string'},
'ldap_uri': {'type': 'string'},
'ldap_bind_dn': {'type': 'string'},
'ldap_bind_user': {'type': 'string'},
'ldap_uid_attribute': {'type': 'string'},
'ldap_manager_attribute': {'type': 'string'},
'ldap_email_attribute': {'type': 'string'},
'ldap_bind_password_in_kms': {'type': 'boolean'},
'ldap_bind_password': {'type': 'string'},
'cross_accounts': {'type': 'object'},
'ses_region': {'type': 'string'},
'redis_host': {'type': 'string'},
'redis_port': {'type': 'integer'},
'datadog_api_key': {'type': 'string'}, # TODO: encrypt with KMS?
'datadog_application_key': {'type': 'string'}, # TODO: encrypt with KMS?
'slack_token': {'type': 'string'},
'slack_webhook': {'type': 'string'},
'sendgrid_api_key': {'type': 'string'},
# SDK Config
'profile': {'type': 'string'},
'http_proxy': {'type': 'string'},
'https_proxy': {'type': 'string'},
# Mapping account / emails
'account_emails': {'type': 'object'}
}
}
def session_factory(mailer_config):
return boto3.Session(
region_name=mailer_config['region'],
profile_name=mailer_config.get('profile', None))
def get_logger(debug=False):
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(level=logging.INFO, format=log_format)
logging.getLogger('botocore').setLevel(logging.WARNING)
if debug:
logging.getLogger('botocore').setLevel(logging.DEBUG)
debug_logger = logging.getLogger('custodian-mailer')
debug_logger.setLevel(logging.DEBUG)
return debug_logger
else:
return logging.getLogger('custodian-mailer')
def get_and_validate_mailer_config(args):
with open(args.config) as fh:
config = yaml.load(fh.read(), Loader=yaml.SafeLoader)
jsonschema.validate(config, CONFIG_SCHEMA)
utils.setup_defaults(config)
return config
def get_c7n_mailer_parser():
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', required=True, help='mailer.yml config file')
debug_help_msg = 'sets c7n_mailer logger to debug, for maximum output (the default is INFO)'
parser.add_argument('--debug', action='store_true', help=debug_help_msg)
max_num_processes_help_msg = 'will run the mailer in parallel, integer of max processes allowed'
parser.add_argument('--max-num-processes', type=int, help=max_num_processes_help_msg)
group = parser.add_mutually_exclusive_group(required=True)
update_lambda_help_msg = 'packages your c7n_mailer, uploads the zip to aws lambda as a function'
group.add_argument('--update-lambda', action='store_true', help=update_lambda_help_msg)
run_help_msg = 'run c7n-mailer locally, process sqs messages and send emails or sns messages'
group.add_argument('--run', action='store_true', help=run_help_msg)
return parser
def run_mailer_in_parallel(processor, max_num_processes):
max_num_processes = int(max_num_processes)
if max_num_processes < 1:
raise Exception
processor.max_num_processes = max_num_processes
processor.run(parallel=True)
def is_azure_cloud(mailer_config):
return mailer_config.get('queue_url').startswith('asq')
def main():
parser = get_c7n_mailer_parser()
args = parser.parse_args()
mailer_config = get_and_validate_mailer_config(args)
args_dict = vars(args)
logger = get_logger(debug=args_dict.get('debug', False))
if args_dict.get('update_lambda'):
if args_dict.get('debug'):
print('\n** --debug is only supported with --run, not --update-lambda **\n')
return
if args_dict.get('max_num_processes'):
print('\n** --max-num-processes is only supported '
'with --run, not --update-lambda **\n')
return
if is_azure_cloud(mailer_config):
azure_deploy.provision(mailer_config)
else:
deploy.provision(mailer_config, functools.partial(session_factory, mailer_config))
if args_dict.get('run'):
max_num_processes = args_dict.get('max_num_processes')
# Select correct processor
if is_azure_cloud(mailer_config):
processor = MailerAzureQueueProcessor(mailer_config, logger)
else:
aws_session = session_factory(mailer_config)
processor = MailerSqsQueueProcessor(mailer_config, aws_session, logger)
# Execute
if max_num_processes:
run_mailer_in_parallel(processor, max_num_processes)
else:
processor.run()
if __name__ == '__main__':
main()