1#!/usr/bin/python
2
3"""Upload a local build to Google Compute Engine and run it."""
4
5import argparse
6import glob
7import os
8import subprocess
9
10
11def gcloud_ssh(args):
12  command = 'gcloud compute ssh %s@%s ' % (args.user, args.instance)
13  if args.zone:
14    command += '--zone=%s ' % args.zone
15  return command
16
17
18def upload_artifacts(args):
19  dir = os.getcwd()
20  try:
21    os.chdir(args.image_dir)
22    images = glob.glob('*.img')
23    if len(images) == 0:
24      raise OSError('No images found in: %s' + args.image_dir)
25    subprocess.check_call(
26        'tar -c -f - --lzop -S ' + ' '.join(images) +
27        ' | ' +
28        gcloud_ssh(args) + '-- tar -x -f - --lzop -S',
29        shell=True)
30  finally:
31    os.chdir(dir)
32
33  host_package = os.path.join(args.host_dir, 'cvd-host_package.tar.gz')
34  subprocess.check_call(
35      gcloud_ssh(args) + '-- tar -x -z -f - < %s' % host_package,
36      shell=True)
37
38
39def launch_cvd(args):
40  launch_cvd_args = ''
41  if args.data_image:
42    launch_cvd_args = (
43      '--data-image %s '
44      '--data-policy create_if_missing '
45      '--blank-data-image-mb %d ' % (args.data_image, args.blank_data_image_mb))
46
47  subprocess.check_call(
48      gcloud_ssh(args) + '-- ./bin/launch_cvd ' + launch_cvd_args,
49      shell=True)
50
51
52def stop_cvd(args):
53  subprocess.call(
54      gcloud_ssh(args) + '-- ./bin/stop_cvd',
55      shell=True)
56
57
58def main():
59  parser = argparse.ArgumentParser(
60      description='Upload a local build to Google Compute Engine and run it')
61  parser.add_argument(
62      '-host_dir',
63      type=str,
64      default=os.environ.get('ANDROID_HOST_OUT', '.'),
65      help='path to the dist directory')
66  parser.add_argument(
67      '-image_dir',
68      type=str,
69      default=os.environ.get('ANDROID_PRODUCT_OUT', '.'),
70      help='path to the img files')
71  parser.add_argument(
72      '-instance', type=str, required=True,
73      help='instance to update')
74  parser.add_argument(
75      '-zone', type=str, default=None,
76      help='zone containing the instance')
77  parser.add_argument(
78      '-user', type=str, default='vsoc-01',
79      help='user to update on the instance')
80  parser.add_argument(
81      '-data-image', type=str, default=None,
82      help='userdata image file name, this file will be used instead of default one')
83  parser.add_argument(
84      '-blank-data-image-mb', type=int, default=4098,
85      help='custom userdata image size in megabytes')
86  parser.add_argument(
87      '-launch', default=False,
88      action='store_true',
89      help='launch the device')
90  args = parser.parse_args()
91  stop_cvd(args)
92  upload_artifacts(args)
93  if args.launch:
94    launch_cvd(args)
95
96
97if __name__ == '__main__':
98  main()
99