blob: f131c531964e838649dca8d0450ad05062be9a46 [file] [log] [blame]
Shuqian Zhaoae2d0782016-11-15 16:58:47 -08001#!/usr/bin/python
2
3# Copyright (c) 2016 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Module to automate the process of deploying to production.
8
9Example usage of this script:
10 1. Update both autotest and chromite to the lastest commit that has passed
11 the test instance.
12 $ ./site_utils/automated_deploy.py
13 2. Skip updating a repo, e.g. autotest
14 $ ./site_utils/automated_deploy.py --skip_autotest
15 3. Update a given repo to a specific commit
16 $ ./site_utils/automated_deploy.py --autotest_hash='1234'
17"""
18
19import argparse
20import os
21import re
22import sys
23import subprocess
24
25import common
26from autotest_lib.client.common_lib import revision_control
27from autotest_lib.site_utils.lib import infra
28
29AUTOTEST_DIR = common.autotest_dir
30GIT_URL = {'autotest':
31 'https://chromium.googlesource.com/chromiumos/third_party/autotest',
32 'chromite':
33 'https://chromium.googlesource.com/chromiumos/chromite'}
34PROD_BRANCH = 'prod'
35MASTER_AFE = 'cautotest'
Shuqian Zhaoa482c4a2016-11-21 18:49:41 -080036NOTIFY_GROUP = 'chromeos-infra-discuss@google.com'
Shuqian Zhaoae2d0782016-11-15 16:58:47 -080037
38
39class AutoDeployException(Exception):
40 """Raised when any deploy step fails."""
41
42
43def parse_arguments():
44 """Parse command line arguments.
45
46 @returns An argparse.Namespace populated with argument values.
47 """
48 parser = argparse.ArgumentParser(
49 description=('Command to update prod branch for autotest, chromite '
50 'repos. Then deploy new changes to all lab servers.'))
51 parser.add_argument('--skip_autotest', action='store_true', default=False,
52 help='Skip updating autotest prod branch. Default is False.')
53 parser.add_argument('--skip_chromite', action='store_true', default=False,
54 help='Skip updating chromite prod branch. Default is False.')
Shuqian Zhao67ee3b42017-12-07 11:12:18 -080055 parser.add_argument('--force_update', action='store_true', default=False,
56 help=('Force a deployment without updating both autotest and '
57 'chromite prod branch'))
Shuqian Zhaoae2d0782016-11-15 16:58:47 -080058 parser.add_argument('--autotest_hash', type=str, default=None,
59 help='Update autotest prod branch to the given hash. If it is not'
60 ' specified, autotest prod branch will be rebased to '
61 'prod-next branch, which is the latest commit that has '
62 'passed our test instance.')
63 parser.add_argument('--chromite_hash', type=str, default=None,
64 help='Same as autotest_hash option.')
65
66 results = parser.parse_args(sys.argv[1:])
67
68 # Verify the validity of the options.
69 if ((results.skip_autotest and results.autotest_hash) or
70 (results.skip_chromite and results.chromite_hash)):
71 parser.print_help()
72 print 'Cannot specify skip_* and *_hash options at the same time.'
73 sys.exit(1)
Shuqian Zhao67ee3b42017-12-07 11:12:18 -080074 if results.force_update:
75 results.skip_autotest = True
76 results.skip_chromite = True
Shuqian Zhaoae2d0782016-11-15 16:58:47 -080077 return results
78
79
80def clone_prod_branch(repo):
81 """Method to clone the prod branch for a given repo under /tmp/ dir.
82
83 @param repo: Name of the git repo to be cloned.
84
85 @returns path to the cloned repo.
86 @raises subprocess.CalledProcessError on a command failure.
87 @raised revision_control.GitCloneError when git clone fails.
88 """
89 repo_dir = '/tmp/%s' % repo
90 print 'Cloning %s prod branch under %s' % (repo, repo_dir)
91 if os.path.exists(repo_dir):
92 infra.local_runner('rm -rf %s' % repo_dir)
93 git_repo = revision_control.GitRepo(repo_dir, GIT_URL[repo])
94 git_repo.clone(remote_branch=PROD_BRANCH)
95 print 'Successfully cloned %s prod branch' % repo
96 return repo_dir
97
98
99def update_prod_branch(repo, repo_dir, hash_to_rebase):
100 """Method to update the prod branch of the given repo to the given hash.
101
102 @param repo: Name of the git repo to be updated.
103 @param repo_dir: path to the cloned repo.
104 @param hash_to_rebase: Hash to rebase the prod branch to. If it is None,
105 prod branch will rebase to prod-next branch.
106
Shuqian Zhao673519b2017-05-05 15:13:25 -0700107 @returns the range of the pushed commits as a string. E.g 123...345. If the
108 prod branch is already up-to-date, return None.
Shuqian Zhaoae2d0782016-11-15 16:58:47 -0800109 @raises subprocess.CalledProcessError on a command failure.
110 """
111 with infra.chdir(repo_dir):
Shuqian Zhaoa482c4a2016-11-21 18:49:41 -0800112 print 'Updating %s prod branch.' % repo
113 rebase_to = hash_to_rebase if hash_to_rebase else 'origin/prod-next'
Shuqian Zhao673519b2017-05-05 15:13:25 -0700114 # Check whether prod branch is already up-to-date, which means there is
115 # no changes since last push.
116 print 'Detecting new changes since last push...'
117 diff = infra.local_runner('git log prod..%s --oneline' % rebase_to,
118 stream_output=True)
119 if diff:
120 print 'Find new changes, will update prod branch...'
121 infra.local_runner('git rebase %s prod' % rebase_to,
122 stream_output=True)
123 result = infra.local_runner('git push origin prod',
124 stream_output=True)
125 print 'Successfully pushed %s prod branch!\n' % repo
Shuqian Zhaoae2d0782016-11-15 16:58:47 -0800126
Shuqian Zhao673519b2017-05-05 15:13:25 -0700127 # Get the pushed commit range, which is used to get pushed commits
128 # using git log E.g. 123..456, then run git log --oneline 123..456.
129 grep = re.search('(\w)*\.\.(\w)*', result)
Shuqian Zhaoae2d0782016-11-15 16:58:47 -0800130
Shuqian Zhao673519b2017-05-05 15:13:25 -0700131 if not grep:
132 raise AutoDeployException(
133 'Fail to get pushed commits for repo %s from git log: %s' %
134 (repo, result))
135 return grep.group(0)
136 else:
137 print 'No new %s changes found since last push.' % repo
138 return None
Shuqian Zhaoae2d0782016-11-15 16:58:47 -0800139
140
141def get_pushed_commits(repo, repo_dir, pushed_commits_range):
142 """Method to get the pushed commits.
143
144 @param repo: Name of the updated git repo.
145 @param repo_dir: path to the cloned repo.
146 @param pushed_commits_range: The range of the pushed commits. E.g 123...345
147 @return: the commits that are pushed to prod branch. The format likes this:
148 "git log --oneline A...B | grep autotest
149 A xxxx
150 B xxxx"
151 @raises subprocess.CalledProcessError on a command failure.
152 """
Shuqian Zhaoa482c4a2016-11-21 18:49:41 -0800153 print 'Getting pushed CLs for %s repo.' % repo
Shuqian Zhao673519b2017-05-05 15:13:25 -0700154 if not pushed_commits_range:
155 return '\n%s:\nNo new changes since last push.' % repo
156
Shuqian Zhaoae2d0782016-11-15 16:58:47 -0800157 with infra.chdir(repo_dir):
158 get_commits_cmd = 'git log --oneline %s' % pushed_commits_range
xixuan6d782dc2017-06-21 18:08:48 -0700159
160 pushed_commits = infra.local_runner(
161 get_commits_cmd, stream_output=True)
Shuqian Zhaoae2d0782016-11-15 16:58:47 -0800162 if repo == 'autotest':
xixuan6d782dc2017-06-21 18:08:48 -0700163 autotest_commits = ''
164 for cl in pushed_commits.splitlines():
165 if 'autotest' in cl:
166 autotest_commits += '%s\n' % cl
167
168 pushed_commits = autotest_commits
169
Shuqian Zhaoa482c4a2016-11-21 18:49:41 -0800170 print 'Successfully got pushed CLs for %s repo!\n' % repo
Aviv Keshet6dd1c3d2017-09-26 17:46:49 -0700171 displayed_cmd = get_commits_cmd
172 if repo == 'autotest':
173 displayed_cmd += ' | grep autotest'
174 return '\n%s:\n%s\n%s\n' % (repo, displayed_cmd, pushed_commits)
Shuqian Zhaoae2d0782016-11-15 16:58:47 -0800175
176
177def kick_off_deploy():
178 """Method to kick off deploy script to deploy changes to lab servers.
179
180 @raises subprocess.CalledProcessError on a repo command failure.
181 """
182 print 'Start deploying changes to all lab servers...'
183 with infra.chdir(AUTOTEST_DIR):
Shuqian Zhaoae2d0782016-11-15 16:58:47 -0800184 # Then kick off the deploy script.
Aviv Keshetfc59c142017-10-31 09:27:57 -0700185 deploy_cmd = ('runlocalssh ./site_utils/deploy_server.py -x --afe=%s' %
Shuqian Zhaoae2d0782016-11-15 16:58:47 -0800186 MASTER_AFE)
Shuqian Zhao6ad127a2017-05-22 22:57:19 +0000187 infra.local_runner(deploy_cmd, stream_output=True)
Aviv Keshetfc59c142017-10-31 09:27:57 -0700188 print 'Successfully deployed changes to all lab servers.'
Shuqian Zhaoae2d0782016-11-15 16:58:47 -0800189
190
191def main(args):
192 """Main entry"""
193 options = parse_arguments()
194 repos = dict()
195 if not options.skip_autotest:
196 repos.update({'autotest': options.autotest_hash})
197 if not options.skip_chromite:
198 repos.update({'chromite': options.chromite_hash})
199
200 try:
201 # update_log saves the git log of the updated repo.
202 update_log = ''
203 for repo, hash_to_rebase in repos.iteritems():
204 repo_dir = clone_prod_branch(repo)
205 push_commits_range = update_prod_branch(
206 repo, repo_dir, hash_to_rebase)
207 update_log += get_pushed_commits(repo, repo_dir, push_commits_range)
208
209 kick_off_deploy()
210 except revision_control.GitCloneError as e:
211 print 'Fail to clone prod branch. Error:\n%s\n' % e
212 raise
213 except subprocess.CalledProcessError as e:
Shuqian Zhao1c3f2462017-02-02 17:21:42 -0800214 print ('Deploy fails when running a subprocess cmd :\n%s\n'
215 'Below is the push log:\n%s\n' % (e.output, update_log))
Shuqian Zhaoae2d0782016-11-15 16:58:47 -0800216 raise
217 except Exception as e:
Shuqian Zhao1c3f2462017-02-02 17:21:42 -0800218 print 'Deploy fails with error:\n%s\nPush log:\n%s\n' % (e, update_log)
Shuqian Zhaoae2d0782016-11-15 16:58:47 -0800219 raise
220
221 # When deploy succeeds, print the update_log.
222 print ('Deploy succeeds!!! Below is the push log of the updated repo:\n%s'
Shuqian Zhaoa482c4a2016-11-21 18:49:41 -0800223 'Please email this to %s.'% (update_log, NOTIFY_GROUP))
Shuqian Zhaoae2d0782016-11-15 16:58:47 -0800224
225
226if __name__ == '__main__':
227 sys.exit(main(sys.argv))