blob: 8f4e583ab17976554784afb78850995531f5b43d [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
38
Andrew Lassalle165843c2019-11-05 13:30:34 -080039from six.moves import BaseHTTPServer
40
Sen Jianga1784b72017-08-09 17:42:36 -070041import update_payload.payload
42
Alex Deymo6751bbe2017-03-21 11:20:02 -070043
44# The path used to store the OTA package when applying the package from a file.
45OTA_PACKAGE_PATH = '/data/ota_package'
46
Sen Jianga1784b72017-08-09 17:42:36 -070047# The path to the payload public key on the device.
48PAYLOAD_KEY_PATH = '/etc/update_engine/update-payload-key.pub.pem'
49
50# The port on the device that update_engine should connect to.
51DEVICE_PORT = 1234
Alex Deymo6751bbe2017-03-21 11:20:02 -070052
Andrew Lassalle165843c2019-11-05 13:30:34 -080053
Kelvin Zhang46a860c2022-09-28 19:42:39 -070054def CopyFileObjLength(fsrc, fdst, buffer_size=128 * 1024, copy_length=None, speed_limit=None):
Alex Deymo6751bbe2017-03-21 11:20:02 -070055 """Copy from a file object to another.
56
57 This function is similar to shutil.copyfileobj except that it allows to copy
58 less than the full source file.
59
60 Args:
61 fsrc: source file object where to read from.
62 fdst: destination file object where to write to.
63 buffer_size: size of the copy buffer in memory.
64 copy_length: maximum number of bytes to copy, or None to copy everything.
Kelvin Zhang46a860c2022-09-28 19:42:39 -070065 speed_limit: upper limit for copying speed, in bytes per second.
Alex Deymo6751bbe2017-03-21 11:20:02 -070066
67 Returns:
68 the number of bytes copied.
69 """
Kelvin Zhang46a860c2022-09-28 19:42:39 -070070 # If buffer size significantly bigger than speed limit
71 # traffic would seem extremely spiky to the client.
72 if speed_limit:
73 print(f"Applying speed limit: {speed_limit}")
74 buffer_size = min(speed_limit//32, buffer_size)
75
76 start_time = time.time()
Alex Deymo6751bbe2017-03-21 11:20:02 -070077 copied = 0
78 while True:
79 chunk_size = buffer_size
80 if copy_length is not None:
81 chunk_size = min(chunk_size, copy_length - copied)
82 if not chunk_size:
83 break
84 buf = fsrc.read(chunk_size)
85 if not buf:
86 break
Kelvin Zhang46a860c2022-09-28 19:42:39 -070087 if speed_limit:
88 expected_duration = copied/speed_limit
89 actual_duration = time.time() - start_time
90 if actual_duration < expected_duration:
91 time.sleep(expected_duration-actual_duration)
Alex Deymo6751bbe2017-03-21 11:20:02 -070092 fdst.write(buf)
93 copied += len(buf)
94 return copied
95
96
97class AndroidOTAPackage(object):
98 """Android update payload using the .zip format.
99
100 Android OTA packages traditionally used a .zip file to store the payload. When
101 applying A/B updates over the network, a payload binary is stored RAW inside
102 this .zip file which is used by update_engine to apply the payload. To do
103 this, an offset and size inside the .zip file are provided.
104 """
105
106 # Android OTA package file paths.
107 OTA_PAYLOAD_BIN = 'payload.bin'
108 OTA_PAYLOAD_PROPERTIES_TXT = 'payload_properties.txt'
Tianjie Xu3f9be772019-11-02 18:31:50 -0700109 SECONDARY_OTA_PAYLOAD_BIN = 'secondary/payload.bin'
110 SECONDARY_OTA_PAYLOAD_PROPERTIES_TXT = 'secondary/payload_properties.txt'
Kelvin Zhangaba70ab2020-08-04 10:32:59 -0400111 PAYLOAD_MAGIC_HEADER = b'CrAU'
Alex Deymo6751bbe2017-03-21 11:20:02 -0700112
Tianjie Xu3f9be772019-11-02 18:31:50 -0700113 def __init__(self, otafilename, secondary_payload=False):
Alex Deymo6751bbe2017-03-21 11:20:02 -0700114 self.otafilename = otafilename
115
116 otazip = zipfile.ZipFile(otafilename, 'r')
Tianjie Xu3f9be772019-11-02 18:31:50 -0700117 payload_entry = (self.SECONDARY_OTA_PAYLOAD_BIN if secondary_payload else
118 self.OTA_PAYLOAD_BIN)
119 payload_info = otazip.getinfo(payload_entry)
Kelvin Zhangaba70ab2020-08-04 10:32:59 -0400120
121 if payload_info.compress_type != 0:
122 logging.error(
Kelvin Zhang07676f52020-12-01 10:45:09 -0500123 "Expected payload to be uncompressed, got compression method %d",
Kelvin Zhangaba70ab2020-08-04 10:32:59 -0400124 payload_info.compress_type)
125 # Don't use len(payload_info.extra). Because that returns size of extra
126 # fields in central directory. We need to look at local file directory,
127 # as these two might have different sizes.
128 with open(otafilename, "rb") as fp:
129 fp.seek(payload_info.header_offset)
130 data = fp.read(zipfile.sizeFileHeader)
131 fheader = struct.unpack(zipfile.structFileHeader, data)
132 # Last two fields of local file header are filename length and
133 # extra length
134 filename_len = fheader[-2]
135 extra_len = fheader[-1]
136 self.offset = payload_info.header_offset
137 self.offset += zipfile.sizeFileHeader
138 self.offset += filename_len + extra_len
139 self.size = payload_info.file_size
140 fp.seek(self.offset)
141 payload_header = fp.read(4)
142 if payload_header != self.PAYLOAD_MAGIC_HEADER:
143 logging.warning(
Kelvin Zhang07676f52020-12-01 10:45:09 -0500144 "Invalid header, expected %s, got %s."
Kelvin Zhangaba70ab2020-08-04 10:32:59 -0400145 "Either the offset is not correct, or payload is corrupted",
146 binascii.hexlify(self.PAYLOAD_MAGIC_HEADER),
Kelvin Zhang07676f52020-12-01 10:45:09 -0500147 binascii.hexlify(payload_header))
Tianjie Xu3f9be772019-11-02 18:31:50 -0700148
149 property_entry = (self.SECONDARY_OTA_PAYLOAD_PROPERTIES_TXT if
150 secondary_payload else self.OTA_PAYLOAD_PROPERTIES_TXT)
151 self.properties = otazip.read(property_entry)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700152
153
154class UpdateHandler(BaseHTTPServer.BaseHTTPRequestHandler):
155 """A HTTPServer that supports single-range requests.
156
157 Attributes:
158 serving_payload: path to the only payload file we are serving.
Sen Jiang3b15b592017-09-26 18:21:04 -0700159 serving_range: the start offset and size tuple of the payload.
Alex Deymo6751bbe2017-03-21 11:20:02 -0700160 """
161
162 @staticmethod
Sen Jiang10485592017-08-15 18:20:24 -0700163 def _parse_range(range_str, file_size):
Alex Deymo6751bbe2017-03-21 11:20:02 -0700164 """Parse an HTTP range string.
165
166 Args:
167 range_str: HTTP Range header in the request, not including "Header:".
168 file_size: total size of the serving file.
169
170 Returns:
171 A tuple (start_range, end_range) with the range of bytes requested.
172 """
173 start_range = 0
174 end_range = file_size
175
176 if range_str:
177 range_str = range_str.split('=', 1)[1]
178 s, e = range_str.split('-', 1)
179 if s:
180 start_range = int(s)
181 if e:
182 end_range = int(e) + 1
183 elif e:
184 if int(e) < file_size:
185 start_range = file_size - int(e)
186 return start_range, end_range
187
Alex Deymo6751bbe2017-03-21 11:20:02 -0700188 def do_GET(self): # pylint: disable=invalid-name
189 """Reply with the requested payload file."""
190 if self.path != '/payload':
191 self.send_error(404, 'Unknown request')
192 return
193
194 if not self.serving_payload:
195 self.send_error(500, 'No serving payload set')
196 return
197
198 try:
199 f = open(self.serving_payload, 'rb')
200 except IOError:
201 self.send_error(404, 'File not found')
202 return
203 # Handle the range request.
204 if 'Range' in self.headers:
205 self.send_response(206)
206 else:
207 self.send_response(200)
208
Sen Jiang3b15b592017-09-26 18:21:04 -0700209 serving_start, serving_size = self.serving_range
Sen Jiang10485592017-08-15 18:20:24 -0700210 start_range, end_range = self._parse_range(self.headers.get('range'),
Sen Jiang3b15b592017-09-26 18:21:04 -0700211 serving_size)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700212 logging.info('Serving request for %s from %s [%d, %d) length: %d',
Sen Jiang3b15b592017-09-26 18:21:04 -0700213 self.path, self.serving_payload, serving_start + start_range,
214 serving_start + end_range, end_range - start_range)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700215
216 self.send_header('Accept-Ranges', 'bytes')
217 self.send_header('Content-Range',
218 'bytes ' + str(start_range) + '-' + str(end_range - 1) +
219 '/' + str(end_range - start_range))
220 self.send_header('Content-Length', end_range - start_range)
221
Sen Jiang3b15b592017-09-26 18:21:04 -0700222 stat = os.fstat(f.fileno())
Alex Deymo6751bbe2017-03-21 11:20:02 -0700223 self.send_header('Last-Modified', self.date_time_string(stat.st_mtime))
224 self.send_header('Content-type', 'application/octet-stream')
225 self.end_headers()
226
Sen Jiang3b15b592017-09-26 18:21:04 -0700227 f.seek(serving_start + start_range)
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700228 CopyFileObjLength(f, self.wfile, copy_length=end_range -
229 start_range, speed_limit=self.speed_limit)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700230
Sen Jianga1784b72017-08-09 17:42:36 -0700231 def do_POST(self): # pylint: disable=invalid-name
232 """Reply with the omaha response xml."""
233 if self.path != '/update':
234 self.send_error(404, 'Unknown request')
235 return
236
237 if not self.serving_payload:
238 self.send_error(500, 'No serving payload set')
239 return
240
241 try:
242 f = open(self.serving_payload, 'rb')
243 except IOError:
244 self.send_error(404, 'File not found')
245 return
246
Sen Jiang144f9f82017-09-26 15:49:45 -0700247 content_length = int(self.headers.getheader('Content-Length'))
248 request_xml = self.rfile.read(content_length)
249 xml_root = xml.etree.ElementTree.fromstring(request_xml)
250 appid = None
251 for app in xml_root.iter('app'):
252 if 'appid' in app.attrib:
253 appid = app.attrib['appid']
254 break
255 if not appid:
256 self.send_error(400, 'No appid in Omaha request')
257 return
258
Sen Jianga1784b72017-08-09 17:42:36 -0700259 self.send_response(200)
260 self.send_header("Content-type", "text/xml")
261 self.end_headers()
262
Sen Jiang3b15b592017-09-26 18:21:04 -0700263 serving_start, serving_size = self.serving_range
264 sha256 = hashlib.sha256()
265 f.seek(serving_start)
266 bytes_to_hash = serving_size
267 while bytes_to_hash:
268 buf = f.read(min(bytes_to_hash, 1024 * 1024))
269 if not buf:
270 self.send_error(500, 'Payload too small')
271 return
272 sha256.update(buf)
273 bytes_to_hash -= len(buf)
274
275 payload = update_payload.Payload(f, payload_file_offset=serving_start)
Sen Jianga1784b72017-08-09 17:42:36 -0700276 payload.Init()
277
Sen Jiang144f9f82017-09-26 15:49:45 -0700278 response_xml = '''
Sen Jianga1784b72017-08-09 17:42:36 -0700279 <?xml version="1.0" encoding="UTF-8"?>
280 <response protocol="3.0">
Sen Jiang144f9f82017-09-26 15:49:45 -0700281 <app appid="{appid}">
Sen Jianga1784b72017-08-09 17:42:36 -0700282 <updatecheck status="ok">
283 <urls>
Sen Jiang144f9f82017-09-26 15:49:45 -0700284 <url codebase="http://127.0.0.1:{port}/"/>
Sen Jianga1784b72017-08-09 17:42:36 -0700285 </urls>
286 <manifest version="0.0.0.1">
287 <actions>
288 <action event="install" run="payload"/>
Sen Jiang144f9f82017-09-26 15:49:45 -0700289 <action event="postinstall" MetadataSize="{metadata_size}"/>
Sen Jianga1784b72017-08-09 17:42:36 -0700290 </actions>
291 <packages>
Sen Jiang144f9f82017-09-26 15:49:45 -0700292 <package hash_sha256="{payload_hash}" name="payload" size="{payload_size}"/>
Sen Jianga1784b72017-08-09 17:42:36 -0700293 </packages>
294 </manifest>
295 </updatecheck>
296 </app>
297 </response>
Sen Jiang144f9f82017-09-26 15:49:45 -0700298 '''.format(appid=appid, port=DEVICE_PORT,
Sen Jiang3b15b592017-09-26 18:21:04 -0700299 metadata_size=payload.metadata_size,
300 payload_hash=sha256.hexdigest(),
301 payload_size=serving_size)
Sen Jiang144f9f82017-09-26 15:49:45 -0700302 self.wfile.write(response_xml.strip())
Sen Jianga1784b72017-08-09 17:42:36 -0700303 return
304
305
Alex Deymo6751bbe2017-03-21 11:20:02 -0700306class ServerThread(threading.Thread):
307 """A thread for serving HTTP requests."""
308
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700309 def __init__(self, ota_filename, serving_range, speed_limit):
Alex Deymo6751bbe2017-03-21 11:20:02 -0700310 threading.Thread.__init__(self)
Sen Jiang3b15b592017-09-26 18:21:04 -0700311 # serving_payload and serving_range are class attributes and the
312 # UpdateHandler class is instantiated with every request.
Alex Deymo6751bbe2017-03-21 11:20:02 -0700313 UpdateHandler.serving_payload = ota_filename
Sen Jiang3b15b592017-09-26 18:21:04 -0700314 UpdateHandler.serving_range = serving_range
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700315 UpdateHandler.speed_limit = speed_limit
Alex Deymo6751bbe2017-03-21 11:20:02 -0700316 self._httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 0), UpdateHandler)
317 self.port = self._httpd.server_port
318
319 def run(self):
320 try:
321 self._httpd.serve_forever()
322 except (KeyboardInterrupt, socket.error):
323 pass
324 logging.info('Server Terminated')
325
326 def StopServer(self):
Kelvin Zhang4b883ea2020-10-08 13:26:44 -0400327 self._httpd.shutdown()
Alex Deymo6751bbe2017-03-21 11:20:02 -0700328 self._httpd.socket.close()
329
330
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700331def StartServer(ota_filename, serving_range, speed_limit):
332 t = ServerThread(ota_filename, serving_range, speed_limit)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700333 t.start()
334 return t
335
336
Tianjie Xu3f9be772019-11-02 18:31:50 -0700337def AndroidUpdateCommand(ota_filename, secondary, payload_url, extra_headers):
Alex Deymo6751bbe2017-03-21 11:20:02 -0700338 """Return the command to run to start the update in the Android device."""
Tianjie Xu3f9be772019-11-02 18:31:50 -0700339 ota = AndroidOTAPackage(ota_filename, secondary)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700340 headers = ota.properties
Kelvin Zhang4b883ea2020-10-08 13:26:44 -0400341 headers += b'USER_AGENT=Dalvik (something, something)\n'
342 headers += b'NETWORK_ID=0\n'
343 headers += extra_headers.encode()
Alex Deymo6751bbe2017-03-21 11:20:02 -0700344
345 return ['update_engine_client', '--update', '--follow',
346 '--payload=%s' % payload_url, '--offset=%d' % ota.offset,
Kelvin Zhang4b883ea2020-10-08 13:26:44 -0400347 '--size=%d' % ota.size, '--headers="%s"' % headers.decode()]
Alex Deymo6751bbe2017-03-21 11:20:02 -0700348
349
Sen Jianga1784b72017-08-09 17:42:36 -0700350def OmahaUpdateCommand(omaha_url):
351 """Return the command to run to start the update in a device using Omaha."""
352 return ['update_engine_client', '--update', '--follow',
353 '--omaha_url=%s' % omaha_url]
354
355
Alex Deymo6751bbe2017-03-21 11:20:02 -0700356class AdbHost(object):
357 """Represents a device connected via ADB."""
358
359 def __init__(self, device_serial=None):
360 """Construct an instance.
361
362 Args:
363 device_serial: options string serial number of attached device.
364 """
365 self._device_serial = device_serial
366 self._command_prefix = ['adb']
367 if self._device_serial:
368 self._command_prefix += ['-s', self._device_serial]
369
Kelvin Zhang3a188952021-04-13 12:44:45 -0400370 def adb(self, command, timeout_seconds: float = None):
Alex Deymo6751bbe2017-03-21 11:20:02 -0700371 """Run an ADB command like "adb push".
372
373 Args:
374 command: list of strings containing command and arguments to run
375
376 Returns:
377 the program's return code.
378
379 Raises:
380 subprocess.CalledProcessError on command exit != 0.
381 """
382 command = self._command_prefix + command
383 logging.info('Running: %s', ' '.join(str(x) for x in command))
384 p = subprocess.Popen(command, universal_newlines=True)
Kelvin Zhang3a188952021-04-13 12:44:45 -0400385 p.wait(timeout_seconds)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700386 return p.returncode
387
Sen Jianga1784b72017-08-09 17:42:36 -0700388 def adb_output(self, command):
389 """Run an ADB command like "adb push" and return the output.
390
391 Args:
392 command: list of strings containing command and arguments to run
393
394 Returns:
395 the program's output as a string.
396
397 Raises:
398 subprocess.CalledProcessError on command exit != 0.
399 """
400 command = self._command_prefix + command
401 logging.info('Running: %s', ' '.join(str(x) for x in command))
402 return subprocess.check_output(command, universal_newlines=True)
403
Alex Deymo6751bbe2017-03-21 11:20:02 -0700404
Kelvin Zhang63b39112021-03-05 12:31:38 -0500405def PushMetadata(dut, otafile, metadata_path):
406 payload = update_payload.Payload(otafile)
407 payload.Init()
408 with tempfile.TemporaryDirectory() as tmpdir:
409 with zipfile.ZipFile(otafile, "r") as zfp:
410 extracted_path = os.path.join(tmpdir, "payload.bin")
411 with zfp.open("payload.bin") as payload_fp, \
412 open(extracted_path, "wb") as output_fp:
413 # Only extract the first |data_offset| bytes from the payload.
414 # This is because allocateSpaceForPayload only needs to see
415 # the manifest, not the entire payload.
416 # Extracting the entire payload works, but is slow for full
417 # OTA.
418 output_fp.write(payload_fp.read(payload.data_offset))
419
420 return dut.adb([
421 "push",
422 extracted_path,
423 metadata_path
424 ]) == 0
425
426
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700427def ParseSpeedLimit(arg: str) -> int:
428 arg = arg.strip().upper()
429 if not re.match(r"\d+[KkMmGgTt]?", arg):
430 raise argparse.ArgumentError(
431 "Wrong speed limit format, expected format is number followed by unit, such as 10K, 5m, 3G (case insensitive)")
432 unit = 1
433 if arg[-1].isalpha():
434 if arg[-1] == "K":
435 unit = 1024
436 elif arg[-1] == "M":
437 unit = 1024 * 1024
438 elif arg[-1] == "G":
439 unit = 1024 * 1024 * 1024
440 elif arg[-1] == "T":
441 unit = 1024 * 1024 * 1024 * 1024
442 else:
443 raise argparse.ArgumentError(
444 f"Unsupported unit for download speed: {arg[-1]}, supported units are K,M,G,T (case insensitive)")
445 return int(float(arg[:-1]) * unit)
446
447
Alex Deymo6751bbe2017-03-21 11:20:02 -0700448def main():
449 parser = argparse.ArgumentParser(description='Android A/B OTA helper.')
Sen Jiang3b15b592017-09-26 18:21:04 -0700450 parser.add_argument('otafile', metavar='PAYLOAD', type=str,
451 help='the OTA package file (a .zip file) or raw payload \
452 if device uses Omaha.')
Alex Deymo6751bbe2017-03-21 11:20:02 -0700453 parser.add_argument('--file', action='store_true',
454 help='Push the file to the device before updating.')
455 parser.add_argument('--no-push', action='store_true',
456 help='Skip the "push" command when using --file')
457 parser.add_argument('-s', type=str, default='', metavar='DEVICE',
458 help='The specific device to use.')
459 parser.add_argument('--no-verbose', action='store_true',
460 help='Less verbose output')
Sen Jianga1784b72017-08-09 17:42:36 -0700461 parser.add_argument('--public-key', type=str, default='',
462 help='Override the public key used to verify payload.')
Sen Jiang6fbfd7d2017-10-31 16:16:56 -0700463 parser.add_argument('--extra-headers', type=str, default='',
464 help='Extra headers to pass to the device.')
Tianjie Xu3f9be772019-11-02 18:31:50 -0700465 parser.add_argument('--secondary', action='store_true',
466 help='Update with the secondary payload in the package.')
Kelvin Zhang8212f532020-11-13 16:00:00 -0500467 parser.add_argument('--no-slot-switch', action='store_true',
468 help='Do not perform slot switch after the update.')
Kelvin Zhangbec0f072021-03-31 16:09:00 -0400469 parser.add_argument('--no-postinstall', action='store_true',
470 help='Do not execute postinstall scripts after the update.')
Kelvin Zhangffd21442021-04-14 09:09:41 -0400471 parser.add_argument('--allocate-only', action='store_true',
Kelvin Zhang51aad992021-02-19 14:46:28 -0500472 help='Allocate space for this OTA, instead of actually \
473 applying the OTA.')
Kelvin Zhangffd21442021-04-14 09:09:41 -0400474 parser.add_argument('--verify-only', action='store_true',
Kelvin Zhang63b39112021-03-05 12:31:38 -0500475 help='Verify metadata then exit, instead of applying the OTA.')
Kelvin Zhangffd21442021-04-14 09:09:41 -0400476 parser.add_argument('--no-care-map', action='store_true',
Kelvin Zhang5bd46222021-03-02 12:36:14 -0500477 help='Do not push care_map.pb to device.')
Kelvin Zhangc56afa32021-08-13 12:32:31 -0700478 parser.add_argument('--perform-slot-switch', action='store_true',
479 help='Perform slot switch for this OTA package')
480 parser.add_argument('--perform-reset-slot-switch', action='store_true',
481 help='Perform reset slot switch for this OTA package')
Kelvin Zhang2451a302022-03-23 19:18:35 -0700482 parser.add_argument('--wipe-user-data', action='store_true',
483 help='Wipe userdata after installing OTA')
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000484 parser.add_argument('--disable-vabc', action='store_true',
485 help='Disable vabc during OTA')
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800486 parser.add_argument('--enable-threading', action='store_true',
487 help='Enable multi-threaded compression for VABC')
488 parser.add_argument('--batched-writes', action='store_true',
489 help='Enable batched writes for VABC')
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700490 parser.add_argument('--speed-limit', type=str,
491 help='Speed limit for serving payloads over HTTP. For '
492 'example: 10K, 5m, 1G, input is case insensitive')
493
Alex Deymo6751bbe2017-03-21 11:20:02 -0700494 args = parser.parse_args()
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700495 if args.speed_limit:
496 args.speed_limit = ParseSpeedLimit(args.speed_limit)
497
Alex Deymo6751bbe2017-03-21 11:20:02 -0700498 logging.basicConfig(
499 level=logging.WARNING if args.no_verbose else logging.INFO)
500
Nikita Ioffe3a327e62021-06-30 16:05:09 +0100501 start_time = time.perf_counter()
502
Alex Deymo6751bbe2017-03-21 11:20:02 -0700503 dut = AdbHost(args.s)
504
505 server_thread = None
506 # List of commands to execute on exit.
507 finalize_cmds = []
508 # Commands to execute when canceling an update.
509 cancel_cmd = ['shell', 'su', '0', 'update_engine_client', '--cancel']
510 # List of commands to perform the update.
511 cmds = []
512
Sen Jianga1784b72017-08-09 17:42:36 -0700513 help_cmd = ['shell', 'su', '0', 'update_engine_client', '--help']
514 use_omaha = 'omaha' in dut.adb_output(help_cmd)
515
Kelvin Zhang63b39112021-03-05 12:31:38 -0500516 metadata_path = "/data/ota_package/metadata"
Kelvin Zhang51aad992021-02-19 14:46:28 -0500517 if args.allocate_only:
Kelvin Zhang63b39112021-03-05 12:31:38 -0500518 if PushMetadata(dut, args.otafile, metadata_path):
519 dut.adb([
520 "shell", "update_engine_client", "--allocate",
521 "--metadata={}".format(metadata_path)])
522 # Return 0, as we are executing ADB commands here, no work needed after
523 # this point
524 return 0
525 if args.verify_only:
526 if PushMetadata(dut, args.otafile, metadata_path):
527 dut.adb([
528 "shell", "update_engine_client", "--verify",
529 "--metadata={}".format(metadata_path)])
Kelvin Zhang51aad992021-02-19 14:46:28 -0500530 # Return 0, as we are executing ADB commands here, no work needed after
531 # this point
532 return 0
Kelvin Zhangc56afa32021-08-13 12:32:31 -0700533 if args.perform_slot_switch:
534 assert PushMetadata(dut, args.otafile, metadata_path)
535 dut.adb(["shell", "update_engine_client",
536 "--switch_slot=true", "--metadata={}".format(metadata_path), "--follow"])
537 return 0
538 if args.perform_reset_slot_switch:
539 assert PushMetadata(dut, args.otafile, metadata_path)
540 dut.adb(["shell", "update_engine_client",
541 "--switch_slot=false", "--metadata={}".format(metadata_path)])
542 return 0
Kelvin Zhang51aad992021-02-19 14:46:28 -0500543
Kelvin Zhang8212f532020-11-13 16:00:00 -0500544 if args.no_slot_switch:
545 args.extra_headers += "\nSWITCH_SLOT_ON_REBOOT=0"
Kelvin Zhangbec0f072021-03-31 16:09:00 -0400546 if args.no_postinstall:
547 args.extra_headers += "\nRUN_POST_INSTALL=0"
Kelvin Zhang2451a302022-03-23 19:18:35 -0700548 if args.wipe_user_data:
549 args.extra_headers += "\nPOWERWASH=1"
Daniel Zheng730ae9b2022-08-25 22:37:22 +0000550 if args.disable_vabc:
551 args.extra_headers += "\nDISABLE_VABC=1"
Kelvin Zhang6bef4902023-02-22 12:43:27 -0800552 if args.enable_threading:
553 args.extra_headers += "\nENABLE_THREADING=1"
554 if args.batched_writes:
555 args.extra_headers += "\nBATCHED_WRITES=1"
Kelvin Zhang8212f532020-11-13 16:00:00 -0500556
Kelvin Zhang5bd46222021-03-02 12:36:14 -0500557 with zipfile.ZipFile(args.otafile) as zfp:
558 CARE_MAP_ENTRY_NAME = "care_map.pb"
559 if CARE_MAP_ENTRY_NAME in zfp.namelist() and not args.no_care_map:
560 # Need root permission to push to /data
561 dut.adb(["root"])
Kelvin Zhang472d5612021-03-05 12:32:19 -0500562 with tempfile.NamedTemporaryFile() as care_map_fp:
Kelvin Zhang5bd46222021-03-02 12:36:14 -0500563 care_map_fp.write(zfp.read(CARE_MAP_ENTRY_NAME))
564 care_map_fp.flush()
565 dut.adb(["push", care_map_fp.name,
Kelvin Zhangffd21442021-04-14 09:09:41 -0400566 "/data/ota_package/" + CARE_MAP_ENTRY_NAME])
Kelvin Zhang5bd46222021-03-02 12:36:14 -0500567
Alex Deymo6751bbe2017-03-21 11:20:02 -0700568 if args.file:
569 # Update via pushing a file to /data.
570 device_ota_file = os.path.join(OTA_PACKAGE_PATH, 'debug.zip')
571 payload_url = 'file://' + device_ota_file
572 if not args.no_push:
Tao Baoabb45a52017-10-25 11:13:03 -0700573 data_local_tmp_file = '/data/local/tmp/debug.zip'
574 cmds.append(['push', args.otafile, data_local_tmp_file])
575 cmds.append(['shell', 'su', '0', 'mv', data_local_tmp_file,
576 device_ota_file])
577 cmds.append(['shell', 'su', '0', 'chcon',
578 'u:object_r:ota_package_file:s0', device_ota_file])
Alex Deymo6751bbe2017-03-21 11:20:02 -0700579 cmds.append(['shell', 'su', '0', 'chown', 'system:cache', device_ota_file])
580 cmds.append(['shell', 'su', '0', 'chmod', '0660', device_ota_file])
581 else:
582 # Update via sending the payload over the network with an "adb reverse"
583 # command.
Sen Jianga1784b72017-08-09 17:42:36 -0700584 payload_url = 'http://127.0.0.1:%d/payload' % DEVICE_PORT
Sen Jiang3b15b592017-09-26 18:21:04 -0700585 if use_omaha and zipfile.is_zipfile(args.otafile):
Tianjie Xu3f9be772019-11-02 18:31:50 -0700586 ota = AndroidOTAPackage(args.otafile, args.secondary)
Sen Jiang3b15b592017-09-26 18:21:04 -0700587 serving_range = (ota.offset, ota.size)
588 else:
589 serving_range = (0, os.stat(args.otafile).st_size)
Kelvin Zhang46a860c2022-09-28 19:42:39 -0700590 server_thread = StartServer(args.otafile, serving_range, args.speed_limit)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700591 cmds.append(
Sen Jianga1784b72017-08-09 17:42:36 -0700592 ['reverse', 'tcp:%d' % DEVICE_PORT, 'tcp:%d' % server_thread.port])
593 finalize_cmds.append(['reverse', '--remove', 'tcp:%d' % DEVICE_PORT])
594
595 if args.public_key:
596 payload_key_dir = os.path.dirname(PAYLOAD_KEY_PATH)
597 cmds.append(
598 ['shell', 'su', '0', 'mount', '-t', 'tmpfs', 'tmpfs', payload_key_dir])
599 # Allow adb push to payload_key_dir
600 cmds.append(['shell', 'su', '0', 'chcon', 'u:object_r:shell_data_file:s0',
601 payload_key_dir])
602 cmds.append(['push', args.public_key, PAYLOAD_KEY_PATH])
603 # Allow update_engine to read it.
604 cmds.append(['shell', 'su', '0', 'chcon', '-R', 'u:object_r:system_file:s0',
605 payload_key_dir])
606 finalize_cmds.append(['shell', 'su', '0', 'umount', payload_key_dir])
Alex Deymo6751bbe2017-03-21 11:20:02 -0700607
608 try:
609 # The main update command using the configured payload_url.
Sen Jianga1784b72017-08-09 17:42:36 -0700610 if use_omaha:
611 update_cmd = \
612 OmahaUpdateCommand('http://127.0.0.1:%d/update' % DEVICE_PORT)
613 else:
Tianjie Xu3f9be772019-11-02 18:31:50 -0700614 update_cmd = AndroidUpdateCommand(args.otafile, args.secondary,
615 payload_url, args.extra_headers)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700616 cmds.append(['shell', 'su', '0'] + update_cmd)
617
618 for cmd in cmds:
619 dut.adb(cmd)
620 except KeyboardInterrupt:
621 dut.adb(cancel_cmd)
622 finally:
623 if server_thread:
624 server_thread.StopServer()
625 for cmd in finalize_cmds:
Kelvin Zhang3a188952021-04-13 12:44:45 -0400626 dut.adb(cmd, 5)
Alex Deymo6751bbe2017-03-21 11:20:02 -0700627
Nikita Ioffe3a327e62021-06-30 16:05:09 +0100628 logging.info('Update took %.3f seconds', (time.perf_counter() - start_time))
Alex Deymo6751bbe2017-03-21 11:20:02 -0700629 return 0
630
Andrew Lassalle165843c2019-11-05 13:30:34 -0800631
Alex Deymo6751bbe2017-03-21 11:20:02 -0700632if __name__ == '__main__':
633 sys.exit(main())