-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathhandlers.py.template
368 lines (303 loc) · 12.8 KB
/
handlers.py.template
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
import logging
import json
import os
from uuid import uuid4
from typing import Any, MutableMapping, Optional
from cloudformation_cli_python_lib import (
Action,
HandlerErrorCode,
OperationStatus,
ProgressEvent,
Resource,
SessionProxy,
exceptions,
)
from .models import ResourceHandlerRequest, ResourceModel
# Use this logger to forward log messages to CloudWatch Logs.
LOG = logging.getLogger(__name__)
TYPE_NAME = "###CFNTYPENAME###"
resource = Resource(TYPE_NAME, ResourceModel)
test_entrypoint = resource.test_entrypoint
def check_progress(operationid, trackingid, progress, session):
LOG.warn("Retrieving existing operation status ({})".format(operationid))
s3client = session.client('s3')
stsclient = session.client('sts')
callerid = stsclient.get_caller_identity()
statebucketname = "cfntf-{}-{}".format(os.environ['AWS_REGION'], callerid.get('Account'))
try:
result = json.loads(s3client.get_object(Bucket=statebucketname, Key="status/{}.json".format(operationid))['Body'].read())
s3client.delete_object(Bucket=statebucketname, Key="status/{}.json".format(operationid))
if result['status'] == 'completed':
progress.status = OperationStatus.SUCCESS
# retrieve model
try:
state_str = s3client.get_object(Bucket=statebucketname, Key="state/###TFTYPENAME###/{}.model.json".format(trackingid))['Body'].read()
if state_str == "":
state_str = "{}"
model_state = json.loads(state_str)
for k,v in model_state.items():
setattr(progress.resourceModel, k, v)
except Exception as e:
LOG.warn(str(e))
LOG.warn("Action complete")
else:
progress.status = OperationStatus.FAILED
if 'error' in result:
progress.message = result['error']
progress.errorCode = HandlerErrorCode.GeneralServiceException
except:
progress.callbackDelaySeconds = 20
progress.callbackContext = {
'trackingid': trackingid,
'operationid': operationid,
}
return progress
@resource.handler(Action.CREATE)
def create_handler(
session: Optional[SessionProxy],
request: ResourceHandlerRequest,
callback_context: MutableMapping[str, Any],
) -> ProgressEvent:
model = request.desiredResourceState
progress: ProgressEvent = ProgressEvent(
status=OperationStatus.IN_PROGRESS,
resourceModel=model,
)
if callback_context.get('operationid'):
return check_progress(callback_context.get('operationid'), callback_context.get('trackingid'), progress, session)
LOG.warn("Starting create action")
try:
lambdaclient = session.client("lambda")
trackingid = str(uuid4())
operationid = str(uuid4())
resolved_model = None
if model: # potentially no properties set
resolved_model = model._serialize()
lambdaclient.invoke(
FunctionName="cfntf-executor",
InvocationType="Event",
Payload=json.dumps({
'action': 'CREATE',
'trackingId': trackingid,
'operationId': operationid,
'model': resolved_model,
'logicalId': request.logicalResourceIdentifier,
'providerFullName': '###PROVIDERFULLNAME###',
'providerTypeName': '###PROVIDERTYPENAME###',
'terraformTypeName': '###TFTYPENAME###',
'returnValues': ###GETATT###,
}).encode(),
)
progress.resourceModel.tfcfnid = trackingid
progress.callbackDelaySeconds = 20
progress.callbackContext = {
'trackingid': trackingid,
'operationid': operationid,
}
except lambdaclient.exceptions.ResourceNotFoundException as e:
progress.message = "The execution infrastructure is not available. Read more at https://github.com/iann0036/cfn-tf-custom-types."
progress.status = OperationStatus.FAILED
progress.errorCode = HandlerErrorCode.GeneralServiceException
except Exception as e:
progress.status = OperationStatus.FAILED
progress.message = str(e)
progress.errorCode = HandlerErrorCode.InternalFailure
return progress
@resource.handler(Action.UPDATE)
def update_handler(
session: Optional[SessionProxy],
request: ResourceHandlerRequest,
callback_context: MutableMapping[str, Any],
) -> ProgressEvent:
model = request.desiredResourceState
progress: ProgressEvent = ProgressEvent(
status=OperationStatus.IN_PROGRESS,
resourceModel=model,
)
s3client = session.client('s3')
stsclient = session.client('sts')
callerid = stsclient.get_caller_identity()
statebucketname = "cfntf-{}-{}".format(os.environ['AWS_REGION'], callerid.get('Account'))
if callback_context.get('operationid'):
return check_progress(callback_context.get('operationid'), callback_context.get('trackingid'), progress, session)
LOG.warn("Starting update action")
try:
state_str = s3client.get_object(Bucket=statebucketname, Key="state/###TFTYPENAME###/{}.model.json".format(model.tfcfnid))['Body'].read()
if state_str == "":
state_str = "{}"
model_state = json.loads(state_str)
lambdaclient = session.client("lambda")
trackingid = model.tfcfnid
operationid = str(uuid4())
resolved_model = None
if model: # potentially no properties set
resolved_model = model._serialize()
lambdaclient.invoke(
FunctionName="cfntf-executor",
InvocationType="Event",
Payload=json.dumps({
'action': 'UPDATE',
'trackingId': trackingid,
'operationId': operationid,
'model': resolved_model,
'logicalId': request.logicalResourceIdentifier,
'providerFullName': '###PROVIDERFULLNAME###',
'providerTypeName': '###PROVIDERTYPENAME###',
'terraformTypeName': '###TFTYPENAME###',
'returnValues': ###GETATT###,
}).encode(),
)
progress.resourceModel.tfcfnid = trackingid
progress.callbackDelaySeconds = 20
progress.callbackContext = {
'trackingid': trackingid,
'operationid': operationid,
}
except s3client.exceptions.NoSuchKey as e:
progress.message = str(e)
progress.status = OperationStatus.FAILED
progress.errorCode = HandlerErrorCode.NotFound
except lambdaclient.exceptions.ResourceNotFoundException as e:
progress.message = "The execution infrastructure is not available. Read more at https://github.com/iann0036/cfn-tf-custom-types."
progress.status = OperationStatus.FAILED
progress.errorCode = HandlerErrorCode.GeneralServiceException
except Exception as e:
progress.message = str(e)
progress.status = OperationStatus.FAILED
progress.errorCode = HandlerErrorCode.InternalFailure
return progress
@resource.handler(Action.DELETE)
def delete_handler(
session: Optional[SessionProxy],
request: ResourceHandlerRequest,
callback_context: MutableMapping[str, Any],
) -> ProgressEvent:
model = request.desiredResourceState
progress: ProgressEvent = ProgressEvent(
status=OperationStatus.IN_PROGRESS,
resourceModel=model,
)
s3client = session.client('s3')
stsclient = session.client('sts')
callerid = stsclient.get_caller_identity()
statebucketname = "cfntf-{}-{}".format(os.environ['AWS_REGION'], callerid.get('Account'))
if callback_context.get('operationid'):
ret = check_progress(callback_context.get('operationid'), callback_context.get('trackingid'), progress, session)
ret.resourceModel = None
return ret
LOG.warn("Starting delete action")
try:
state_str = s3client.get_object(Bucket=statebucketname, Key="state/###TFTYPENAME###/{}.model.json".format(model.tfcfnid))['Body'].read()
if state_str == "":
state_str = "{}"
model_state = json.loads(state_str)
lambdaclient = session.client("lambda")
trackingid = model.tfcfnid
operationid = str(uuid4())
resolved_model = None
if model: # potentially no properties set
resolved_model = model._serialize()
lambdaclient.invoke(
FunctionName="cfntf-executor",
InvocationType="Event",
Payload=json.dumps({
'action': 'DELETE',
'trackingId': trackingid,
'operationId': operationid,
'model': resolved_model,
'logicalId': request.logicalResourceIdentifier,
'providerFullName': '###PROVIDERFULLNAME###',
'providerTypeName': '###PROVIDERTYPENAME###',
'terraformTypeName': '###TFTYPENAME###',
'returnValues': ###GETATT###,
}).encode(),
)
progress.resourceModel.tfcfnid = trackingid
progress.callbackDelaySeconds = 20
progress.callbackContext = {
'trackingid': trackingid,
'operationid': operationid,
}
except s3client.exceptions.NoSuchKey as e:
progress.message = str(e)
progress.status = OperationStatus.FAILED
progress.errorCode = HandlerErrorCode.NotFound
except lambdaclient.exceptions.ResourceNotFoundException as e:
progress.message = "The execution infrastructure is not available. Read more at https://github.com/iann0036/cfn-tf-custom-types."
progress.status = OperationStatus.FAILED
progress.errorCode = HandlerErrorCode.GeneralServiceException
except Exception as e:
progress.message = str(e)
progress.status = OperationStatus.FAILED
progress.errorCode = HandlerErrorCode.InternalFailure
return progress
@resource.handler(Action.READ)
def read_handler(
session: Optional[SessionProxy],
request: ResourceHandlerRequest,
callback_context: MutableMapping[str, Any],
) -> ProgressEvent:
model = request.desiredResourceState
s3client = session.client('s3')
stsclient = session.client('sts')
callerid = stsclient.get_caller_identity()
statebucketname = "cfntf-{}-{}".format(os.environ['AWS_REGION'], callerid.get('Account'))
# retrieve model
try:
state_str = s3client.get_object(Bucket=statebucketname, Key="state/###TFTYPENAME###/{}.model.json".format(model.tfcfnid))['Body'].read()
if state_str == "":
state_str = "{}"
model_state = json.loads(state_str)
for k,v in model_state.items():
setattr(model, k, v)
return ProgressEvent(
status=OperationStatus.SUCCESS,
resourceModel=model,
)
except Exception as e:
LOG.warn(str(e))
return ProgressEvent(
status=OperationStatus.FAILED,
errorCode=HandlerErrorCode.NotFound,
resourceModel=model,
)
@resource.handler(Action.LIST)
def list_handler(
session: Optional[SessionProxy],
request: ResourceHandlerRequest,
callback_context: MutableMapping[str, Any],
) -> ProgressEvent:
s3client = session.client('s3')
stsclient = session.client('sts')
callerid = stsclient.get_caller_identity()
statebucketname = "cfntf-{}-{}".format(os.environ['AWS_REGION'], callerid.get('Account'))
# retrieve models
try:
models = []
state_objects = s3client.list_objects_v2(
Bucket=statebucketname,
MaxKeys=1000,
Prefix='state/###TFTYPENAME###/'
)
if 'Contents' in state_objects:
for state_object in state_objects['Contents']:
if state_object['Key'].endswith(".model.json"):
model = ResourceModel(tfcfnid=state_object['Key'].replace(".model.json", ""), ###ALLPROPS###)
state_str = s3client.get_object(Bucket=statebucketname, Key=state_object['Key'])['Body'].read()
if state_str == "":
state_str = "{}"
model_state = json.loads(state_str)
for k,v in model_state.items():
setattr(model, k, v)
models.append(model)
return ProgressEvent(
status=OperationStatus.SUCCESS,
resourceModels=models,
)
except Exception as e:
LOG.warn(str(e))
return ProgressEvent(
status=OperationStatus.FAILED,
errorCode=HandlerErrorCode.InternalFailure,
resourceModels=[],
)