File: fetch-cft-chromedriver.py

package info (click to toggle)
firefox 147.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,683,324 kB
  • sloc: cpp: 7,607,156; javascript: 6,532,492; ansic: 3,775,158; python: 1,415,368; xml: 634,556; asm: 438,949; java: 186,241; sh: 62,751; makefile: 18,079; objc: 13,092; perl: 12,808; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (283 lines) | stat: -rw-r--r-- 9,484 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#!/usr/bin/python3 -u

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

"""
This script downloads chromedriver for a given platform and then
packages the driver along with the revision and uploads the archive.
This is currently accomplished by using "last known good version" of
the chromedrivers associated with Chrome for Testing. The `Canary`
channel is specified as it is required for the Chromium-as-Release
performance tests.
"""


import argparse
import errno
import os
import shutil
import subprocess
import tempfile

import requests
from redo import retriable

CHROME_FOR_TESTING_INFO = {
    "linux": {
        "platform": "linux64",
        "dir": "cft-chromedriver-linux",
        "result": "cft-cd-linux.tar.bz2",
        "result_backup": "cft-cd-linux-backup.tar.bz2",
        "chromedriver": "chromedriver_linux64.zip",
    },
    "win64": {
        "platform": "win64",
        "dir": "cft-chromedriver-win64",
        "result": "cft-cd-win64.tar.bz2",
        "result_backup": "cft-cd-win64-backup.tar.bz2",
        "chromedriver": "chromedriver_win32.zip",
    },
    "mac": {
        "platform": "mac-x64",
        "dir": "cft-chromedriver-mac",
        "result": "cft-cd-mac.tar.bz2",
        "result_backup": "cft-cd-mac-backup.tar.bz2",
        "chromedriver": "chromedriver_mac64.zip",
    },
    "mac-arm": {
        "platform": "mac-arm64",
        "dir": "cft-chromedriver-mac",
        "result": "cft-cd-mac-arm.tar.bz2",
        "result_backup": "cft-cd-mac-arm-backup.tar.bz2",
        "chromedriver": "chromedriver_mac64.zip",
    },
}

LAST_GOOD_CFT_JSON = (
    "https://googlechromelabs.github.io/chrome-for-testing/"
    "last-known-good-versions-with-downloads.json"
)

MILESTONE_CFT_JSON = (
    "https://googlechromelabs.github.io/chrome-for-testing/"
    "latest-versions-per-milestone-with-downloads.json"
)


def log(msg):
    print("build-cft-chromedriver: %s" % msg)


@retriable(attempts=7, sleeptime=5, sleepscale=2)
def fetch_file(url, filepath):
    """Download a file from the given url to a given file."""
    size = 4096
    r = requests.get(url, stream=True)
    r.raise_for_status()

    with open(filepath, "wb") as fd:
        for chunk in r.iter_content(size):
            fd.write(chunk)


def unzip(zippath, target):
    """Unzips an archive to the target location."""
    log("Unpacking archive at: %s to: %s" % (zippath, target))
    unzip_command = ["unzip", "-q", "-o", zippath, "-d", target]
    subprocess.check_call(unzip_command)


def get_cft_metadata(endpoint=LAST_GOOD_CFT_JSON):
    """Send a request to the Chrome for Testing's last
    good json URL (default) and get the json payload which will have
    the download URLs that we need.
    """
    res = requests.get(endpoint)
    data = res.json()

    return data


def get_cd_url(data, cft_platform, channel):
    """Given the json data, get the download URL's for
    the correct platform
    """
    for p in data["channels"][channel]["downloads"]["chromedriver"]:
        if p["platform"] == cft_platform:
            return p["url"]
    raise Exception("Platform not found")


def get_chromedriver_revision(data, channel):
    """Grab revision metadata from payload"""
    return data["channels"][channel]["revision"]


def fetch_chromedriver(download_url, cft_dir):
    """Get the chromedriver for the given cft url repackage it."""

    tmpzip = os.path.join(tempfile.mkdtemp(), "cd-tmp.zip")
    log("Downloading chromedriver from %s" % download_url)
    fetch_file(download_url, tmpzip)

    tmppath = tempfile.mkdtemp()
    unzip(tmpzip, tmppath)

    # Find the chromedriver then copy it to the chromium directory
    cd_path = None
    for dirpath, _, filenames in os.walk(tmppath):
        for filename in filenames:
            if filename == "chromedriver" or filename == "chromedriver.exe":
                cd_path = os.path.join(dirpath, filename)
                break
        if cd_path is not None:
            break
    if cd_path is None:
        raise Exception("Could not find chromedriver binary in %s" % tmppath)
    log("Copying chromedriver from: %s to: %s" % (cd_path, cft_dir))
    shutil.copy(cd_path, cft_dir)


def get_backup_chromedriver(version, cft_data, cft_platform):
    """Download a backup chromedriver for the transitionary period of machine auto updates.

    If no version is specified, by default grab the N-1 version of the latest Stable channel
    chromedriver.

    """
    log("Grabbing a backup chromedriver...")
    if not version:
        log("No version specified")
        # Get latest stable version and subtract 1
        current_stable_version = cft_data["channels"]["Stable"]["version"].split(".")[0]
        version = str(int(current_stable_version) - 1)
        log("Fetching major version %s" % version)

    milestone_metadata = get_cft_metadata(MILESTONE_CFT_JSON)
    backup_revision = milestone_metadata["milestones"][version]["revision"]
    backup_version = milestone_metadata["milestones"][version]["version"].split(".")[0]

    backup_url = None
    for p in milestone_metadata["milestones"][version]["downloads"]["chromedriver"]:
        if p["platform"] == cft_platform:
            backup_url = p["url"]

    log("Found backup chromedriver")

    if not backup_url:
        raise Exception("Platform not found")

    return backup_url, backup_revision, backup_version


def get_version_from_json(data, channel):
    return data["channels"][channel]["version"].split(".")[0]


def insert_channel_in_archive_name(filename, channel):
    parts = filename.rsplit(".", maxsplit=2)
    if len(parts) != 3:
        raise ValueError(
            f"Unexpected filename format: '{filename}'. Expected a file with two extensions (e.g., '.tar.bz2')."
        )
    return f"{parts[0]}-{channel.lower()}.{parts[1]}.{parts[2]}"


def build_cft_archive(platform, channel, backup, version):
    """Download and store a chromedriver for a given platform."""
    upload_dir = os.environ.get("UPLOAD_DIR")
    if upload_dir:
        # Create the upload directory if it doesn't exist.
        try:
            log("Creating upload directory in %s..." % os.path.abspath(upload_dir))
            os.makedirs(upload_dir)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

    cft_platform = CHROME_FOR_TESTING_INFO[platform]["platform"]

    data = get_cft_metadata()
    if backup:
        cft_chromedriver_url, revision, payload_version = get_backup_chromedriver(
            version, data, cft_platform
        )
        tar_file = CHROME_FOR_TESTING_INFO[platform]["result_backup"]
    else:
        cft_chromedriver_url = get_cd_url(data, cft_platform, channel)
        revision = get_chromedriver_revision(data, channel)
        payload_version = get_version_from_json(data, channel)
        # For clarity, include channel in artifact name.
        tar_file = insert_channel_in_archive_name(
            CHROME_FOR_TESTING_INFO[platform]["result"], channel
        )
    # Make a temporary location for the file
    tmppath = tempfile.mkdtemp()

    # Create the directory format expected for browsertime setup in taskgraph transform
    artifact_dir = CHROME_FOR_TESTING_INFO[platform]["dir"]
    if backup or channel in ("Stable", "Beta"):
        # need to prepend the major version to the artifact dir due to how raptor browsertime
        # ensures the correct version is used with chrome stable.
        artifact_dir = payload_version + artifact_dir
    cft_dir = os.path.join(tmppath, artifact_dir)
    os.mkdir(cft_dir)

    # Store the revision number and chromedriver
    fetch_chromedriver(cft_chromedriver_url, cft_dir)
    revision_file = os.path.join(cft_dir, ".REVISION")
    with open(revision_file, "w+") as f:
        f.write(str(revision))

    tar_command = ["tar", "cjf", tar_file, "-C", tmppath, artifact_dir]
    log("Revision is %s" % revision)
    log("Added revision to %s file." % revision_file)

    log("Tarring with the command: %s" % str(tar_command))
    subprocess.check_call(tar_command)

    upload_dir = os.environ.get("UPLOAD_DIR")
    if upload_dir:
        # Move the tarball to the output directory for upload.
        log("Moving %s to the upload directory..." % tar_file)
        shutil.copy(tar_file, os.path.join(upload_dir, tar_file))

    shutil.rmtree(tmppath)


def parse_args():
    """Read command line arguments and return options."""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--platform",
        help="Corresponding platform of CfT chromedriver to fetch.",
        required=True,
    )
    # Bug 1869592 - Add optional flag to provide CfT channel e.g. Canary, Stable, etc.
    parser.add_argument(
        "--channel",
        help="Corresponding channel of CfT chromedriver to fetch.",
        required=False,
        default="Canary",
    )
    parser.add_argument(
        "--backup",
        help="Determine if we are grabbing a backup chromedriver version.",
        required=False,
        default=False,
        action="store_true",
    )
    parser.add_argument(
        "--version",
        help="Pin the revision if necessary for current platform",
        required=False,
        default="",
    )
    return parser.parse_args()


if __name__ == "__main__":
    args = vars(parse_args())
    build_cft_archive(**args)