1#
2# Copyright (C) 2018 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the 'License');
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#      http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an 'AS IS' BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17import logging
18
19from host_controller import common
20from vti.test_serving.proto import TestScheduleConfigMessage_pb2 as pb
21
22# The list of the kwargs key. can retrieve informations on the leased job.
23_JOB_ATTR_LIST = [
24    "build_id",
25    "test_name",
26    "shards",
27    "serial",
28    "build_target",
29    "manifest_branch",
30    "gsi_branch",
31    "gsi_build_target",
32    "test_branch",
33    "test_build_target",
34]
35
36
37def HasAttr(attr, **kwargs):
38    """Returns True if 'attr' is in 'kwargs' as an arg."""
39    return True if attr in kwargs and kwargs[attr] else False
40
41
42def GetVersion(branch):
43    """Returns the API level (integer) for the given branch."""
44    branch = str(branch.lower())
45    if branch.startswith("git_"):
46        branch = branch[4:]
47    if branch.startswith("aosp-"):
48        branch = branch[5:]
49
50    if "-treble-" in branch:
51        branch = branch.replace("-treble-", "-")
52
53    if branch.endswith("-dev"):
54        branch = branch[:-4]
55    elif branch.endswith("-release"):
56        branch = branch[:-8]
57
58    if (branch.startswith("o") and branch.endswith(
59        ("mr1", "m2", "m3", "m4", "m5", "m6"))):
60        return 8.1
61    elif branch.startswith("o"):
62        return 8.0
63    elif branch.startswith("p"):
64        return 9.0
65    elif branch.startswith("gs://"):
66        if "v8.0" in branch:
67            return 8.0
68        elif "v8.1" in branch:
69            return 8.1
70        elif "v9.0" in branch:
71            return 9.0
72    return 9.0
73
74
75def EmitFetchCommands(**kwargs):
76    """Returns a list of common fetch commands.
77
78    This uses a given device branch information and automatically
79    selects a GSI branch and a test branch.
80
81    Args:
82        kwargs: keyword argument, contains data about the leased job.
83    Returns:
84        list of command string.
85        bool, True if GSI image is fetched. False otherwise
86    """
87    result = []
88    if isinstance(kwargs["build_target"], list):
89        build_target = kwargs["build_target"][0]
90    else:
91        build_target = kwargs["build_target"]
92    shards = int(kwargs["shards"])
93    suite_name, _ = kwargs["test_name"].split("/")
94    serials = kwargs["serial"]
95
96    if HasAttr("pab_account_id", **kwargs):
97        pab_account_id = kwargs["pab_account_id"]
98    else:
99        pab_account_id = common._DEFAULT_ACCOUNT_ID_INTERNAL
100
101    manifest_branch = kwargs["manifest_branch"]
102    build_id = kwargs["build_id"]
103    build_storage_type = pb.BUILD_STORAGE_TYPE_PAB
104    if HasAttr("build_storage_type", **kwargs):
105        build_storage_type = int(kwargs["build_storage_type"])
106
107    if build_storage_type == pb.BUILD_STORAGE_TYPE_PAB:
108        result.append(
109            "fetch --type=pab --branch=%s --target=%s --artifact_name=%s-img-%s.zip "
110            "--build_id=%s --account_id=%s" %
111            (manifest_branch, build_target, build_target.split("-")[0],
112             build_id if build_id != "latest" else "{build_id}", build_id,
113             pab_account_id))
114        if HasAttr("require_signed_device_build", **kwargs):
115            result[-1] += " --fetch_signed_build=True"
116        if common.UNIVERSAL9810 in build_target:
117            result[-1] += " --full_device_images=True"
118
119        if HasAttr("has_bootloader_img", **kwargs):
120            result.append("fetch --type=pab --branch=%s --target=%s "
121                          "--artifact_name=bootloader.img --build_id=%s "
122                          "--account_id=%s" % (manifest_branch, build_target,
123                                               build_id, pab_account_id))
124
125        if HasAttr("has_radio_img", **kwargs):
126            result.append("fetch --type=pab --branch=%s --target=%s "
127                          "--artifact_name=radio.img --build_id=%s "
128                          "--account_id=%s" % (manifest_branch, build_target,
129                                               build_id, pab_account_id))
130
131    elif build_storage_type == pb.BUILD_STORAGE_TYPE_GCS:
132        result.append("fetch --type=gcs --path=%s" % (manifest_branch))
133        if common.UNIVERSAL9810 in build_target:
134            result[-1] += " --full_device_images=True"
135    else:
136        logging.error("unknown build storage type is given: %d",
137                      build_storage_type)
138        return None
139
140    if HasAttr("gsi_branch", **kwargs):
141        gsi = True
142    else:
143        gsi = False
144
145    if HasAttr("gsi_vendor_version", **kwargs):
146        gsi_vendor_version = kwargs["gsi_vendor_version"]
147    else:
148        gsi_vendor_version = None
149
150    if gsi:
151        if common.SDM845 in build_target:
152            if shards > 1:
153                sub_commands = []
154                if shards <= len(serials):
155                    for shard_index in range(shards):
156                        sub_commands.append(
157                            GenerateSdm845SetupCommands(serials[shard_index]))
158                result.append(sub_commands)
159            else:
160                result.extend(GenerateSdm845SetupCommands(serials[0]))
161
162        if HasAttr("gsi_build_id", **kwargs):
163            gsi_build_id = kwargs["gsi_build_id"]
164        else:
165            gsi_build_id = "latest"
166        gsi_storage_type = pb.BUILD_STORAGE_TYPE_PAB
167        if HasAttr("gsi_storage_type", **kwargs):
168            gsi_storage_type = int(kwargs["gsi_storage_type"])
169
170        if gsi_storage_type == pb.BUILD_STORAGE_TYPE_PAB:
171            result.append(
172                "fetch --type=pab --branch=%s --target=%s --gsi=True "
173                "--artifact_name=%s-img-{build_id}.zip --build_id=%s" %
174                (kwargs["gsi_branch"], kwargs["gsi_build_target"],
175                 kwargs["gsi_build_target"].split("-")[0], gsi_build_id))
176        elif gsi_storage_type == pb.BUILD_STORAGE_TYPE_GCS:
177            result.append("fetch --type=gcs --path=%s/%s-img-%s.zip "
178                          "--gsi=True" %
179                          (kwargs["gsi_branch"],
180                           kwargs["gsi_build_target"].split("-")[0],
181                           gsi_build_id))
182        else:
183            logging.error("unknown gsi storage type is given: %d",
184                          gsi_storage_type)
185            return None
186
187        if HasAttr("gsi_pab_account_id", **kwargs):
188            result[-1] += " --account_id=%s" % kwargs["gsi_pab_account_id"]
189
190    if HasAttr("test_build_id", **kwargs):
191        test_build_id = kwargs["test_build_id"]
192    else:
193        test_build_id = "latest"
194    test_storage_type = pb.BUILD_STORAGE_TYPE_PAB
195    if HasAttr("test_storage_type", **kwargs):
196        test_storage_type = int(kwargs["test_storage_type"])
197
198    if test_storage_type == pb.BUILD_STORAGE_TYPE_PAB:
199        result.append("fetch --type=pab --branch=%s --target=%s "
200                      "--artifact_name=android-%s.zip --build_id=%s" %
201                      (kwargs["test_branch"], kwargs["test_build_target"],
202                       suite_name, test_build_id))
203    elif test_storage_type == pb.BUILD_STORAGE_TYPE_GCS:
204        result.append("fetch --type=gcs --path=%s/%s.zip --set_suite_as=%s" %
205                      (kwargs["test_branch"], kwargs["test_build_target"],
206                       suite_name))
207    else:
208        logging.error("unknown test storage type is given: %d",
209                      test_storage_type)
210        return None
211
212    if HasAttr("test_pab_account_id", **kwargs):
213        result[-1] += " --account_id=%s" % kwargs["test_pab_account_id"]
214
215    result.append("info")
216    if gsi:
217        gsispl_command = "gsispl --version_from_path=boot.img"
218        if gsi_vendor_version:
219            gsispl_command += " --vendor_version=%s" % gsi_vendor_version
220        result.append(gsispl_command)
221        result.append("info")
222
223    return result, gsi
224
225
226def EmitFlashCommands(gsi, **kwargs):
227    """Returns a list of common flash commands.
228
229    This uses a given device branch information and automatically
230    selects a GSI branch and a test branch.
231
232    Args:
233        gsi: bool, whether to flash GSI over vendor images or not.
234        kwargs: keyword argument, contains data about the leased job.
235    Returns:
236        list of command string.
237    """
238    result = []
239
240    if isinstance(kwargs["build_target"], list):
241        build_target = kwargs["build_target"][0]
242    else:
243        build_target = kwargs["build_target"]
244    shards = int(kwargs["shards"])
245    serials = kwargs["serial"]
246    if gsi:
247        system_version = GetVersion(kwargs["gsi_branch"])
248    else:
249        system_version = GetVersion(kwargs["manifest_branch"])
250
251    repack_command = "repack"
252    if HasAttr("image_package_repo_base", **kwargs):
253        repack_command += " --dest=%s" % kwargs["image_package_repo_base"]
254    if common.SDM845 in build_target and gsi:
255        repack_command += (" --additional_files")
256        for lib_file in common.SDM845_LIB_LIST:
257            repack_command += (" {tmp_dir}/%s/%s" % (serials[0], lib_file))
258    # TODO: verify this before re-enabling.
259    # result.append(repack_command)
260
261    if shards > 1:
262        sub_commands = []
263
264        if shards <= len(serials):
265            for shard_index in range(shards):
266                new_cmd_list = []
267                if (common.K39TV1_BSP in build_target
268                        or common.K39TV1_BSP_1G in build_target):
269                    new_cmd_list.extend(
270                        GenerateMt6739GsiFlashingCommands(
271                            serials[shard_index], gsi))
272                elif common.SDM845 in build_target and gsi:
273                    new_cmd_list.extend(
274                        GenerateSdm845GsiFlashingCommands(
275                            serials[shard_index]))
276                elif common.UNIVERSAL9810 in build_target:
277                    new_cmd_list.extend(
278                        GenerateUniversal9810GsiFlashingCommands(
279                            serials[shard_index], gsi))
280                else:
281                    new_cmd_list.append(
282                        "flash --current --serial %s --skip-vbmeta=True " %
283                        serials[shard_index])
284                new_cmd_list.append("adb -s %s root" % serials[shard_index])
285                if common.SDM845 not in build_target:  # b/78487061
286                    new_cmd_list.append(
287                        "dut --operation=wifi_on --serial=%s --ap=%s" %
288                        (serials[shard_index], common._DEFAULT_WIFI_AP))
289                    new_cmd_list.append(
290                        "dut --operation=volume_mute --serial=%s --version=%s"
291                        % (serials[shard_index], system_version))
292                sub_commands.append(new_cmd_list)
293        result.append(sub_commands)
294    else:
295        if (common.K39TV1_BSP in build_target
296                or common.K39TV1_BSP_1G in build_target):
297            result.extend(GenerateMt6739GsiFlashingCommands(serials[0], gsi))
298        elif common.SDM845 in build_target and gsi:
299            result.extend(GenerateSdm845GsiFlashingCommands(serials[0]))
300        elif common.UNIVERSAL9810 in build_target:
301            result.extend(
302                GenerateUniversal9810GsiFlashingCommands(serials[0], gsi))
303        else:
304            result.append(
305                "flash --current --serial %s --skip-vbmeta=True" % serials[0])
306        if common.SDM845 not in build_target:  # b/78487061
307            result.append("dut --operation=wifi_on --serial=%s --ap=%s" %
308                          (serials[0], common._DEFAULT_WIFI_AP))
309            result.append(
310                "dut --operation=volume_mute --serial=%s --version=%s" %
311                (serials[0], system_version))
312        if serials:
313            serial_arg_list = []
314            for serial in serials:
315                result.append("adb -s %s root" % serial)
316                serial_arg_list.append("--serial %s" % serial)
317
318    return result
319
320
321def EmitCommonConsoleCommands(**kwargs):
322    """Runs a common VTS-on-GSI or CTS-on-GSI test.
323
324    This uses a given device branch information and automatically
325    selects a GSI branch and a test branch.
326    """
327    result = []
328
329    if not set(_JOB_ATTR_LIST).issubset(kwargs):
330        missing_keys = [key for key in _JOB_ATTR_LIST if key not in kwargs]
331        logging.error("Leased job missing attribute(s): {}".format(
332            ", ".join(missing_keys)))
333        return None
334
335    if isinstance(kwargs["build_target"], list):
336        build_target = kwargs["build_target"][0]
337    else:
338        build_target = kwargs["build_target"]
339    shards = int(kwargs["shards"])
340    suite_name, plan_name = kwargs["test_name"].split("/")
341    serials = kwargs["serial"]
342
343    result.append("device --set_serial=%s --from_job_pool --interval=%s" %
344                  (",".join(serials), common.DEFAULT_DEVICE_TIMEOUT_SECS))
345    fetch_commands_result, gsi = EmitFetchCommands(**kwargs)
346    result.extend(fetch_commands_result)
347    flash_commands_result = EmitFlashCommands(gsi, **kwargs)
348    result.extend(flash_commands_result)
349
350    param = ""
351    if HasAttr("param", **kwargs):
352        param = " ".join(kwargs["param"])
353
354    test_branch = kwargs["test_branch"]
355    if (GetVersion(test_branch) >= 9.0 and
356        (suite_name in ["cts", "gts", "sts"] or plan_name.startswith("cts"))):
357        shard_option = "--shard-count"
358    else:
359        shard_option = "--shards"
360
361    if shards > 1:
362        test_command = "test --suite %s --keep-result -- %s %s %d %s" % (
363            suite_name, plan_name, shard_option, shards, param)
364        if shards <= len(serials):
365            for shard_index in range(shards):
366                test_command += " --serial %s" % serials[shard_index]
367        result.append(test_command)
368    else:
369        if serials:
370            serial_arg_list = []
371            for serial in serials:
372                serial_arg_list.append("--serial %s" % serial)
373            result.append("test --suite %s --keep-result -- %s %s %s" %
374                          (suite_name, plan_name, " ".join(serial_arg_list),
375                           param))
376        else:
377            result.append("test --suite %s --keep-result -- %s %s" %
378                          (suite_name, plan_name, param))
379
380    if "retry_count" in kwargs:
381        retry_count = int(kwargs["retry_count"])
382        result.append(
383            GenerateRetryCommand(build_target, test_branch, suite_name,
384                                 plan_name, serials, retry_count))
385
386    if HasAttr("test_build_id", **kwargs):
387        test_build_id = kwargs["test_build_id"]
388    else:
389        test_build_id = "latest"
390    test_storage_type = pb.BUILD_STORAGE_TYPE_PAB
391    if HasAttr("test_storage_type", **kwargs):
392        test_storage_type = int(kwargs["test_storage_type"])
393
394    if HasAttr("report_bucket", **kwargs):
395        report_buckets = kwargs["report_bucket"]
396    else:
397        report_buckets = ["gs://vts-report"]
398
399    upload_dests = []
400    upload_commands = []
401    for report_bucket in report_buckets:
402        if test_storage_type == pb.BUILD_STORAGE_TYPE_PAB:
403            upload_dest = ("%s/{suite_plan}/%s/{branch}/{target}/"
404                           "%s_{build_id}_{timestamp}/" %
405                           (report_bucket, plan_name, build_target))
406        elif test_storage_type == pb.BUILD_STORAGE_TYPE_GCS:
407            upload_dest = ("%s/{suite_plan}/%s/%s/%s/%s_%s_{timestamp}/" %
408                           (report_bucket, plan_name,
409                            kwargs["test_branch"].replace("gs://", "gs_")
410                            if kwargs["test_branch"].startswith("gs://") else
411                            kwargs["test_branch"], kwargs["test_build_target"],
412                            build_target, test_build_id))
413        upload_dests.append(upload_dest)
414        upload_commands.append(
415            "upload --src={result_full} --dest=%s "
416            "--report_path=%s/suite_result/{timestamp_year}/{timestamp_month}/"
417            "{timestamp_day}" % (upload_dest, report_bucket))
418
419    if HasAttr("report_persistent_url", **kwargs):
420        for upload_dest in kwargs["report_persistent_url"]:
421            upload_dests.append(upload_dest)
422            upload_commands.append("upload --src={result_full} --dest=%s "
423                                   "--clear_dest" % upload_dest)
424
425    result.extend(upload_commands)
426
427    if HasAttr("report_reference_url", **kwargs):
428        ref_urls = kwargs["report_reference_url"]
429    else:
430        ref_urls = []
431
432    extra_rows = " ".join("logs," + x for x in upload_dests)
433    if HasAttr("report_spreadsheet_id", **kwargs):
434        for index, sheet_id in enumerate(kwargs["report_spreadsheet_id"]):
435            sheet_command = ("sheet --src {result_zip} --dest %s "
436                             "--extra_rows %s" % (sheet_id, extra_rows))
437            if plan_name == "cts-on-gsi":
438                sheet_command += " --primary_abi_only"
439            if index < len(ref_urls):
440                sheet_command += " --ref " + ref_urls[index]
441            sheet_command += " --client_secrets DATA/vtslab-gcs.json"
442            result.append(sheet_command)
443
444    result.append("device --update=stop")
445
446    return result
447
448
449def GenerateRetryCommand(build_target,
450                         test_branch,
451                         suite_name,
452                         plan_name,
453                         serials,
454                         retry_count=None):
455    """Returns a retry command.
456
457    Args:
458        build_target: string, build target of the device images
459        test_branch: string, branch name from which the test suite is fetched
460        suite_name: string, the name of the test suite
461        plan_name: string, the name of the test plan that needs to be run
462        serials: list of strings, serial numbers of the DUTs
463        retry_count: int,
464
465    Returns:
466        a string, retry command of the console.
467    """
468    if GetVersion(test_branch) >= 9.0:
469        retry_option = ""
470        shard_option = "--shard-count"
471        if suite_name in ["cts", "gts", "sts"]:
472            retry_option = "--retry_plan=retry"
473        elif plan_name.startswith("cts"):
474            retry_option = "--retry_plan=%s-retry" % plan_name
475        else:
476            shard_option = "--shards"
477    else:
478        shard_option = "--shards"
479        retry_option = ""
480
481    if retry_count is None:
482        retry_count = common.DEFAULT_RETRY_COUNT
483    retry_command = ("retry --suite %s --count %d %s" %
484                     (suite_name, retry_count, retry_option))
485    if serials:
486        if len(serials) > 1:
487            retry_command += " %s %d" % (shard_option, len(serials))
488            for shard_index in range(len(serials)):
489                retry_command += " --serial %s" % serials[shard_index]
490        else:
491            retry_command += " --serial %s" % serials[0]
492    if suite_name in ["cts", "gts", "sts"] or plan_name.startswith("cts"):
493        if common.SDM845 in build_target:
494            # TODO(vtslab-dev): remove after b/77664643 is resolved
495            pass
496        else:
497            retry_command += " --cleanup_devices=True"
498
499    return retry_command
500
501
502def GenerateSdm845SetupCommands(serial):
503    """Returns a sequence of console commands to setup a device.
504
505    Args:
506        serial: string, the target device serial number.
507
508    Returns:
509        a list of strings, each string is a console command.
510    """
511    result = []
512
513    result.append(
514        "fastboot -s %s flash bootloader {device-image[bootloader.img]}" %
515        serial)
516    result.append("fastboot -s %s -- reboot bootloader" % serial)
517    result.append(
518        "fastboot -s %s flash radio {device-image[radio.img]}" % serial)
519    result.append("fastboot -s %s -- reboot bootloader" % serial)
520    result.append(
521        "fastboot -s %s flash boot {device-image[full-zipfile-dir]}/boot.img" %
522        serial)
523    result.append(
524        "fastboot -s %s flash dtbo {device-image[full-zipfile-dir]}/dtbo.img" %
525        serial)
526    result.append(
527        "fastboot --timeout=900 -s %s flash system {device-image[full-zipfile-dir]}/system.img"
528        % serial)
529    result.append(
530        "fastboot -s %s flash userdata {device-image[full-zipfile-dir]}/userdata.img"
531        % serial)
532    result.append(
533        "fastboot -s %s flash vbmeta {device-image[full-zipfile-dir]}/vbmeta.img"
534        " -- --disable-verity" % serial)
535    result.append(
536        "fastboot -s %s flash vendor {device-image[full-zipfile-dir]}/vendor.img"
537        % serial)
538    result.append("fastboot -s %s reboot" % serial)
539    result.append("sleep 90")  # wait for boot_complete (success)
540    result.append("adb -s %s root" % serial)
541    # TODO: to make sure {tmp_dir} is unique per session and
542    #       is cleaned up at exit.
543    result.append("shell -- mkdir -p {tmp_dir}/%s" % serial)
544    result.extend([
545        "adb -s %s pull /system/lib64/%s {tmp_dir}/%s" % (serial, lib_file,
546                                                          serial)
547        for lib_file in common.SDM845_LIB_LIST
548    ])
549
550    # TODO: remove this paragraph after b/74552817 is fixed.
551    result.append(
552        "fetch --type=gcs --path=gs://vts-release/v9.0/sdm845/vbmeta.img "
553        "--artifact_name=vbmeta.img")
554    result.append("adb -s %s reboot bootloader" % serial)
555    result.append("fastboot -s %s flash vbmeta {device-image[vbmeta.img]}"
556                  " -- --disable-verity" % serial)
557
558    return result
559
560
561def GenerateSdm845GsiFlashingCommands(serial, repacked_imageset=False):
562    """Returns a sequence of console commands to flash GSI to a device.
563
564    Args:
565        serial: string, the target device serial number.
566        repacked_imageset: bool, True if this function is called directly from
567                           the console, adjusts the resulting commands for
568                           atomic flashing process.
569
570    Returns:
571        a list of strings, each string is a console command.
572    """
573    result = []
574
575    if repacked_imageset:
576        result.append(
577            "fastboot -s %s flash bootloader {device-image[bootloader.img]}" %
578            serial)
579        result.append("fastboot -s %s -- reboot bootloader" % serial)
580        result.append(
581            "fastboot -s %s flash radio {device-image[radio.img]}" % serial)
582        result.append("fastboot -s %s -- reboot bootloader" % serial)
583        result.append(
584            "fastboot -s %s flash boot {device-image[boot.img]}" % serial)
585        result.append(
586            "fastboot -s %s flash dtbo {device-image[dtbo.img]}" % serial)
587        result.append(
588            "fastboot -s %s flash userdata {device-image[userdata.img]}" %
589            serial)
590        result.append(
591            "fastboot -s %s flash vbmeta {device-image[vbmeta.img]} -- --disable-verity"
592            % serial)
593        result.append(
594            "fastboot -s %s flash vendor {device-image[vendor.img]}" % serial)
595
596    result.append(
597        "fastboot --timeout=900 -s %s flash system {device-image[system.img]}"
598        % serial)
599    # removed -w from below command
600    result.append("fastboot -s %s -- reboot" % serial)
601    result.append("sleep 90")  # wait until adb shell (not boot complete)
602    result.append("adb -s %s root" % serial)
603    result.append("adb -s %s remount" % serial)
604    result.append("adb -s %s shell setenforce 0" % serial)
605    result.append("adb -s %s shell mkdir /bt_firmware" % serial)
606    result.append("adb -s %s shell chown system:system /bt_firmware" % serial)
607    result.append("adb -s %s shell chmod 650 /bt_firmware" % serial)
608    result.append("adb -s %s shell setenforce 1" % serial)
609    if repacked_imageset:
610        result.extend([
611            "adb -s %s push {tools[%s/%s]} /system/lib64" %
612            (serial, common._ADDITIONAL_FILES_DIR, lib_file)
613            for lib_file in common.SDM845_LIB_LIST
614        ])
615    else:
616        result.extend([
617            "adb -s %s push {tmp_dir}/%s/%s /system/lib64" % (serial, serial,
618                                                              lib_file)
619            for lib_file in common.SDM845_LIB_LIST
620        ])
621        result.extend(
622            [("adb -s %s push ../testcases/DATA/xml/media_profiles_vendor.xml "
623              "/vendor/etc/media_profiles_vendor.xml") % serial])
624
625    result.append("shell -- rm {tmp_dir}/%s -rf" % serial)
626    result.append("adb -s %s reboot bootloader" % serial)
627    result.append("sleep 5")
628    # TODO(vtslab-dev): remove after b/112171990 is resolved
629    result.append("fastboot -s %s erase userdata" % serial)
630    # removed -w from below command
631    result.append("fastboot -s %s  -- reboot" % serial)
632    if not repacked_imageset:
633        result.append("sleep 300")  # wait for boot_complete (success)
634
635    return result
636
637
638def GenerateMt6739GsiFlashingCommands(serial,
639                                      gsi=False,
640                                      repacked_imageset=False):
641    """Returns a sequence of console commands to flash device imgs and GSI.
642
643    Args:
644        serial: string, the target device serial number.
645        gsi: bool, whether to flash GSI over vendor images or not.
646        repacked_imageset: bool, True if this func is called directly from
647                           the console, adjusts the resulting commands for
648                           atomic flashing process.
649
650    Returns:
651        a list of strings, each string is a console command.
652    """
653    flash_img_cmd = ("fastboot -s %s flash %s "
654                     "{device-image[full-zipfile-dir]}/%s")
655    flash_gsi_cmd = ("fastboot --timeout=900 -s %s flash system "
656                     "{device-image[system.img]}")
657    result = [
658        flash_img_cmd % (serial, partition, image)
659        for partition, image in (
660            ("preloader", "preloader_SBOOT_DIS.img"),
661            ("loader_ext1", "loader_ext.img"),
662            ("loader_ext2", "loader_ext.img"),
663            ("tee1", "tee.img"),
664            ("tee2", "tee.img"),
665            ("lk", "lk.img"),
666            ("lk2", "lk.img"),
667        )
668    ]
669    result.append("fastboot -s %s -- reboot bootloader" % serial)
670    # gpt is the partition table and must be flashed first.
671    # The bootloader reloads partition table automatically after flashing gpt.
672    result += [
673        flash_img_cmd % (serial, partition, image)
674        for partition, image in (
675            ("gpt", "PGPT"),
676            ("md1img", "md1img.img"),
677            ("md1dsp", "md1dsp.img"),
678            ("recovery", "recovery.img"),
679            ("spmfw", "spmfw.img"),
680            ("mcupmfw", "mcupmfw.img"),
681            ("boot", "boot.img"),
682            ("dtbo", "dtbo.img"),
683            ("vendor", "vendor.img"),
684            ("cache", "cache.img"),
685            ("userdata", "userdata.img"),
686        )
687    ]
688
689    if gsi:
690        result.append(flash_gsi_cmd % serial)
691        result.append("fastboot -s %s -- -w" % serial)
692    else:
693        flash_img_cmd += " --timeout=900"
694        result.append(flash_img_cmd % (serial, "system", "system.img"))
695
696    result.append("fastboot -s %s reboot" % serial)
697    if not repacked_imageset:
698        result.append("sleep 300")  # wait for boot_complete (success)
699
700    return result
701
702
703def GenerateUniversal9810GsiFlashingCommands(serial,
704                                             gsi=False,
705                                             repacked_imageset=False):
706    """Returns a sequence of console commands to flash device imgs and GSI.
707
708    Args:
709        serial: string, the target device serial number.
710        gsi: bool, whether to flash GSI over vendor images or not.
711        repacked_imageset: bool, True if this func is called directly from
712                           the console, adjusts the resulting commands for
713                           atomic flashing process.
714
715    Returns:
716        a list of strings, each string is a console command.
717    """
718    result = [
719        ("fastboot -s %s flash el3_mon "
720         "{device-image[full-zipfile-dir]}/el3_mon.img" % serial),
721        ("fastboot -s %s flash epbl "
722         "{device-image[full-zipfile-dir]}/epbl.img" % serial),
723        ("fastboot -s %s flash bootloader "
724         "{device-image[full-zipfile-dir]}/u-boot.img" % serial),
725        ("fastboot -s %s flash dtb "
726         "{device-image[full-zipfile-dir]}/dtb.img" % serial),
727        ("fastboot -s %s flash dtbo "
728         "{device-image[full-zipfile-dir]}/dtbo.img" % serial),
729        ("fastboot -s %s flash kernel "
730         "{device-image[full-zipfile-dir]}/kernel.img" % serial),
731        ("fastboot -s %s flash ramdisk "
732         "{device-image[full-zipfile-dir]}/ramdisk.img" % serial),
733        ("fastboot -s %s flash vendor "
734         "{device-image[full-zipfile-dir]}/vendor.img -- -S 300M" % serial),
735    ]
736    if gsi:
737        result.append(("fastboot --timeout=900 -s %s flash system "
738                       "{device-image[system.img]} -- -S 512M" % serial))
739    else:
740        result.append((
741            "fastboot --timeout=900 -s %s flash system "
742            "{device-image[full-zipfile-dir]}/system.img -- -S 512M" % serial))
743    result.append("fastboot -s %s reboot -- -w" % serial)
744    if not repacked_imageset:
745        result.append("sleep 300")  # wait for boot_complete (success)
746
747    return result
748
749
750FLASH_COMMAND_EMITTER = {
751    common.K39TV1_BSP: GenerateMt6739GsiFlashingCommands,
752    common.K39TV1_BSP_1G: GenerateMt6739GsiFlashingCommands,
753    common.SDM845: GenerateSdm845GsiFlashingCommands,
754    common.UNIVERSAL9810: GenerateUniversal9810GsiFlashingCommands,
755}
756