-
Notifications
You must be signed in to change notification settings - Fork 175
/
oe_upload.py
159 lines (131 loc) · 5.5 KB
/
oe_upload.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
""" oe_upload.py: client script for running OE updates
This requires aiohttp
"""
import argparse
import asyncio
import json
import sys
import aiohttp
# TODO (al, 2022-04-18): This separate script should be refactored. It and
# buildroot_upload.py should be merged into one script.
async def poll_status(sess, token, root):
await asyncio.sleep(1.0)
resp = await sess.get(root + '/' + token + '/status')
return await resp.json()
async def do_update(update_file: str, host: str,
pause_between_steps: bool = False):
timeout = aiohttp.ClientTimeout(total=7200)
async with aiohttp.ClientSession(timeout=timeout) as session:
root = host + '/server/update'
filename = "ot3-system.zip"
print(f"Starting update of {update_file.name} to {host}")
begin_resp = await session.post(root + '/begin')
if begin_resp.status == 409:
should_cancel = input(
'Another update is in process! Cancel [yN]? ')
if should_cancel.lower()[0] == 'y':
cancel_resp = await session.post(root + '/cancel')
if cancel_resp.status != 200:
body = await cancel_resp.text()
sys.stderr.write(
f"Error response from host when canceling: "
f"{cancel_resp.status}: {body}\n")
sys.exit(-1)
begin_resp = await session.post(root + '/begin')
if begin_resp.status != 201:
body = await begin_resp.text()
sys.stderr.write(
f'Error response from host: {begin_resp.status}: {body}')
sys.exit(-1)
begin_body = await begin_resp.json()
token = begin_body['token']
msg = f'Session created at {root}/{token}'
if pause_between_steps:
input(f'{msg}. Press enter to continue to upload and validation')
else:
print(msg)
print(f"Uploading file...")
file_resp = await session.post(root + '/' + token + '/file',
data={filename: update_file})
if file_resp.status != 201:
body = await file_resp.text()
try:
json_resp = json.loads(body)
except json.JSONDecodeError:
message = body
else:
message = f'{json_resp["error"]}: {json_resp["message"]}'
print(f'Error uploading file: {message}')
sys.exit(-1)
status = await file_resp.json()
while status['stage'] == 'validating':
sys.stdout.write(
f'{status["message"]}: {status["progress"] * 100:.0f}%\r')
status = await poll_status(session, token, root)
print(msg)
if status['stage'] == 'error':
print(f'Error validating: {status["error"]}: {status["message"]}')
sys.exit(-1)
while status['stage'] == 'writing':
sys.stdout.write(
f'{status["message"]}: {status["progress"] * 100:.0f}%\r')
status = await poll_status(session, token, root)
if status['stage'] == 'error':
print(f'Error writing: {status["error"]}: {status["message"]}')
sys.exit(-1)
msg = 'File written and validated'
if pause_between_steps:
input(f'{msg}. Press enter to continue to commit')
else:
print(msg)
if status['stage'] == 'done':
print("Committing update...")
resp = await session.post(root + '/' + token + '/commit')
if resp.status != 200:
print(f'Error committing: {status["error"]}: '
f'{status["message"]}')
sys.exit(-1)
msg = 'Update committed'
if pause_between_steps:
input(f'{msg}. Press enter to continue to restart')
else:
print(msg)
print("Restarting...")
resp = await session.post(host + '/server/restart')
if resp.status != 200:
try:
body = await resp.json()
print(f'Error restarting: {resp.status}: '
f'{body["error"]: body["message"]}')
except (json.JSONDecodeError,
KeyError,
aiohttp.client_exceptions.ContentTypeError):
body = await resp.text()
print(f'Error restarting: {resp.status}: {body}')
sys.exit(-1)
print("Done!")
def assure_host(host_arg):
if not host_arg.startswith('http'):
host_arg = 'http:https://' + host_arg
if not host_arg.endswith(':31950'):
host_arg = host_arg + ':31950'
return host_arg
def main():
parser = argparse.ArgumentParser(description='update OE systems')
parser.add_argument('update', metavar='UPDATE_FILE',
type=argparse.FileType('rb'),
help='The OT3/OE root file system to upload')
parser.add_argument('host', metavar='ROBOT HOSTNAME',
type=str,
help='The IP of the robot')
parser.add_argument('-s', '--step-by-step', action='store_true',
help='Pause until the user hits enter in between each '
'stage. Useful for dev workflows')
args = parser.parse_args()
asyncio.get_event_loop().run_until_complete(
do_update(
args.update,
assure_host(args.host),
pause_between_steps=args.step_by_step))
if __name__ == '__main__':
main()