/usr/lib/python2.7/dist-packages/linkcheck/director/aggregator.py is in linkchecker 9.3-5.
This file is owned by root:root, with mode 0o644.
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 | # -*- coding: iso-8859-1 -*-
# Copyright (C) 2006-2014 Bastian Kleineidam
#
# 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 should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Aggregate needed object instances for checker threads.
"""
import threading
import thread
import requests
import time
import urlparse
import random
from .. import log, LOG_CHECK, strformat, LinkCheckerError
from ..decorators import synchronized
from ..cache import urlqueue
from ..htmlutil import formsearch
from . import logger, status, checker, interrupt
_threads_lock = threading.RLock()
_hosts_lock = threading.RLock()
_downloadedbytes_lock = threading.RLock()
def new_request_session(config, cookies):
"""Create a new request session."""
session = requests.Session()
if cookies:
session.cookies = cookies
session.max_redirects = config["maxhttpredirects"]
session.headers = {
"User-Agent": config["useragent"],
}
if config["cookiefile"]:
for cookie in cookies.from_file(config["cookiefile"]):
session.cookies = requests.cookies.merge_cookies(session.cookies, cookie)
return session
class Aggregate (object):
"""Store thread-safe data collections for checker threads."""
def __init__ (self, config, urlqueue, robots_txt, plugin_manager,
result_cache):
"""Store given link checking objects."""
self.config = config
self.urlqueue = urlqueue
self.logger = logger.Logger(config)
self.threads = []
self.request_sessions = {}
self.robots_txt = robots_txt
self.plugin_manager = plugin_manager
self.result_cache = result_cache
self.times = {}
self.cookies = None
requests_per_second = config["maxrequestspersecond"]
self.wait_time_min = 1.0 / requests_per_second
self.wait_time_max = max(self.wait_time_min + 0.5, 0.5)
self.downloaded_bytes = 0
def visit_loginurl(self):
"""Check for a login URL and visit it."""
url = self.config["loginurl"]
if not url:
return
user, password = self.config.get_user_password(url)
session = requests.Session()
# XXX user-agent header
# XXX timeout
response = session.get(url)
cgiuser = self.config["loginuserfield"]
cgipassword = self.config["loginpasswordfield"]
form = formsearch.search_form(response.content, cgiuser, cgipassword,
encoding=response.encoding)
form.data[cgiuser] = user
form.data[cgipassword] = password
for key, value in self.config["loginextrafields"].items():
form.data[key] = value
formurl = urlparse.urljoin(url, form.url)
response = session.post(formurl, data=form.data)
self.cookies = session.cookies
if len(self.cookies) == 0:
raise LinkCheckerError("No cookies set by login URL %s" % url)
@synchronized(_threads_lock)
def start_threads (self):
"""Spawn threads for URL checking and status printing."""
if self.config["status"]:
t = status.Status(self, self.config["status_wait_seconds"])
t.start()
self.threads.append(t)
if self.config["maxrunseconds"]:
t = interrupt.Interrupt(self.config["maxrunseconds"])
t.start()
self.threads.append(t)
num = self.config["threads"]
if num > 0:
for dummy in range(num):
t = checker.Checker(self.urlqueue, self.logger, self.add_request_session)
self.threads.append(t)
t.start()
else:
self.request_sessions[thread.get_ident()] = new_request_session(self.config, self.cookies)
checker.check_urls(self.urlqueue, self.logger)
@synchronized(_threads_lock)
def add_request_session(self):
"""Add a request session for current thread."""
session = new_request_session(self.config, self.cookies)
self.request_sessions[thread.get_ident()] = session
@synchronized(_threads_lock)
def get_request_session(self):
"""Get the request session for current thread."""
return self.request_sessions[thread.get_ident()]
@synchronized(_hosts_lock)
def wait_for_host(self, host):
"""Throttle requests to one host."""
t = time.time()
if host in self.times:
due_time = self.times[host]
if due_time > t:
wait = due_time - t
time.sleep(wait)
t = time.time()
wait_time = random.uniform(self.wait_time_min, self.wait_time_max)
self.times[host] = t + wait_time
@synchronized(_threads_lock)
def print_active_threads (self):
"""Log all currently active threads."""
debug = log.is_debug(LOG_CHECK)
if debug:
first = True
for name in self.get_check_threads():
if first:
log.info(LOG_CHECK, _("These URLs are still active:"))
first = False
log.info(LOG_CHECK, name[12:])
args = dict(
num=len([x for x in self.threads if x.getName().startswith("CheckThread-")]),
timeout=strformat.strduration_long(self.config["aborttimeout"]),
)
log.info(LOG_CHECK, _("%(num)d URLs are still active. After a timeout of %(timeout)s the active URLs will stop.") % args)
@synchronized(_threads_lock)
def get_check_threads(self):
"""Return iterator of checker threads."""
for t in self.threads:
name = t.getName()
if name.startswith("CheckThread-"):
yield name
def cancel (self):
"""Empty the URL queue."""
self.urlqueue.do_shutdown()
def abort (self):
"""Print still-active URLs and empty the URL queue."""
self.print_active_threads()
self.cancel()
timeout = self.config["aborttimeout"]
try:
self.urlqueue.join(timeout=timeout)
except urlqueue.Timeout:
log.warn(LOG_CHECK, "Abort timed out after %d seconds, stopping application." % timeout)
raise KeyboardInterrupt()
@synchronized(_threads_lock)
def remove_stopped_threads (self):
"""Remove the stopped threads from the internal thread list."""
self.threads = [t for t in self.threads if t.is_alive()]
@synchronized(_threads_lock)
def finish (self):
"""Wait for checker threads to finish."""
if not self.urlqueue.empty():
# This happens when all checker threads died.
self.cancel()
for t in self.threads:
t.stop()
@synchronized(_threads_lock)
def is_finished (self):
"""Determine if checking is finished."""
self.remove_stopped_threads()
return self.urlqueue.empty() and not self.threads
@synchronized(_downloadedbytes_lock)
def add_downloaded_bytes(self, numbytes):
"""Add to number of downloaded bytes."""
self.downloaded_bytes += numbytes
def end_log_output(self, **kwargs):
"""Print ending output to log."""
kwargs.update(dict(
downloaded_bytes=self.downloaded_bytes,
num_urls = len(self.result_cache),
))
self.logger.end_log_output(**kwargs)
|