copy-iuks-to-rsync-server-and-verify 6.94 KB
Newer Older
1
2
3
4
#!/usr/bin/python3

import argparse
import logging
5
6
import os
import re
7
8
9
10
11
import subprocess
import sys

from typing import List
from pathlib import Path
12
13
from urllib.parse import urlparse
from urllib.request import Request, urlopen
14

15
16
17
from bs4 import BeautifulSoup  # type: ignore

JENKINS_IUKS_BASE_URL = "https://nightly.tails.boum.org/build_IUKs"
18
19
20
21
22
23
24
25
RSYNC_SERVER_HOSTNAME = "rsync.lizard"
LOG_FORMAT = "%(asctime)-15s %(levelname)s %(message)s"
log = logging.getLogger()


def main():
    parser = argparse.ArgumentParser(
        description="Copy IUKs from Jenkins to our rsync server \
intrigeri's avatar
Lint    
intrigeri committed
26
27
28
29
30
31
32
33
34
        and verify that they match those built locally")
    parser.add_argument("--hashes-file",
                        type=str,
                        action="store",
                        required=True)
    parser.add_argument("--jenkins-build-id",
                        type=int,
                        action="store",
                        required=True)
35
    parser.add_argument("--work-dir", type=str, action="store", default=".")
intrigeri's avatar
Lint    
intrigeri committed
36
37
38
    parser.add_argument("-q",
                        "--quiet",
                        action="store_true",
39
40
                        help="quiet output")
    parser.add_argument("--debug", action="store_true", help="debug output")
intrigeri's avatar
Lint    
intrigeri committed
41
42
    parser.add_argument("--skip-sending-hashes-file",
                        action="store_true",
43
                        help="Assume the hashes file was uploaded already")
intrigeri's avatar
Lint    
intrigeri committed
44
45
    parser.add_argument("--skip-downloading-iuks",
                        action="store_true",
46
47
48
49
                        help="Assume the IUKs were already downloaded")
    args = parser.parse_args()

    if args.debug:
segfault's avatar
segfault committed
50
        logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)
51
    elif args.quiet:
segfault's avatar
segfault committed
52
        logging.basicConfig(level=logging.WARN, format=LOG_FORMAT)
53
    else:
segfault's avatar
segfault committed
54
        logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
55
56

    if not Path(args.hashes_file).exists():
intrigeri's avatar
Lint    
intrigeri committed
57
        log.error("%s does not exist", args.hashes_file)
58
59
60
61
62
63
        sys.exit(1)

    if not args.skip_sending_hashes_file:
        send_hashes_file(
            hashes_file=args.hashes_file,
            desthost=RSYNC_SERVER_HOSTNAME,
64
            destdir=args.work_dir,
65
66
67
68
69
70
        )

    if not args.skip_downloading_iuks:
        download_iuks_from_jenkins(
            hashes_file=args.hashes_file,
            desthost=RSYNC_SERVER_HOSTNAME,
71
            destdir=args.work_dir,
72
73
74
75
76
77
            jenkins_iuks_base_url=JENKINS_IUKS_BASE_URL,
            jenkins_build_id=args.jenkins_build_id,
        )

    verify_iuks(
        desthost=RSYNC_SERVER_HOSTNAME,
78
79
        iuks_dir=args.work_dir,
        hashes_file=Path(args.work_dir, args.hashes_file).name,
80
81
82
    )


intrigeri's avatar
Lint    
intrigeri committed
83
def send_hashes_file(hashes_file: str, desthost: str, destdir: str) -> None:
84
    log.info("Sending %(f)s to %(d)s on %(h)s…" % {
85
        "f": hashes_file,
86
        "d": destdir,
87
88
89
        "h": desthost,
    })
    subprocess.run(
intrigeri's avatar
Lint    
intrigeri committed
90
        ["scp", hashes_file, "%s:%s" % (desthost, destdir)], check=True)
91
92
93
94
95


def iuks_listed_in(hashes_file: str) -> List[str]:
    with Path(hashes_file).open() as f:
        lines = f.readlines()
intrigeri's avatar
Lint    
intrigeri committed
96
    return [line.split('  ')[-1].rstrip() for line in lines]
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
def get_jenkins_iuks_urls(jenkins_iuks_base_url: str,
                          jenkins_build_id: int) -> List[str]:
    urls: List[str] = []
    source_version_index_url = jenkins_iuks_base_url + \
        "/configurations/axis-SOURCE_VERSION"
    for source_version_url in [
            source_version_index_url + '/' + link.get('href')
            for link in BeautifulSoup(
                urlopen(Request(source_version_index_url)),
                'html.parser').find_all(href=re.compile('^[1-9]'))
    ]:
        axis_label_index_url = source_version_url + "axis-label_exp/"
        log.debug("Looking at %s", axis_label_index_url)
        label_urls = [
            axis_label_index_url + link.get('href')
            for link in BeautifulSoup(urlopen(Request(axis_label_index_url)),
                                      'html.parser').find_all(
                                          href=re.compile('^[a-z]'))
        ]
        if len(label_urls) == 0:
            log.debug("Found no label URL in %s, ignoring this source version",
                      axis_label_index_url)
            continue
        if len(label_urls) > 1:
            log.error("Found too many label URLs in %s: %s",
                      axis_label_index_url, label_urls)
            sys.exit(1)
        label_url = label_urls[0]

        artifacts_index_url = label_url + '/builds/' + str(
            jenkins_build_id) + '/archive/'
        log.debug("Looking at %s", artifacts_index_url)
        iuk_urls = [
            artifacts_index_url + link.get('href') for link in BeautifulSoup(
                urlopen(Request(artifacts_index_url)), 'html.parser').find_all(
                    href=re.compile('[.]iuk$'))
        ]
        if len(iuk_urls) == 0:
            log.debug("Found no IUK URL in %s, ignoring this source version",
                      artifacts_index_url)
            continue
        if len(iuk_urls) > 1:
            log.error("Found too many IUK URLs in %s: %s", artifacts_index_url,
                      iuk_urls)
            sys.exit(1)
        else:
            iuk_url = iuk_urls[0]
        urls.append(iuk_url)
    log.debug("Found IUK URLs: %s", urls)
    return urls


intrigeri's avatar
Lint    
intrigeri committed
151
152
153
def download_iuks_from_jenkins(hashes_file: str, desthost: str, destdir: str,
                               jenkins_iuks_base_url: str,
                               jenkins_build_id: int) -> None:
intrigeri's avatar
Lint    
intrigeri committed
154
    log.info("Downloading IUKs from Jenkins to %s…", desthost)
155
    expected_iuks = iuks_listed_in(hashes_file)
intrigeri's avatar
Lint    
intrigeri committed
156
    log.debug("IUKS: %s", ', '.join(expected_iuks)
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
    jenkins_iuks_urls = get_jenkins_iuks_urls(jenkins_iuks_base_url,
                                              jenkins_build_id)
    jenkins_iuks = [
        os.path.basename(urlparse(url).path) for url in jenkins_iuks_urls
    ]
    if set(expected_iuks) != set(jenkins_iuks):
        log.error(
            "Jenkins' set of IUKs differs from local one:\n"
            " - locally: %s\n"
            " - Jenkins: %s\n",
            expected_iuks, jenkins_iuks)
        sys.exit(1)
    for iuk_url in jenkins_iuks_urls:
        log.debug("Downloading %s to %s", iuk_url, destdir)
        subprocess.run([
            "ssh", desthost, "wget", "--quiet", "--no-clobber",
            "--directory-prefix=%s" % destdir, iuk_url
        ],
                       check=True)
176
177


178
def verify_iuks(desthost: str, iuks_dir: str, hashes_file: str) -> None:
179
180
    log.info("Verifying that IUKs built on Jenkins match those you've built…")
    try:
intrigeri's avatar
Lint    
intrigeri committed
181
182
183
184
185
186
187
188
        subprocess.run([
            "ssh", desthost,
            "cd '%(d)s' && sha256sum --check --strict '%(f)s'" % {
                "d": iuks_dir,
                "f": Path(hashes_file).name,
            }
        ],
                       check=True)
189
190
191
192
193
194
    except subprocess.CalledProcessError:
        print("\nERROR: IUKs built on Jenkins don't match yours\n",
              file=sys.stderr)


if __name__ == "__main__":
segfault's avatar
segfault committed
195
    main()