/usr/bin/mirrorkit is in mirrorkit 0.2.1.
This file is owned by root:root, with mode 0o755.
The actual contents of the file can be viewed below.
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 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2013 Stéphane Graber
# Author: Stéphane Graber <stgraber@ubuntu.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You can find the license on Debian systems in the file
# /usr/share/common-licenses/GPL-2
import argparse
import configparser
import logging
import os
import string
import subprocess
import sys
import tempfile
import time
import urllib.parse
def get_path_size(path):
total_size = 0
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
def parse_config(path):
"""
Return a dict representation of a .ini config
"""
config = {}
configp = configparser.ConfigParser()
try:
configp.read(path)
except:
return config
for section in configp.sections():
config_section = {}
for option in configp.options(section):
value = configp.get(section, option)
if ", " in value:
value = [entry.strip('"').strip()
for entry in value.split(", ")]
else:
value = value.strip('"').strip()
config_section[option] = value
config[section] = config_section
return config
def load_config(config_path):
"""
Read an ini configuration file and return a MirrorKitConfig object.
"""
# Get a dict representation of the config
config = parse_config(config_path)
# Process the global section
settings = {}
if not "global" in config:
logging.error("Missing 'global' config section.")
return None
if not config['global'].get("publish_path", None):
logging.error("Missing 'publish_path' value.")
return None
settings['publish_path'] = config['global']['publish_path']
settings['log_path'] = config['global'].get("log_path", None)
if settings['log_path']:
if not config['global'].get("log_template_path", None):
logging.error("Missing 'log_template_path' value.")
return None
settings['log_template_path'] = config['global'].get(
"log_template_path", None)
settings['apache_conf_path'] = config['global'].get("apache_conf_path",
None)
settings['http_base'] = config['global'].get("http_base", "/")
settings['mirrors'] = []
for mirror_name in config['global'].get("mirrors", []):
mirror = {}
mirror['name'] = mirror_name
if mirror_name not in config:
logging.error("Couldn't find settings for mirror: %s" %
mirror_name)
return None
mirror['source'] = config[mirror_name].get("source", None)
mirror['sources'] = config[mirror_name].get("sources", False) == "true"
for key in ("pockets", "components", "sub-components",
"architectures"):
value = config[mirror_name].get(key, None)
if not isinstance(value, list):
value = [value]
mirror[key] = value
# Expand sub-components
extra_components = []
for entry in mirror['sub-components']:
for component in mirror['components']:
extra_components.append("%s/%s" % (component, entry))
mirror['components'] += extra_components
mirror.pop("sub-components")
for key in ("source", "pockets", "components", "architectures"):
if not mirror[key]:
logging.error("Missing value for '%s' in mirror: %s" %
(key, mirror_name))
return None
settings['mirrors'].append(type("MirrorKitMirror", (object,), mirror))
# Create our fake object
return type("MirrorKitConfig", (object,), settings)
def debmirror_command(config, mirror):
"""
Generate the appropriate debmirror command.
"""
url = urllib.parse.urlparse(mirror.source)
if not url:
logging.error("Invalid URL: %s" % url)
return None
if url.scheme not in ("http", "https", "ftp", "rsync"):
logging.error("Invalid URL scheme: %s" % url.scheme)
return None
cmd = ["debmirror", "-v",
"--host=%s" % url.netloc,
"--root=%s" % url.path,
"--arch=%s" % ",".join(mirror.architectures),
"--dist=%s" % ",".join(mirror.pockets),
"--section=%s" % ",".join(mirror.components),
"--progress",
"--method=%s" % url.scheme,
"--ignore-release-gpg"]
if not mirror.sources:
cmd += ["--nosource"]
cmd += [os.path.join(config.publish_path, mirror.name)]
return cmd
def run_debmirror(config, mirror, log):
"""
Run debmirror.
Output is written to stdout and stderr.
"""
cmd = debmirror_command(config, mirror)
if not cmd:
return None
if subprocess.call(cmd, stdout=log, stderr=log,
universal_newlines=True) != 0:
logging.error("debmirror failed to run for: %s" % mirror.name)
return None
return (True, cmd)
def generate_report(config, mirror, success, log):
log_filename = "%s.%s.html" % (mirror.name,
time.strftime("%Y%m%d.%H-%M-%S",
time.gmtime()))
log_file = os.path.join(config.log_path, log_filename)
log.seek(0)
variables = {'date': time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()),
'name': mirror.name,
'status': "Success" if success else "Failure",
'status_html': "<span id=\"success\">Success</span>"
if success else
"<span id=\"failure\">Failure</span>",
'size': round(get_path_size(os.path.join(
config.publish_path, mirror.name)) / 1048576, 2),
'source': mirror.source,
'destination': os.path.join(config.publish_path, mirror.name),
'pockets': ", ".join(mirror.pockets),
'components': ", ".join(mirror.components),
'architectures': ", ".join(mirror.architectures),
'sources': "yes" if mirror.sources else "no",
'command': " ".join(debmirror_command(config, mirror)),
'log': log.read()}
# Generate the html file
with open(log_file, "w+") as log_fd:
with open(config.log_template_path, "r") as fd:
template_str = fd.read()
template = string.Template(template_str)
log_fd.write(template.safe_substitute(variables))
# Create symlink
log_symlink = os.path.join(config.log_path, "%s.html" % mirror.name)
if os.path.exists(log_symlink):
os.remove(log_symlink)
os.symlink(log_filename, log_symlink)
def generate_apache_conf(config):
if not os.path.exists(os.path.dirname(config.apache_conf_path)):
logging.info("Apache configuration directory doesn't exist, skipping")
return
with open(config.apache_conf_path, "w+") as fd:
for mirror in config.mirrors:
fd.write("Alias %s %s\n" % (os.path.join(config.http_base,
mirror.name),
os.path.join(config.publish_path,
mirror.name)))
if config.log_path:
fd.write("Alias %s %s\n" % (os.path.join(config.http_base, "logs"),
config.log_path))
fd.write("""
<Location %s>
Options Indexes FollowSymLinks MultiViews
<IfVersion < 2.3 >
Order allow,deny
Allow from all
</IfVersion>
<IfVersion >= 2.3>
Require all granted
</IfVersion>
</Location>
""" % (os.path.join(config.http_base, "logs")))
for mirror in config.mirrors:
rel_path = os.path.join(config.http_base, mirror.name)
rel_path_escaped = rel_path.replace("/", "\\/")
fd.write("""
<Location %s>
RewriteEngine On
RewriteCond %%{REQUEST_FILENAME} !-f
RewriteCond %%{REQUEST_FILENAME} !-d
RewriteRule .*%s\/pool\/(.*) %s.orig/pool/$1 [L]
RewriteRule .*%s\/dists\/(.*) %s.orig/dists/$1 [L]
Options Indexes FollowSymLinks MultiViews
<IfVersion < 2.3 >
Order allow,deny
Allow from all
</IfVersion>
<IfVersion >= 2.3>
Require all granted
</IfVersion>
</Location>
<Location %s/project>
Deny from all
</Location>
ProxyPass %s.orig/ %s/
""" % (rel_path,
rel_path_escaped, rel_path,
rel_path_escaped, rel_path,
rel_path,
rel_path, mirror.source))
fd.write("ProxyRequests off")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="mirrorkit")
parser.add_argument("--config", metavar="CONFIG",
help="Path to the configuration file",
default="/etc/mirrorkit.conf")
args = parser.parse_args()
# Basic checks
if not os.path.exists(args.config):
parser.error("Configuration file doesn't exist: %s" % args.config)
sys.exit(1)
# Load the configuration
config = load_config(args.config)
if not config:
sys.error(1)
if not config.mirrors:
sys.exit(0)
# Check if template exists
if config.log_template_path:
if not os.path.exists(config.log_template_path):
parser.error("Missing log template: %s" % config.log_template_path)
sys.exit(1)
# Create any missing path
if not os.path.exists(config.publish_path):
logging.debug("Creating missing path: %s" % config.publish_path)
os.makedirs(config.publish_path)
if config.log_path and not os.path.exists(config.log_path):
logging.debug("Creating missing path: %s" % config.log_path)
os.makedirs(config.log_path)
# Start the mirroring
for mirror in config.mirrors:
logging.info("Beginning to mirror: %s" % mirror.name)
log_fd, log_path = tempfile.mkstemp()
log = os.fdopen(log_fd)
retval = run_debmirror(config, mirror, log)
logging.info("Done mirroring: %s" % mirror.name)
if config.log_path:
logging.info("Generating html report for: %s" % mirror.name)
generate_report(config, mirror, retval is not None, log)
log.close()
os.remove(log_path)
# Generate the http configuration
if config.apache_conf_path:
logging.info("Generating apache2 configuration: %s" %
config.apache_conf_path)
generate_apache_conf(config)
|