-
Notifications
You must be signed in to change notification settings - Fork 13
/
helpers.py
249 lines (204 loc) · 7.59 KB
/
helpers.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
#!/usr/bin/python3
# Copyright 2024 Northern.tech AS
#
# 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
#
# https://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.
import logging
import os
import packaging.version
import re
import stat
import subprocess
import time
class Result:
def __init__(self, stdout, stderr, exited):
self.stdout = stdout
self.stderr = stderr
self.exited = exited
self.return_code = exited
@property
def failed(self):
return self.exited != 0
class Connection:
def __init__(self, host, user, port, connect_timeout, key_filename=None):
self.host = host
self.user = user
self.port = port
self.connect_timeout = connect_timeout
self.key_filename = key_filename
self.key = _prepare_key_arg(key_filename)
def __enter__(self):
return self
def get_ssh_command(self):
return f"ssh {self.key} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout={self.connect_timeout} -p {self.port} {self.user}@{self.host}"
def run(self, command, warn=False, hide=True, echo=False, popen=False):
if not command.startswith("ssh") and not command.startswith("scp"):
command = f"{self.get_ssh_command()} '{command}'"
logging.debug(command)
if echo:
print(command)
if popen:
return subprocess.Popen(command)
else:
try:
proc = subprocess.run(
command, check=not warn, capture_output=True, shell=True
)
returncode = proc.returncode
except subprocess.CalledProcessError as e:
returncode = e.returncode
if returncode != 255:
raise
if returncode == 255:
raise ConnectionError(f"Could not connect using command '{command}'")
stdout = proc.stdout.decode()
stderr = proc.stderr.decode()
if not hide:
print(stdout)
print(stderr)
return Result(stdout, stderr, returncode)
def put(self, file, key_filename=None, local_path=".", remote_path="."):
if not key_filename:
key_filename = self.key_filename
return put(self, file, key_filename, local_path, remote_path)
def sudo(self, command, warn=False):
sudo_command = f"sudo {command}"
return self.run(sudo_command, warn)
def __exit__(self, arg1, arg2, arg3):
pass
def _prepare_key_arg(key_filename):
if key_filename:
# Git doesn't track rw permissions, but the keyfile needs to be 600 for
# scp to accept it, so fix that here.
os.chmod(key_filename, stat.S_IRUSR | stat.S_IWUSR)
return "-i %s" % key_filename
else:
return ""
def put(conn, file, key_filename=None, local_path=".", remote_path="."):
key_arg = _prepare_key_arg(key_filename)
cmd = (
"scp %s -C -O -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -P %s %s %s@%s:%s"
% (
key_arg,
conn.port,
os.path.join(local_path, file),
conn.user,
conn.host,
remote_path,
)
)
logging.debug(cmd)
conn.run(cmd)
def run(conn, command, key_filename=None, warn=False):
key_arg = _prepare_key_arg(key_filename)
cmd = (
"ssh %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=60 -p %s %s@%s %s"
% (key_arg, conn.port, conn.user, conn.host, command)
)
logging.debug(cmd)
result = conn.run(cmd, warn=warn)
return result
class PortForward:
user = None
host = None
port = None
key_filename = None
local_port = None
remote_port = None
args = None
proc = None
def __init__(self, conn, key_filename, local_port, remote_port):
self.user = conn.user
self.host = conn.host
self.port = conn.port
self.key_filename = key_filename
self.local_port = local_port
self.remote_port = remote_port
def __enter__(self):
try:
key_arg = _prepare_key_arg(self.key_filename).split()
self.args = (
["ssh", "-4", "-N", "-f"]
+ key_arg
+ [
"-L",
"%d:localhost:%d" % (self.local_port, self.remote_port),
"-o",
"StrictHostKeyChecking=no",
"-o",
"UserKnownHostsFile=/dev/null",
"-p",
"%d" % self.port,
"%s@%s" % (self.user, self.host),
]
)
self.proc = subprocess.Popen(self.args)
# '-f' flag causes SSH to background itself. We wait until it does so.
self.proc.wait()
if self.proc.returncode != 0:
raise subprocess.CalledProcessError(self.proc.returncode, self.args)
except subprocess.CalledProcessError:
self.proc = None
raise
def __exit__(self, arg1, arg2, arg3):
if self.proc:
subprocess.check_call(["pkill", "-xf", re.escape(" ".join(self.args))])
def new_tester_ssh_connection(setup_test_container):
with Connection(
host="localhost",
user=setup_test_container.user,
port=setup_test_container.port,
key_filename=setup_test_container.key_filename,
connect_timeout=60,
) as conn:
ready = _probe_ssh_connection(conn)
assert ready, "SSH connection can not be established. Aborting"
return conn
def wait_for_container_boot(docker_container_id):
assert docker_container_id is not None
ready = False
timeout = time.time() + 60 * 3
while not ready and time.time() < timeout:
time.sleep(5)
output = subprocess.check_output(
"docker logs {} 2>&1".format(docker_container_id), shell=True
)
# Check on the last few chars only, so that we can detect reboots
# For Raspberry Pi OS, the tty prompt comes earlier than the SSH server, so wait for the later
if re.search(
"(Poky.* tty|Started.*OpenBSD Secure Shell server)",
output.decode("utf-8")[-1000:],
flags=re.MULTILINE,
):
ready = True
return ready
def _probe_ssh_connection(conn):
ready = False
timeout = time.time() + 60
while not ready and time.time() < timeout:
try:
result = conn.run("true", hide=True)
if result.exited == 0:
ready = True
except ConnectionError as e:
if not "Could not connect using command" in str(e):
raise e
time.sleep(5)
return ready
def version_is_minimum(mender_deb_version, min_version):
try:
version_parsed = packaging.version.Version(mender_deb_version)
except packaging.version.InvalidVersion:
# Indicates that 'mender_deb_version' is likely a string (branch name).
# Always consider them higher than the minimum version.
return True
return version_parsed >= packaging.version.Version(min_version)