blob: f5151403c463804497d435ac4e2cb13b13bcada9 [file] [log] [blame]
Yifan Hong0c715502021-04-19 13:48:21 -07001#!/usr/bin/env python3
Alex Deymo6751bbe2017-03-21 11:20:02 -07002#
3# Copyright (C) 2017 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18"""Send an A/B update to an Android device over adb."""
19
Kelvin Zhang4b883ea2020-10-08 13:26:44 -040020from __future__ import print_function
Andrew Lassalle165843c2019-11-05 13:30:34 -080021from __future__ import absolute_import
22
Alex Deymo6751bbe2017-03-21 11:20:02 -070023import argparse
Kelvin Zhangaba70ab2020-08-04 10:32:59 -040024import binascii
Sen Jiang3b15b592017-09-26 18:21:04 -070025import hashlib
Alex Deymo6751bbe2017-03-21 11:20:02 -070026import logging
27import os
Kelvin Zhang46a860c2022-09-28 19:42:39 -070028import re
Alex Deymo6751bbe2017-03-21 11:20:02 -070029import socket
30import subprocess
31import sys
Kelvin Zhangaba70ab2020-08-04 10:32:59 -040032import struct
Kelvin Zhang51aad992021-02-19 14:46:28 -050033import tempfile
Nikita Ioffe3a327e62021-06-30 16:05:09 +010034import time
Alex Deymo6751bbe2017-03-21 11:20:02 -070035import threading
Sen Jiang144f9f82017-09-26 15:49:45 -070036import xml.etree.ElementTree
Alex Deymo6751bbe2017-03-21 11:20:02 -070037import zipfile
Kelvin Zhang9a2d9a32023-11-28 09:42:16 -080038import shutil
Alex Deymo6751bbe2017-03-21 11:20:02 -070039
Andrew Lassalle165843c2019-11-05 13:30:34 -080040from six.moves import BaseHTTPServer
41
Alex Deymo6751bbe2017-03-21 11:20:02 -070042
43# The path used to store the OTA package when applying the package from a file.
44OTA_PACKAGE_PATH = '/data/ota_package'
45
Sen Jianga1784b72017-08-09 17:42:36 -070046# The path to the payload public key on the device.
47PAYLOAD_KEY_PATH = '/etc/update_engine/update-payload-key.pub.pem'
48
49# The port on the device that update_engine should connect to.
50DEVICE_PORT = 1234
Alex Deymo6751bbe2017-03-21 11:20:02 -070051
Andrew Lassalle165843c2019-11-05 13:30:34 -080052
Kelvin Zhang46a860c2022-09-28 19:42:39 -070053def CopyFileObjLength(fsrc, fdst, buffer_size=128 * 1024, copy_length=None, speed_limit=None):
Alex Deymo6751bbe2017-03-21 11:20:02 -070054 """Copy from a file object to another.
55
56 This function is similar to shutil.copyfileobj except that it allows to copy
57 less than the full source file.
58
59 Args:
60 fsrc: source file object where to read from.
61 fdst: destination file object where to write to.
62 buffer_size: size of the copy buffer in memory.
63 copy_length: maximum number of bytes to copy, or None to copy everything.
Kelvin Zhang46a860c2022-09-28 19:42:39 -070064 speed_limit: upper limit for copying speed, in bytes per second.
Alex Deymo6751bbe2017-03-21 11:20:02 -070065
66 Returns:
67 the number of bytes copied.
68 """
Kelvin Zhang46a860c2022-09-28 19:42:39 -070069 # If buffer size significantly bigger than speed limit
70 # traffic would seem extremely spiky to the client.
71 if speed_limit:
72 print(f"Applying speed limit: {speed_limit}")
73 buffer_size = min(speed_limit//32, buffer_size)
74
75 start_time = time.time()
Alex Deymo6751bbe2017-03-21 11:20:02 -070076 copied = 0
77 while True:
78 chunk_size = buffer_size
79 if copy_length is not None:
80 chunk_size = min(chunk_size, copy_length - copied)
81 if not chunk_size:
82 break
83 buf = fsrc.read(chunk_size)
84 if not buf:
85 break
Kelvin Zhang46a860c2022-09-28 19:42:39 -070086 if speed_limit:
87 expected_duration = copied/speed_limit
88 actual_duration = time.time() - start_time
89 if actual_duration < expected_duration:
90 time.sleep(expected_duration-actual_duration)
Alex Deymo6751bbe2017-03-21 11:20:02 -070091 fdst.write(buf)
92 copied += len(buf)
93 return copied
94
95
96class AndroidOTAPackage(object):
97 """Android update payload using the .zip format.
98
99 Android OTA packages traditionally used a .zip file to store the payload. When
100 applying A/B updates over the network, a payload binary is stored RAW inside
101 this .zip file which is used by update_engine to apply the payload. To do
102 this, an offset and size inside the .zip file are provided.
103 """
104
105 # Android OTA package file paths.
106 OTA_PAYLOAD_BIN = 'payload.bin'
107 OTA_PAYLOAD_PROPERTIES_TXT = 'payload_properties.txt'
Tianjie Xu3f9be772019-11-02 18:31:50 -0700108 SECONDARY_OTA_PAYLOAD_BIN = 'secondary/payload.bin'
109 SECONDARY_OTA_PAYLOAD_PROPERTIES_TXT = 'secondary/payload_properties.txt'
Kelvin Zhangaba70ab2020-08-04 10:32:59 -0400110 PAYLOAD_MAGIC_HEADER = b'CrAU'
Alex Deymo6751bbe2017-03-21 11:20:02 -0700111
Tianjie Xu3f9be772019-11-02 18:31:50 -0700112 def __init__(self, otafilename, secondary_payload=False):
Alex Deymo6751bbe2017-03-21 11:20:02 -0700113 self.otafilename = otafilename
114
115 otazip = zipfile.ZipFile(otafilename, 'r')
Tianjie Xu3f9be772019-11-02 18:31:50 -0700116 payload_entry = (self.SECONDARY_OTA_PAYLOAD_BIN if secondary_payload else
117 self.OTA_PAYLOAD_BIN)
118 payload_info = otazip.getinfo(payload_entry)
Kelvin Zhangaba70ab2020-08-04 10:32:59 -0400119
120 if payload_info.compress_type != 0:
121 logging.error(
Kelvin Zhang07676f52020-12-01 10:45:09 -0500122 "Expected payload to be uncompressed, got compression method %d",
Kelvin Zhangaba70ab2020-08-04 10:32:59 -0400123 payload_info.compress_type)
124 # Don't use len(payload_info.extra). Because that returns size of extra
125 # fields in central directory. We need to look at local file directory,
126 # as these two might have different sizes.
127 with open(otafilename, "rb") as fp:
128 fp.seek(payload_info.header_offset)
129 data = fp.read(zipfile.sizeFileHeader)
130 fheader = struct.unpack(zipfile.structFileHeader, data)
131 # Last two fields of local file header are filename length and
132 # extra length
133 filename_len = fheader[-2]
134 extra_len = fheader[-1]
135 self.offset = payload_info.header_offset
136 self.offset += zipfile.sizeFileHeader
137 self.offset += filename_len + extra_len
138 self.size = payload_info.file_size
139 fp.seek(self.offset)
140 payload_header = fp.read(4)
141 if payload_header != self.PAYLOAD_MAGIC_HEADER:
142 logging.warning(
Kelvin Zhang07676f52020-12-01 10:45:09 -0500143 "Invalid header, expected %s, got %s."
Kelvin Zhangaba70ab2020-08-04 10:32:59 -0400144 "Either the offset is not correct, or payload is corrupted",
145 binascii.hexlify(self.PAYLOAD_MAGIC_HEADER),
Kelvin Zhang07676f52020-12-01 10:45:09 -0500146 binascii.hexlify(payload_header))
Tianjie Xu3f9be772019-11-02 18:31:50 -0700147
148 property_entry = (self.SECONDARY_OTA_PAYLOAD_PROPERTIES_TXT if
149 secondary_payload else self.OTA_PAYLOAD_PROPERTIES_TXT)
150 self.properties = otazip.read(property_entry)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700151
152
153class UpdateHandler(BaseHTTPServer.BaseHTTPRequestHandler):
154 """A HTTPServer that supports single-range requests.
155
156 Attributes:
157 serving_payload: path to the only payload file we are serving.
Sen Jiang3b15b592017-09-26 18:21:04 -0700158 serving_range: the start offset and size tuple of the payload.
Alex Deymo6751bbe2017-03-21 11:20:02 -0700159 """
160
161 @staticmethod
Sen Jiang10485592017-08-15 18:20:24 -0700162 def _parse_range(range_str, file_size):
Alex Deymo6751bbe2017-03-21 11:20:02 -0700163 """Parse an HTTP range string.
164
165 Args:
166 range_str: HTTP Range header in the request, not including "Header:".
167 file_size: total size of the serving file.
168
169 Returns:
170 A tuple (start_range, end_range) with the range of bytes requested.
171 """
172 start_range = 0
173 end_range = file_size
174
175 if range_str:
176 range_str = range_str.split('=', 1)[1]
177 s, e = range_str.split('-', 1)
178 if s:
179 start_range = int(s)
180 if e:
181 end_range = int(e) + 1
182 elif e:
183 if int(e) < file_size:
184 start_range = file_size - int(e)
185 return start_range, end_range
186
Alex Deymo6751bbe2017-03-21 11:20:02 -0700187 def do_GET(self): # pylint: disable=invalid-name
188 """Reply with the requested payload file."""
189 if self.path != '/payload':
190 self.send_error(404, 'Unknown request')
191 return
192
193 if not self.serving_payload:
194 self.send_error(500, 'No serving payload set')
195 return
196
197 try:
198 f = open(self.serving_payload, 'rb')
199 except IOError:
200 self.send_error(404, 'File not found')
201 return
202 # Handle the range request.
203 if 'Range' in self.headers:
204 self.send_response(206)
205 else:
206 self.send_response(200)
207
Sen Jiang3b15b592017-09-26 18:21:04 -0700208 serving_start, serving_size = self.serving_range
Sen Jiang10485592017-08-15 18:20:24 -0700209 start_range, end_range = self._parse_range(self.headers.get('range'),
Sen Jiang3b15b592017-09-26 18:21:04 -0700210 serving_size)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700211 logging.info('Serving request for %s from %s [%d, %d) length: %d',
Sen Jiang3b15b592017-09-26 18:21:04 -0700212 self.path, self.serving_payload, serving_start + start_range,
213 serving_start + end_range, end_range - start_range)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700214
215 self.send_header('Accept-Ranges', 'bytes')
216 self.send_header('Content-Range',
217 'bytes ' + str(start_range) + '-' + str(end_range - 1) +
218 '/' + str(end_range - start_range))
219 self.send_header('Content-Length', end_range - start_range)
220
Sen Jiang3b15b592017-09-26 18:21:04 -0700221 stat = os.fstat(f.fileno())
Alex Deymo6751bbe2017-03-21 11:20:02 -0700222 self.send_header('Last-Modified', self.date_time_string(stat.st_mtime))
223 self.send_header('Content-type', 'application/octet-stream')
224 self.end_headers()
225
Sen Jiang3b15b592017-09-26 18:21:04 -0700226 f.seek(serving_start + start_range)
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700227 CopyFileObjLength(f, self.wfile, copy_length=end_range -
228 start_range, speed_limit=self.speed_limit)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700229
Sen Jianga1784b72017-08-09 17:42:36 -0700230
Alex Deymo6751bbe2017-03-21 11:20:02 -0700231class ServerThread(threading.Thread):
232 """A thread for serving HTTP requests."""
233
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700234 def __init__(self, ota_filename, serving_range, speed_limit):
Alex Deymo6751bbe2017-03-21 11:20:02 -0700235 threading.Thread.__init__(self)
Sen Jiang3b15b592017-09-26 18:21:04 -0700236 # serving_payload and serving_range are class attributes and the
237 # UpdateHandler class is instantiated with every request.
Alex Deymo6751bbe2017-03-21 11:20:02 -0700238 UpdateHandler.serving_payload = ota_filename
Sen Jiang3b15b592017-09-26 18:21:04 -0700239 UpdateHandler.serving_range = serving_range
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700240 UpdateHandler.speed_limit = speed_limit
Alex Deymo6751bbe2017-03-21 11:20:02 -0700241 self._httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 0), UpdateHandler)
242 self.port = self._httpd.server_port
243
244 def run(self):
245 try:
246 self._httpd.serve_forever()
247 except (KeyboardInterrupt, socket.error):
248 pass
249 logging.info('Server Terminated')
250
251 def StopServer(self):
Kelvin Zhang4b883ea2020-10-08 13:26:44 -0400252 self._httpd.shutdown()
Alex Deymo6751bbe2017-03-21 11:20:02 -0700253 self._httpd.socket.close()
254
255
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700256def StartServer(ota_filename, serving_range, speed_limit):
257 t = ServerThread(ota_filename, serving_range, speed_limit)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700258 t.start()
259 return t
260
261
Tianjie Xu3f9be772019-11-02 18:31:50 -0700262def AndroidUpdateCommand(ota_filename, secondary, payload_url, extra_headers):
Alex Deymo6751bbe2017-03-21 11:20:02 -0700263 """Return the command to run to start the update in the Android device."""
Tianjie Xu3f9be772019-11-02 18:31:50 -0700264 ota = AndroidOTAPackage(ota_filename, secondary)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700265 headers = ota.properties
Kelvin Zhang4b883ea2020-10-08 13:26:44 -0400266 headers += b'USER_AGENT=Dalvik (something, something)\n'
267 headers += b'NETWORK_ID=0\n'
268 headers += extra_headers.encode()
Alex Deymo6751bbe2017-03-21 11:20:02 -0700269
270 return ['update_engine_client', '--update', '--follow',
271 '--payload=%s' % payload_url, '--offset=%d' % ota.offset,
Kelvin Zhang4b883ea2020-10-08 13:26:44 -0400272 '--size=%d' % ota.size, '--headers="%s"' % headers.decode()]
Alex Deymo6751bbe2017-03-21 11:20:02 -0700273
274
275class AdbHost(object):
276 """Represents a device connected via ADB."""
277
278 def __init__(self, device_serial=None):
279 """Construct an instance.
280
281 Args:
282 device_serial: options string serial number of attached device.
283 """
284 self._device_serial = device_serial
285 self._command_prefix = ['adb']
286 if self._device_serial:
287 self._command_prefix += ['-s', self._device_serial]
288
Kelvin Zhang3a188952021-04-13 12:44:45 -0400289 def adb(self, command, timeout_seconds: float = None):
Alex Deymo6751bbe2017-03-21 11:20:02 -0700290 """Run an ADB command like "adb push".
291
292 Args:
293 command: list of strings containing command and arguments to run
294
295 Returns:
296 the program's return code.
297
298 Raises:
299 subprocess.CalledProcessError on command exit != 0.
300 """
301 command = self._command_prefix + command
302 logging.info('Running: %s', ' '.join(str(x) for x in command))
303 p = subprocess.Popen(command, universal_newlines=True)
Kelvin Zhang3a188952021-04-13 12:44:45 -0400304 p.wait(timeout_seconds)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700305 return p.returncode
306
Sen Jianga1784b72017-08-09 17:42:36 -0700307 def adb_output(self, command):
308 """Run an ADB command like "adb push" and return the output.
309
310 Args:
311 command: list of strings containing command and arguments to run
312
313 Returns:
314 the program's output as a string.
315
316 Raises:
317 subprocess.CalledProcessError on command exit != 0.
318 """
319 command = self._command_prefix + command
320 logging.info('Running: %s', ' '.join(str(x) for x in command))
321 return subprocess.check_output(command, universal_newlines=True)
322
Alex Deymo6751bbe2017-03-21 11:20:02 -0700323
Kelvin Zhang63b39112021-03-05 12:31:38 -0500324def PushMetadata(dut, otafile, metadata_path):
Kelvin Zhang9a2d9a32023-11-28 09:42:16 -0800325 header_format = ">4sQQL"
Kelvin Zhang63b39112021-03-05 12:31:38 -0500326 with tempfile.TemporaryDirectory() as tmpdir:
327 with zipfile.ZipFile(otafile, "r") as zfp:
328 extracted_path = os.path.join(tmpdir, "payload.bin")
329 with zfp.open("payload.bin") as payload_fp, \
330 open(extracted_path, "wb") as output_fp:
Kelvin Zhang9a2d9a32023-11-28 09:42:16 -0800331 # Only extract the first |data_offset| bytes from the payload.
332 # This is because allocateSpaceForPayload only needs to see
333 # the manifest, not the entire payload.
334 # Extracting the entire payload works, but is slow for full
335 # OTA.
336 header = payload_fp.read(struct.calcsize(header_format))
337 magic, major_version, manifest_size, metadata_signature_size = struct.unpack(header_format, header)
338 assert magic == b"CrAU", "Invalid magic {}, expected CrAU".format(magic)
339 assert major_version == 2, "Invalid major version {}, only version 2 is supported".format(major_version)
340 output_fp.write(header)
341
342 shutil.copyfileobj(payload_fp, output_fp, manifest_size + metadata_signature_size)
343
Kelvin Zhang63b39112021-03-05 12:31:38 -0500344
345 return dut.adb([
346 "push",
347 extracted_path,
348 metadata_path
349 ]) == 0
350
351
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700352def ParseSpeedLimit(arg: str) -> int:
353 arg = arg.strip().upper()
354 if not re.match(r"\d+[KkMmGgTt]?", arg):
355 raise argparse.ArgumentError(
356 "Wrong speed limit format, expected format is number followed by unit, such as 10K, 5m, 3G (case insensitive)")
357 unit = 1
358 if arg[-1].isalpha():
359 if arg[-1] == "K":
360 unit = 1024
361 elif arg[-1] == "M":
362 unit = 1024 * 1024
363 elif arg[-1] == "G":
364 unit = 1024 * 1024 * 1024
365 elif arg[-1] == "T":
366 unit = 1024 * 1024 * 1024 * 1024
367 else:
368 raise argparse.ArgumentError(
369 f"Unsupported unit for download speed: {arg[-1]}, supported units are K,M,G,T (case insensitive)")
370 return int(float(arg[:-1]) * unit)
371
372
Alex Deymo6751bbe2017-03-21 11:20:02 -0700373def main():
374 parser = argparse.ArgumentParser(description='Android A/B OTA helper.')
Sen Jiang3b15b592017-09-26 18:21:04 -0700375 parser.add_argument('otafile', metavar='PAYLOAD', type=str,
376 help='the OTA package file (a .zip file) or raw payload \
377 if device uses Omaha.')
Alex Deymo6751bbe2017-03-21 11:20:02 -0700378 parser.add_argument('--file', action='store_true',
379 help='Push the file to the device before updating.')
380 parser.add_argument('--no-push', action='store_true',
381 help='Skip the "push" command when using --file')
382 parser.add_argument('-s', type=str, default='', metavar='DEVICE',
383 help='The specific device to use.')
384 parser.add_argument('--no-verbose', action='store_true',
385 help='Less verbose output')
Sen Jianga1784b72017-08-09 17:42:36 -0700386 parser.add_argument('--public-key', type=str, default='',
387 help='Override the public key used to verify payload.')
Sen Jiang6fbfd7d2017-10-31 16:16:56 -0700388 parser.add_argument('--extra-headers', type=str, default='',
389 help='Extra headers to pass to the device.')
Tianjie Xu3f9be772019-11-02 18:31:50 -0700390 parser.add_argument('--secondary', action='store_true',
391 help='Update with the secondary payload in the package.')
Kelvin Zhang8212f532020-11-13 16:00:00 -0500392 parser.add_argument('--no-slot-switch', action='store_true',
393 help='Do not perform slot switch after the update.')
Kelvin Zhangbec0f072021-03-31 16:09:00 -0400394 parser.add_argument('--no-postinstall', action='store_true',
395 help='Do not execute postinstall scripts after the update.')
Kelvin Zhangffd21442021-04-14 09:09:41 -0400396 parser.add_argument('--allocate-only', action='store_true',
Kelvin Zhang51aad992021-02-19 14:46:28 -0500397 help='Allocate space for this OTA, instead of actually \
398 applying the OTA.')
Kelvin Zhangffd21442021-04-14 09:09:41 -0400399 parser.add_argument('--verify-only', action='store_true',
Kelvin Zhang63b39112021-03-05 12:31:38 -0500400 help='Verify metadata then exit, instead of applying the OTA.')
Kelvin Zhangffd21442021-04-14 09:09:41 -0400401 parser.add_argument('--no-care-map', action='store_true',
Kelvin Zhang5bd46222021-03-02 12:36:14 -0500402 help='Do not push care_map.pb to device.')
Kelvin Zhangc56afa32021-08-13 12:32:31 -0700403 parser.add_argument('--perform-slot-switch', action='store_true',
404 help='Perform slot switch for this OTA package')
405 parser.add_argument('--perform-reset-slot-switch', action='store_true',
406 help='Perform reset slot switch for this OTA package')
Kelvin Zhang2451a302022-03-23 19:18:35 -0700407 parser.add_argument('--wipe-user-data', action='store_true',
408 help='Wipe userdata after installing OTA')
Kelvin Zhanga7407b52023-03-13 15:05:14 -0700409 parser.add_argument('--vabc-none', action='store_true',
410 help='Set Virtual AB Compression algorithm to none, but still use Android COW format')
Daniel Zheng9fc62b82023-03-24 22:57:20 +0000411 parser.add_argument('--disable-vabc', action='store_true',
412 help='Option to enable or disable vabc. If set to false, will fall back on A/B')
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800413 parser.add_argument('--enable-threading', action='store_true',
414 help='Enable multi-threaded compression for VABC')
415 parser.add_argument('--batched-writes', action='store_true',
416 help='Enable batched writes for VABC')
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700417 parser.add_argument('--speed-limit', type=str,
418 help='Speed limit for serving payloads over HTTP. For '
419 'example: 10K, 5m, 1G, input is case insensitive')
420
Alex Deymo6751bbe2017-03-21 11:20:02 -0700421 args = parser.parse_args()
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700422 if args.speed_limit:
423 args.speed_limit = ParseSpeedLimit(args.speed_limit)
424
Alex Deymo6751bbe2017-03-21 11:20:02 -0700425 logging.basicConfig(
426 level=logging.WARNING if args.no_verbose else logging.INFO)
427
Nikita Ioffe3a327e62021-06-30 16:05:09 +0100428 start_time = time.perf_counter()
429
Alex Deymo6751bbe2017-03-21 11:20:02 -0700430 dut = AdbHost(args.s)
431
432 server_thread = None
433 # List of commands to execute on exit.
434 finalize_cmds = []
435 # Commands to execute when canceling an update.
436 cancel_cmd = ['shell', 'su', '0', 'update_engine_client', '--cancel']
437 # List of commands to perform the update.
438 cmds = []
439
Sen Jianga1784b72017-08-09 17:42:36 -0700440 help_cmd = ['shell', 'su', '0', 'update_engine_client', '--help']
Sen Jianga1784b72017-08-09 17:42:36 -0700441
Kelvin Zhang63b39112021-03-05 12:31:38 -0500442 metadata_path = "/data/ota_package/metadata"
Kelvin Zhang51aad992021-02-19 14:46:28 -0500443 if args.allocate_only:
Kelvin Zhang027eb382023-04-27 20:44:45 -0700444 with zipfile.ZipFile(args.otafile, "r") as zfp:
445 headers = zfp.read("payload_properties.txt").decode()
Kelvin Zhang63b39112021-03-05 12:31:38 -0500446 if PushMetadata(dut, args.otafile, metadata_path):
447 dut.adb([
448 "shell", "update_engine_client", "--allocate",
Kelvin Zhang027eb382023-04-27 20:44:45 -0700449 "--metadata={} --headers='{}'".format(metadata_path, headers)])
Kelvin Zhang63b39112021-03-05 12:31:38 -0500450 # Return 0, as we are executing ADB commands here, no work needed after
451 # this point
452 return 0
453 if args.verify_only:
454 if PushMetadata(dut, args.otafile, metadata_path):
455 dut.adb([
456 "shell", "update_engine_client", "--verify",
457 "--metadata={}".format(metadata_path)])
Kelvin Zhang51aad992021-02-19 14:46:28 -0500458 # Return 0, as we are executing ADB commands here, no work needed after
459 # this point
460 return 0
Kelvin Zhangc56afa32021-08-13 12:32:31 -0700461 if args.perform_slot_switch:
462 assert PushMetadata(dut, args.otafile, metadata_path)
463 dut.adb(["shell", "update_engine_client",
464 "--switch_slot=true", "--metadata={}".format(metadata_path), "--follow"])
465 return 0
466 if args.perform_reset_slot_switch:
467 assert PushMetadata(dut, args.otafile, metadata_path)
468 dut.adb(["shell", "update_engine_client",
469 "--switch_slot=false", "--metadata={}".format(metadata_path)])
470 return 0
Kelvin Zhang51aad992021-02-19 14:46:28 -0500471
Kelvin Zhang8212f532020-11-13 16:00:00 -0500472 if args.no_slot_switch:
473 args.extra_headers += "\nSWITCH_SLOT_ON_REBOOT=0"
Kelvin Zhangbec0f072021-03-31 16:09:00 -0400474 if args.no_postinstall:
475 args.extra_headers += "\nRUN_POST_INSTALL=0"
Kelvin Zhang2451a302022-03-23 19:18:35 -0700476 if args.wipe_user_data:
477 args.extra_headers += "\nPOWERWASH=1"
Kelvin Zhanga7407b52023-03-13 15:05:14 -0700478 if args.vabc_none:
479 args.extra_headers += "\nVABC_NONE=1"
Daniel Zheng9fc62b82023-03-24 22:57:20 +0000480 if args.disable_vabc:
481 args.extra_headers += "\nDISABLE_VABC=1"
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800482 if args.enable_threading:
483 args.extra_headers += "\nENABLE_THREADING=1"
484 if args.batched_writes:
485 args.extra_headers += "\nBATCHED_WRITES=1"
Kelvin Zhang8212f532020-11-13 16:00:00 -0500486
Kelvin Zhang5bd46222021-03-02 12:36:14 -0500487 with zipfile.ZipFile(args.otafile) as zfp:
488 CARE_MAP_ENTRY_NAME = "care_map.pb"
489 if CARE_MAP_ENTRY_NAME in zfp.namelist() and not args.no_care_map:
490 # Need root permission to push to /data
491 dut.adb(["root"])
Kelvin Zhang472d5612021-03-05 12:32:19 -0500492 with tempfile.NamedTemporaryFile() as care_map_fp:
Kelvin Zhang5bd46222021-03-02 12:36:14 -0500493 care_map_fp.write(zfp.read(CARE_MAP_ENTRY_NAME))
494 care_map_fp.flush()
495 dut.adb(["push", care_map_fp.name,
Kelvin Zhangffd21442021-04-14 09:09:41 -0400496 "/data/ota_package/" + CARE_MAP_ENTRY_NAME])
Kelvin Zhang5bd46222021-03-02 12:36:14 -0500497
Alex Deymo6751bbe2017-03-21 11:20:02 -0700498 if args.file:
499 # Update via pushing a file to /data.
500 device_ota_file = os.path.join(OTA_PACKAGE_PATH, 'debug.zip')
501 payload_url = 'file://' + device_ota_file
502 if not args.no_push:
Tao Baoabb45a52017-10-25 11:13:03 -0700503 data_local_tmp_file = '/data/local/tmp/debug.zip'
504 cmds.append(['push', args.otafile, data_local_tmp_file])
505 cmds.append(['shell', 'su', '0', 'mv', data_local_tmp_file,
506 device_ota_file])
507 cmds.append(['shell', 'su', '0', 'chcon',
508 'u:object_r:ota_package_file:s0', device_ota_file])
Alex Deymo6751bbe2017-03-21 11:20:02 -0700509 cmds.append(['shell', 'su', '0', 'chown', 'system:cache', device_ota_file])
510 cmds.append(['shell', 'su', '0', 'chmod', '0660', device_ota_file])
511 else:
512 # Update via sending the payload over the network with an "adb reverse"
513 # command.
Sen Jianga1784b72017-08-09 17:42:36 -0700514 payload_url = 'http://127.0.0.1:%d/payload' % DEVICE_PORT
Kelvin Zhang033e1732023-09-11 16:32:11 -0700515 serving_range = (0, os.stat(args.otafile).st_size)
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700516 server_thread = StartServer(args.otafile, serving_range, args.speed_limit)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700517 cmds.append(
Sen Jianga1784b72017-08-09 17:42:36 -0700518 ['reverse', 'tcp:%d' % DEVICE_PORT, 'tcp:%d' % server_thread.port])
519 finalize_cmds.append(['reverse', '--remove', 'tcp:%d' % DEVICE_PORT])
520
521 if args.public_key:
522 payload_key_dir = os.path.dirname(PAYLOAD_KEY_PATH)
523 cmds.append(
524 ['shell', 'su', '0', 'mount', '-t', 'tmpfs', 'tmpfs', payload_key_dir])
525 # Allow adb push to payload_key_dir
526 cmds.append(['shell', 'su', '0', 'chcon', 'u:object_r:shell_data_file:s0',
527 payload_key_dir])
528 cmds.append(['push', args.public_key, PAYLOAD_KEY_PATH])
529 # Allow update_engine to read it.
530 cmds.append(['shell', 'su', '0', 'chcon', '-R', 'u:object_r:system_file:s0',
531 payload_key_dir])
532 finalize_cmds.append(['shell', 'su', '0', 'umount', payload_key_dir])
Alex Deymo6751bbe2017-03-21 11:20:02 -0700533
534 try:
535 # The main update command using the configured payload_url.
Kelvin Zhang033e1732023-09-11 16:32:11 -0700536 update_cmd = AndroidUpdateCommand(args.otafile, args.secondary,
Tianjie Xu3f9be772019-11-02 18:31:50 -0700537 payload_url, args.extra_headers)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700538 cmds.append(['shell', 'su', '0'] + update_cmd)
539
540 for cmd in cmds:
541 dut.adb(cmd)
542 except KeyboardInterrupt:
543 dut.adb(cancel_cmd)
544 finally:
545 if server_thread:
546 server_thread.StopServer()
547 for cmd in finalize_cmds:
Kelvin Zhang3a188952021-04-13 12:44:45 -0400548 dut.adb(cmd, 5)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700549
Nikita Ioffe3a327e62021-06-30 16:05:09 +0100550 logging.info('Update took %.3f seconds', (time.perf_counter() - start_time))
Alex Deymo6751bbe2017-03-21 11:20:02 -0700551 return 0
552
Andrew Lassalle165843c2019-11-05 13:30:34 -0800553
Alex Deymo6751bbe2017-03-21 11:20:02 -0700554if __name__ == '__main__':
555 sys.exit(main())