blob: 455a5b99f095a3dd8c0909ba864c26dc6e8a663a [file] [log] [blame]
Haibo Huang39aaab62019-01-25 12:23:03 -08001# Copyright (C) 2018 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Send notification email if new version is found.
15
16Example usage:
17external_updater_notifier \
Haibo Huang39aaab62019-01-25 12:23:03 -080018 --history ~/updater/history \
Haibo Huang39287b12019-01-30 15:48:27 -080019 --generate_change \
20 --recipients xxx@xxx.xxx \
21 googletest
Haibo Huang39aaab62019-01-25 12:23:03 -080022"""
23
Haibo Huang11c4a752019-01-31 15:07:03 -080024from datetime import timedelta, datetime
Haibo Huang39aaab62019-01-25 12:23:03 -080025import argparse
26import json
27import os
Haibo Huang39287b12019-01-30 15:48:27 -080028import re
Haibo Huang39aaab62019-01-25 12:23:03 -080029import subprocess
30import time
31
Haibo Huang11c4a752019-01-31 15:07:03 -080032import git_utils
Haibo Huang39aaab62019-01-25 12:23:03 -080033
34def parse_args():
35 """Parses commandline arguments."""
36
37 parser = argparse.ArgumentParser(
38 description='Check updates for third party projects in external/.')
39 parser.add_argument(
Haibo Huang39aaab62019-01-25 12:23:03 -080040 '--history',
41 help='Path of history file. If doesn'
42 't exist, a new one will be created.')
43 parser.add_argument(
44 '--recipients',
45 help='Comma separated recipients of notification email.')
Haibo Huang39287b12019-01-30 15:48:27 -080046 parser.add_argument(
47 '--generate_change',
48 help='If set, an upgrade change will be uploaded to Gerrit.',
49 action='store_true', required=False)
50 parser.add_argument(
51 'paths', nargs='*',
52 help='Paths of the project.')
Haibo Huang1c7284e2019-02-01 11:34:21 -080053 parser.add_argument(
54 '--all', action='store_true',
55 help='Checks all projects.')
Haibo Huang39aaab62019-01-25 12:23:03 -080056
57 return parser.parse_args()
58
59
Haibo Huang39287b12019-01-30 15:48:27 -080060CHANGE_URL_PATTERN = r'(https:\/\/[^\s]*android-review[^\s]*) Upgrade'
61CHANGE_URL_RE = re.compile(CHANGE_URL_PATTERN)
Haibo Huang39aaab62019-01-25 12:23:03 -080062
Haibo Huang39287b12019-01-30 15:48:27 -080063
64def _send_email(proj, latest_ver, recipient, upgrade_log):
65 print('Sending email for {}: {}'.format(proj, latest_ver))
66 msg = "New version: {}".format(latest_ver)
67 match = CHANGE_URL_RE.search(upgrade_log)
68 if match is not None:
69 msg += '\n\nAn upgrade change is generated at:\n{}'.format(
70 match.group(1))
71
72 msg += '\n\n'
73 msg += upgrade_log
74
Haibo Huang39aaab62019-01-25 12:23:03 -080075 subprocess.run(['sendgmr', '--to=' + recipient,
76 '--subject=' + proj], check=True,
77 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
78 input=msg, encoding='ascii')
79
80
Haibo Huang11c4a752019-01-31 15:07:03 -080081NOTIFIED_TIME_KEY_NAME = 'latest_notified_time'
82
83
84def _should_notify(latest_ver, proj_history):
85 if latest_ver in proj_history:
86 # Processed this version before.
87 return False
88
89 timestamp = proj_history.get(NOTIFIED_TIME_KEY_NAME, 0)
90 time_diff = datetime.today() - datetime.fromtimestamp(timestamp)
91 if git_utils.is_commit(latest_ver) and time_diff <= timedelta(days=30):
92 return False
93
94 return True
95
96
Haibo Huang39287b12019-01-30 15:48:27 -080097def _process_results(args, history, results):
Haibo Huang39aaab62019-01-25 12:23:03 -080098 for proj, res in results.items():
99 if 'latest' not in res:
100 continue
101 latest_ver = res['latest']
102 current_ver = res['current']
103 if latest_ver == current_ver:
104 continue
105 proj_history = history.setdefault(proj, {})
Haibo Huang11c4a752019-01-31 15:07:03 -0800106 if _should_notify(latest_ver, proj_history):
Haibo Huang39287b12019-01-30 15:48:27 -0800107 upgrade_log = _upgrade(proj) if args.generate_change else ""
Haibo Huang39aaab62019-01-25 12:23:03 -0800108 try:
Haibo Huang39287b12019-01-30 15:48:27 -0800109 _send_email(proj, latest_ver, args.recipients, upgrade_log)
Haibo Huang39aaab62019-01-25 12:23:03 -0800110 proj_history[latest_ver] = int(time.time())
Haibo Huang11c4a752019-01-31 15:07:03 -0800111 proj_history[NOTIFIED_TIME_KEY_NAME] = int(time.time())
Haibo Huang39aaab62019-01-25 12:23:03 -0800112 except subprocess.CalledProcessError as err:
113 msg = """Failed to send email for {} ({}).
114stdout: {}
115stderr: {}""".format(proj, latest_ver, err.stdout, err.stderr)
116 print(msg)
117
118
Haibo Huang39287b12019-01-30 15:48:27 -0800119RESULT_FILE_PATH = '/tmp/update_check_result.json'
120
121
Haibo Huang39aaab62019-01-25 12:23:03 -0800122def send_notification(args):
123 """Compare results and send notification."""
124 results = {}
Haibo Huang39287b12019-01-30 15:48:27 -0800125 with open(RESULT_FILE_PATH, 'r') as f:
Haibo Huang39aaab62019-01-25 12:23:03 -0800126 results = json.load(f)
127 history = {}
128 try:
129 with open(args.history, 'r') as f:
130 history = json.load(f)
131 except FileNotFoundError:
132 pass
133
Haibo Huang39287b12019-01-30 15:48:27 -0800134 _process_results(args, history, results)
Haibo Huang39aaab62019-01-25 12:23:03 -0800135
136 with open(args.history, 'w') as f:
Haibo Huang38dda432019-02-01 15:45:35 -0800137 json.dump(history, f, sort_keys=True, indent=4)
Haibo Huang39aaab62019-01-25 12:23:03 -0800138
139
Haibo Huang39287b12019-01-30 15:48:27 -0800140def _upgrade(proj):
141 out = subprocess.run(['out/soong/host/linux-x86/bin/external_updater',
142 'update', '--branch_and_commit', '--push_change',
143 proj],
144 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
145 cwd=os.environ['ANDROID_BUILD_TOP'])
146 stdout = out.stdout.decode('utf-8')
147 stderr = out.stderr.decode('utf-8')
148 return """
149====================
150| Debug Info |
151====================
152-=-=-=-=stdout=-=-=-=-
153{}
154
155-=-=-=-=stderr=-=-=-=-
156{}
157""".format(stdout, stderr)
158
159
160def _check_updates(args):
Haibo Huang1c7284e2019-02-01 11:34:21 -0800161 params = ['out/soong/host/linux-x86/bin/external_updater',
162 'check', '--json_output', RESULT_FILE_PATH,
Haibo Huang5c6c63e2019-02-01 11:44:48 -0800163 '--delay', '30']
Haibo Huang1c7284e2019-02-01 11:34:21 -0800164 if args.all:
165 params.append('--all')
166 else:
167 params += args.paths
168
169 subprocess.run(params, cwd=os.environ['ANDROID_BUILD_TOP'])
Haibo Huang39287b12019-01-30 15:48:27 -0800170
171
Haibo Huang39aaab62019-01-25 12:23:03 -0800172def main():
173 """The main entry."""
174
175 args = parse_args()
Haibo Huang39287b12019-01-30 15:48:27 -0800176 _check_updates(args)
Haibo Huang39aaab62019-01-25 12:23:03 -0800177 send_notification(args)
178
179
180if __name__ == '__main__':
181 main()