1import shlex
2import subprocess
3import re
4
5
6class PkgMirror:
7    """class to handle pkg mirrors"""
8
9    def __init__(self, mirror):
10        self.benchmark_files = (
11            "http://%%SERVER%%/%%ABI%%/%%RELEASE%%/packagesite.txz",
12            "http://%%SERVER%%/%%ABI%%/%%RELEASE%%/meta.txz",
13            "http://%%SERVER%%/%%ABI%%/%%RELEASE%%/digests.txz",
14            "http://%%SERVER%%/%%ABI%%/%%RELEASE%%/Latest/pkg.txz",
15        )
16        self.mirror = mirror
17        self.abi, self.release = self.get_info()
18
19    @classmethod
20    def get_info(cls):
21        """get ABI string from pkg -vv"""
22        cmd = "/usr/local/sbin/pkg-static -vv"
23        proc = subprocess.Popen(
24            shlex.split(cmd),
25            stdout=subprocess.PIPE,
26            stderr=subprocess.PIPE,
27            shell=False,
28        )
29        out, err = proc.communicate()
30
31        if err:
32            raise Exception("pkg-static returned an error")
33
34        abi = None
35        release = None
36
37        abi_match = re.search(r"\nABI\s+=\s+\"([^\"]*)\"", out.decode("utf-8"))
38        if abi_match:
39            abi = abi_match.group(1)
40
41        release_match = re.search(r"\n\s+url\s+:\s+\".*/(.*)\"", out.decode("utf-8"))
42        if release_match:
43            release = release_match.group(1)
44
45        return (abi, release)
46
47    def get_urls(self):
48        """returns a list of possible files to download from a mirror"""
49        urls = []
50        for rfile in self.benchmark_files:
51            rfile = re.sub("%%SERVER%%", self.mirror, rfile)
52            rfile = re.sub("%%ABI%%", self.abi, rfile)
53            rfile = re.sub("%%RELEASE%%", self.release, rfile)
54            urls.append(rfile)
55
56        return urls
57