- Notifications
You must be signed in to change notification settings - Fork 219
/
Copy pathfleetprovisioning.py
388 lines (303 loc) · 15.3 KB
/
fleetprovisioning.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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0.
fromawscrtimportmqtt, http
fromawsiotimportiotidentity, mqtt_connection_builder
fromconcurrent.futuresimportFuture
importsys
importthreading
importtime
importtraceback
importjson
fromutils.command_line_utilsimportCommandLineUtils
# - Overview -
# This sample uses the AWS IoT Fleet Provisioning to provision device using either the keys
# or CSR
#
#
# - Instructions -
# This sample requires you to create a provisioning claim. See:
# https://docs.aws.amazon.com/iot/latest/developerguide/provision-wo-cert.html
#
# - Detail -
# On startup, the script subscribes to topics based on the request type of either CSR or Keys
# publishes the request to corresponding topic and calls RegisterThing.
# cmdData is the arguments/input from the command line placed into a single struct for
# use in this sample. This handles all of the command line parsing, validating, etc.
# See the Utils/CommandLineUtils for more information.
cmdData=CommandLineUtils.parse_sample_input_fleet_provisioning()
# Using globals to simplify sample code
is_sample_done=threading.Event()
mqtt_connection=None
identity_client=None
createKeysAndCertificateResponse=None
createCertificateFromCsrResponse=None
registerThingResponse=None
classLockedData:
def__init__(self):
self.lock=threading.Lock()
self.disconnect_called=False
locked_data=LockedData()
# Function for gracefully quitting this sample
defexit(msg_or_exception):
ifisinstance(msg_or_exception, Exception):
print("Exiting Sample due to exception.")
traceback.print_exception(msg_or_exception.__class__, msg_or_exception, sys.exc_info()[2])
else:
print("Exiting Sample:", msg_or_exception)
withlocked_data.lock:
ifnotlocked_data.disconnect_called:
print("Disconnecting...")
locked_data.disconnect_called=True
future=mqtt_connection.disconnect()
future.add_done_callback(on_disconnected)
defon_disconnected(disconnect_future):
# type: (Future) -> None
print("Disconnected.")
# Signal that sample is finished
is_sample_done.set()
defon_publish_register_thing(future):
# type: (Future) -> None
try:
future.result() # raises exception if publish failed
print("Published RegisterThing request..")
exceptExceptionase:
print("Failed to publish RegisterThing request.")
exit(e)
defon_publish_create_keys_and_certificate(future):
# type: (Future) -> None
try:
future.result() # raises exception if publish failed
print("Published CreateKeysAndCertificate request..")
exceptExceptionase:
print("Failed to publish CreateKeysAndCertificate request.")
exit(e)
defon_publish_create_certificate_from_csr(future):
# type: (Future) -> None
try:
future.result() # raises exception if publish failed
print("Published CreateCertificateFromCsr request..")
exceptExceptionase:
print("Failed to publish CreateCertificateFromCsr request.")
exit(e)
defcreatekeysandcertificate_execution_accepted(response):
# type: (iotidentity.CreateKeysAndCertificateResponse) -> None
try:
globalcreateKeysAndCertificateResponse
createKeysAndCertificateResponse=response
if (cmdData.input_is_ci==False):
print("Received a new message {}".format(createKeysAndCertificateResponse))
return
exceptExceptionase:
exit(e)
defcreatekeysandcertificate_execution_rejected(rejected):
# type: (iotidentity.RejectedError) -> None
exit("CreateKeysAndCertificate Request rejected with code:'{}' message:'{}' status code:'{}'".format(
rejected.error_code, rejected.error_message, rejected.status_code))
defcreatecertificatefromcsr_execution_accepted(response):
# type: (iotidentity.CreateCertificateFromCsrResponse) -> None
try:
globalcreateCertificateFromCsrResponse
createCertificateFromCsrResponse=response
if (cmdData.input_is_ci==False):
print("Received a new message {}".format(createCertificateFromCsrResponse))
globalcertificateOwnershipToken
certificateOwnershipToken=response.certificate_ownership_token
return
exceptExceptionase:
exit(e)
defcreatecertificatefromcsr_execution_rejected(rejected):
# type: (iotidentity.RejectedError) -> None
exit("CreateCertificateFromCsr Request rejected with code:'{}' message:'{}' status code:'{}'".format(
rejected.error_code, rejected.error_message, rejected.status_code))
defregisterthing_execution_accepted(response):
# type: (iotidentity.RegisterThingResponse) -> None
try:
globalregisterThingResponse
registerThingResponse=response
if (cmdData.input_is_ci==False):
print("Received a new message {} ".format(registerThingResponse))
return
exceptExceptionase:
exit(e)
defregisterthing_execution_rejected(rejected):
# type: (iotidentity.RejectedError) -> None
exit("RegisterThing Request rejected with code:'{}' message:'{}' status code:'{}'".format(
rejected.error_code, rejected.error_message, rejected.status_code))
# Callback when connection is accidentally lost.
defon_connection_interrupted(connection, error, **kwargs):
print("Connection interrupted. error: {}".format(error))
# Callback when an interrupted connection is re-established.
defon_connection_resumed(connection, return_code, session_present, **kwargs):
print("Connection resumed. return_code: {} session_present: {}".format(return_code, session_present))
ifreturn_code==mqtt.ConnectReturnCode.ACCEPTEDandnotsession_present:
print("Session did not persist. Resubscribing to existing topics...")
resubscribe_future, _=connection.resubscribe_existing_topics()
# Cannot synchronously wait for resubscribe result because we're on the connection's event-loop thread,
# evaluate result with a callback instead.
resubscribe_future.add_done_callback(on_resubscribe_complete)
defon_resubscribe_complete(resubscribe_future):
resubscribe_results=resubscribe_future.result()
print("Resubscribe results: {}".format(resubscribe_results))
fortopic, qosinresubscribe_results['topics']:
ifqosisNone:
sys.exit("Server rejected resubscribe to topic: {}".format(topic))
defwaitForCreateKeysAndCertificateResponse():
# Wait for the response.
loopCount=0
whileloopCount<10andcreateKeysAndCertificateResponseisNone:
ifcreateKeysAndCertificateResponseisnotNone:
break
ifnotcmdData.input_is_ci:
print('Waiting... CreateKeysAndCertificateResponse: '+json.dumps(createKeysAndCertificateResponse))
else:
print("Waiting... CreateKeysAndCertificateResponse: ...")
loopCount+=1
time.sleep(1)
defwaitForCreateCertificateFromCsrResponse():
# Wait for the response.
loopCount=0
whileloopCount<10andcreateCertificateFromCsrResponseisNone:
ifcreateCertificateFromCsrResponseisnotNone:
break
ifnotcmdData.input_is_ci:
print('Waiting...CreateCertificateFromCsrResponse: '+json.dumps(createCertificateFromCsrResponse))
else:
print("Waiting... CreateCertificateFromCsrResponse: ...")
loopCount+=1
time.sleep(1)
defwaitForRegisterThingResponse():
# Wait for the response.
loopCount=0
whileloopCount<20andregisterThingResponseisNone:
ifregisterThingResponseisnotNone:
break
loopCount+=1
ifnotcmdData.input_is_ci:
print('Waiting... RegisterThingResponse: '+json.dumps(registerThingResponse))
else:
print('Waiting... RegisterThingResponse: ...')
time.sleep(1)
if__name__=='__main__':
# Create the proxy options if the data is present in cmdData
proxy_options=None
ifcmdData.input_proxy_hostisnotNoneandcmdData.input_proxy_port!=0:
proxy_options=http.HttpProxyOptions(
host_name=cmdData.input_proxy_host,
port=cmdData.input_proxy_port)
# Create a MQTT connection from the command line data
mqtt_connection=mqtt_connection_builder.mtls_from_path(
endpoint=cmdData.input_endpoint,
port=cmdData.input_port,
cert_filepath=cmdData.input_cert,
pri_key_filepath=cmdData.input_key,
ca_filepath=cmdData.input_ca,
on_connection_interrupted=on_connection_interrupted,
on_connection_resumed=on_connection_resumed,
client_id=cmdData.input_clientId,
clean_session=False,
keep_alive_secs=30,
http_proxy_options=proxy_options)
ifnotcmdData.input_is_ci:
print(f"Connecting to {cmdData.input_endpoint} with client ID '{cmdData.input_clientId}'...")
else:
print("Connecting to endpoint with client ID")
connected_future=mqtt_connection.connect()
identity_client=iotidentity.IotIdentityClient(mqtt_connection)
# Wait for connection to be fully established.
# Note that it's not necessary to wait, commands issued to the
# mqtt_connection before its fully connected will simply be queued.
# But this sample waits here so it's obvious when a connection
# fails or succeeds.
connected_future.result()
print("Connected!")
try:
# Subscribe to necessary topics.
# Note that is **is** important to wait for "accepted/rejected" subscriptions
# to succeed before publishing the corresponding "request".
# Keys workflow if csr is not provided
ifcmdData.input_csr_pathisNone:
createkeysandcertificate_subscription_request=iotidentity.CreateKeysAndCertificateSubscriptionRequest()
print("Subscribing to CreateKeysAndCertificate Accepted topic...")
createkeysandcertificate_subscribed_accepted_future, _=identity_client.subscribe_to_create_keys_and_certificate_accepted(
request=createkeysandcertificate_subscription_request,
qos=mqtt.QoS.AT_LEAST_ONCE,
callback=createkeysandcertificate_execution_accepted)
# Wait for subscription to succeed
createkeysandcertificate_subscribed_accepted_future.result()
print("Subscribing to CreateKeysAndCertificate Rejected topic...")
createkeysandcertificate_subscribed_rejected_future, _=identity_client.subscribe_to_create_keys_and_certificate_rejected(
request=createkeysandcertificate_subscription_request,
qos=mqtt.QoS.AT_LEAST_ONCE,
callback=createkeysandcertificate_execution_rejected)
# Wait for subscription to succeed
createkeysandcertificate_subscribed_rejected_future.result()
else:
createcertificatefromcsr_subscription_request=iotidentity.CreateCertificateFromCsrSubscriptionRequest()
print("Subscribing to CreateCertificateFromCsr Accepted topic...")
createcertificatefromcsr_subscribed_accepted_future, _=identity_client.subscribe_to_create_certificate_from_csr_accepted(
request=createcertificatefromcsr_subscription_request,
qos=mqtt.QoS.AT_LEAST_ONCE,
callback=createcertificatefromcsr_execution_accepted)
# Wait for subscription to succeed
createcertificatefromcsr_subscribed_accepted_future.result()
print("Subscribing to CreateCertificateFromCsr Rejected topic...")
createcertificatefromcsr_subscribed_rejected_future, _=identity_client.subscribe_to_create_certificate_from_csr_rejected(
request=createcertificatefromcsr_subscription_request,
qos=mqtt.QoS.AT_LEAST_ONCE,
callback=createcertificatefromcsr_execution_rejected)
# Wait for subscription to succeed
createcertificatefromcsr_subscribed_rejected_future.result()
registerthing_subscription_request=iotidentity.RegisterThingSubscriptionRequest(
template_name=cmdData.input_template_name)
print("Subscribing to RegisterThing Accepted topic...")
registerthing_subscribed_accepted_future, _=identity_client.subscribe_to_register_thing_accepted(
request=registerthing_subscription_request,
qos=mqtt.QoS.AT_LEAST_ONCE,
callback=registerthing_execution_accepted)
# Wait for subscription to succeed
registerthing_subscribed_accepted_future.result()
print("Subscribing to RegisterThing Rejected topic...")
registerthing_subscribed_rejected_future, _=identity_client.subscribe_to_register_thing_rejected(
request=registerthing_subscription_request,
qos=mqtt.QoS.AT_LEAST_ONCE,
callback=registerthing_execution_rejected)
# Wait for subscription to succeed
registerthing_subscribed_rejected_future.result()
fleet_template_name=cmdData.input_template_name
fleet_template_parameters=cmdData.input_template_parameters
ifcmdData.input_csr_pathisNone:
print("Publishing to CreateKeysAndCertificate...")
publish_future=identity_client.publish_create_keys_and_certificate(
request=iotidentity.CreateKeysAndCertificateRequest(), qos=mqtt.QoS.AT_LEAST_ONCE)
publish_future.add_done_callback(on_publish_create_keys_and_certificate)
waitForCreateKeysAndCertificateResponse()
ifcreateKeysAndCertificateResponseisNone:
raiseException('CreateKeysAndCertificate API did not succeed')
registerThingRequest=iotidentity.RegisterThingRequest(
template_name=fleet_template_name,
certificate_ownership_token=createKeysAndCertificateResponse.certificate_ownership_token,
parameters=json.loads(fleet_template_parameters))
else:
print("Publishing to CreateCertificateFromCsr...")
csrPath=open(cmdData.input_csr_path, 'r').read()
publish_future=identity_client.publish_create_certificate_from_csr(
request=iotidentity.CreateCertificateFromCsrRequest(certificate_signing_request=csrPath),
qos=mqtt.QoS.AT_LEAST_ONCE)
publish_future.add_done_callback(on_publish_create_certificate_from_csr)
waitForCreateCertificateFromCsrResponse()
ifcreateCertificateFromCsrResponseisNone:
raiseException('CreateCertificateFromCsr API did not succeed')
registerThingRequest=iotidentity.RegisterThingRequest(
template_name=fleet_template_name,
certificate_ownership_token=createCertificateFromCsrResponse.certificate_ownership_token,
parameters=json.loads(fleet_template_parameters))
print("Publishing to RegisterThing topic...")
registerthing_publish_future=identity_client.publish_register_thing(
registerThingRequest, mqtt.QoS.AT_LEAST_ONCE)
registerthing_publish_future.add_done_callback(on_publish_register_thing)
waitForRegisterThingResponse()
exit("success")
exceptExceptionase:
exit(e)
# Wait for the sample to finish
is_sample_done.wait()