class GQueue(object): def __init__(self): self.__QUEUE = JoinableQueue() def job(self, func): @functools.wraps(func) def f(*args, **kwargs): self.__QUEUE.put([func, args, kwargs]) return f def join(self): self.__QUEUE.join() def work(self): while True: func, args, kwargs = self.__QUEUE.get() try: func(*args, **kwargs) finally: self.__QUEUE.task_done() def run_worker(self, num=1): for i in range(num): gevent.spawn(self.work)
def on_search(self, query): log.debug('search for %r', query) queue = JoinableQueue() task_group = g.api.search(query, queue) while True: finished = all( [t.ready() for t in task_group] ) try: item = queue.get(timeout=1.0) except Empty: if finished: break continue try: self.emit('result', item._asdict()) finally: queue.task_done() queue.join() task_group.join() self.emit('done', query)
class Dispatcher(gevent.Greenlet): """ The Dispatcher class handles routing communications to and from the Gateway. It implements an Actor interface as made popular by Erlang. """ def __init__(self): self._gw_inbox = JoinableQueue() super().__init__() def _run(self): while True: try: event = self._gw_inbox.get(block=False) # Dispatch the event back to interface self._gw_inbox.task_done() finally: gevent.sleep(1) @property def gw_inbox(self): """ This is the inbox for the Gateway. It's not accessible outside the class methods. :return: None """ return None @gw_inbox.setter def gw_inbox(self, message): self._gw_inbox.put(message)
def test_api(self): queue = JoinableQueue() task_group = self.api.search('terminator', queue) while True: finished = all( [greenlet.ready() for greenlet in task_group.greenlets] ) try: item = queue.get(timeout=1.0) except Empty: if finished: log.info('queue is empty and all jobs are done, quitting') break log.info( 'queue was empty and jobs are still running, retrying' ) continue try: log.info('%r', item) finally: queue.task_done() task_group.join() queue.join() log.info('joined everything')
class Speaker(gevent.Greenlet): RATE = 44100 def __init__(self, rcv): gevent.Greenlet.__init__(self) self.rcv = rcv PA = pyaudio.PyAudio() self.pa= PA.open( format= pyaudio.paInt16, channels= 1, rate= self.RATE, output= True ) self.queue = JoinableQueue() def _run(self): print 'spk_on' while True: try: buf = self.rcv.queue.get() except gevent.queue.Empty: buf = '\0' ## print '.', self.pa.write(buf) time.sleep(0.0001) self.queue.task_done() self.pa.close()
def test_api(self): queue = JoinableQueue() task_group = self.api.search('terminator', queue) while True: finished = all( [greenlet.ready() for greenlet in task_group.greenlets]) try: item = queue.get(timeout=1.0) except Empty: if finished: log.info('queue is empty and all jobs are done, quitting') break log.info( 'queue was empty and jobs are still running, retrying') continue try: log.info('%r', item) finally: queue.task_done() task_group.join() queue.join() log.info('joined everything')
class GeventPoolExecutor2(LoggerMixin): def __init__( self, max_works, ): check_gevent_monkey_patch() self._q = JoinableQueue(maxsize=max_works) # self._q = Queue(maxsize=max_works) for _ in range(max_works): # self.logger.debug('yyyyyy') gevent.spawn(self.__worker) atexit.register(self.__atexit) def __worker(self): while True: fn, args, kwargs = self._q.get() # noinspection PyBroadException try: fn(*args, **kwargs) except Exception as exc: self.logger.exception( f'函数 {fn.__name__} 中发生错误,错误原因是 {type(exc)} {exc} ') finally: pass self._q.task_done() def submit(self, fn: Callable, *args, **kwargs): # self.logger.debug(self._q.qsize()) self._q.put((fn, args, kwargs)) def __atexit(self): self.logger.critical('想即将退出程序。') self._q.join()
class GeventPoolExecutor2(LoggerMixin): def __init__( self, max_works, ): self._q = JoinableQueue(maxsize=max_works) # self._q = Queue(maxsize=max_works) for _ in range(max_works): gevent.spawn(self.__worker) # atexit.register(self.__atexit) self._q.join(timeout=100) def __worker(self): while True: fn, args, kwargs = self._q.get() try: fn(*args, **kwargs) except Exception as exc: self.logger.exception( f'函数 {fn.__name__} 中发生错误,错误原因是 {type(exc)} {exc} ') finally: pass self._q.task_done() def submit(self, fn: Callable, *args, **kwargs): self._q.put((fn, args, kwargs)) def __atexit(self): self.logger.critical('想即将退出程序。') self._q.join()
def fetch_worker(fetch_queue: JoinableQueue, save_queue: JoinableQueue, direction: str): while True: word = fetch_queue.get() print(word) res = fetch(word) if res: save_queue.put((word, direction, res)) fetch_queue.task_done() else: fetch_queue.put(word)
def save_worker(dsn: str, save_queue: JoinableQueue): conn = psycopg2.connect(dsn) while True: word, direction, data = save_queue.get() try: with conn: with conn.cursor() as cur: psycopg2.extensions.register_type(psycopg2.extensions.UNICODE, cur) cur.execute("INSERT INTO youdao_bilingual (keyword, direction, data) VALUES (%s, %s, %s)", (word, direction, data)) save_queue.task_done() except Exception as e: print(e) save_queue.put((word, direction, data)) conn.close()
def _run(self): paths = glob.glob(self.path) while not paths: gevent.sleep(0.01) paths = glob.glob(self.path) q = JoinableQueue() self.logger.debug('Tailing %s' % ', '.join(paths)) self.tails = [Tail(p, q, self.statedir) for p in paths] while True: data = q.get() if data: if data.endswith('\n'): data = data[0:-1] self.logger.debug('Received: %r' % data) self.output.put(Event(data=data)) q.task_done()
class MassGet(FastGet): def __init__(self, urls, dic, threads=10, report_db=False, keepalive=None, each_threads=10): self.dic = dic self.report_db = report_db self.table = None if report_db: self.sql_conn(report_db) self.keepalive = keepalive self.each_threads = each_threads self.queue = JoinableQueue() [self.queue.put(x.strip()) for x in urls] [spawn(self.worker) for _ in xrange(threads)] self.queue.join() def worker(self): while not self.queue.empty(): url = self.queue.get() try: FastGet(url, self.dic, self.each_threads, self.report_db, self.keepalive, self.table) except Exception as e: logging.error('Worker global exception for %s: %s' % (url, e)) finally: self.queue.task_done()
request['jsonParams'], request['view_url']) if not (result is None): url = request['result_url'] data = urllib.urlencode(json.loads(result)) req = urllib2.Request(url, data) f = urllib2.urlopen(req) response = f.read() f.close() except Exception, e: log.error("Exception! - error returning results") log.error(e) finally: pqueue.task_done() #////////////////////////////////////////////////////////// # MAIN FUNCTION #////////////////////////////////////////////////////////// def main(): global datadb, resourcedb global um, pm, im #------------------------------- # setup logging #------------------------------- log.setLevel(logging.DEBUG)
class ScoringService(Service): """A service that assigns a score to submission results. A submission result is ready to be scored when its compilation is unsuccessful (in this case, no evaluation will be performed) or after it has been evaluated. The goal of scoring is to use the evaluations to determine score, score_details, public_score, public_score_details and ranking_score_details (all non-null). Scoring is done by the compute_score method of the ScoreType defined by the dataset of the result. ScoringService keeps a queue of (submission_id, dataset_id) pairs identifying submission results to score. A greenlet is spawned to consume this queue, one item at a time. The queue is filled by the new_evaluation and the invalidate_submissions RPC methods, and by a sweeper greenlet, whose duty is to regularly check all submissions in the database and put the unscored ones in the queue (this check can also be forced by the search_jobs_not_done RPC method). """ # How often we look for submission results not scored. SWEEPER_TIMEOUT = 347.0 def __init__(self, shard): """Initialize the ScoringService. """ Service.__init__(self, shard) # Set up communication with ProxyService. self.proxy_service = self.connect_to(ServiceCoord("ProxyService", 0)) # Set up and spawn the scorer. # TODO Link to greenlet: when it dies, log CRITICAL and exit. self._scorer_queue = JoinableQueue() gevent.spawn(self._scorer_loop) # Set up and spawn the sweeper. # TODO Link to greenlet: when it dies, log CRITICAL and exit. self._sweeper_start = None self._sweeper_event = Event() gevent.spawn(self._sweeper_loop) def _scorer_loop(self): """Monitor the queue, scoring its top element. This is an infinite loop that, at each iteration, gets an item from the queue (blocking until there is one, if the queue is empty) and scores it. Any error during the scoring is sent to the logger and then suppressed, because the loop must go on. """ while True: submission_id, dataset_id = self._scorer_queue.get() try: self._score(submission_id, dataset_id) except Exception: logger.error("Unexpected error when scoring submission %d on " "dataset %d.", submission_id, dataset_id, exc_info=True) finally: self._scorer_queue.task_done() def _score(self, submission_id, dataset_id): """Assign a score to a submission result. This is the core of ScoringService: here we retrieve the result from the database, check if it is in the correct status, instantiate its ScoreType, compute its score, store it back in the database and tell ProxyService to update RWS if needed. submission_id (int): the id of the submission that has to be scored. dataset_id (int): the id of the dataset to use. """ with SessionGen() as session: # Obtain submission. submission = Submission.get_from_id(submission_id, session) if submission is None: raise ValueError("Submission %d not found in the database." % submission_id) # Obtain dataset. dataset = Dataset.get_from_id(dataset_id, session) if dataset is None: raise ValueError("Dataset %d not found in the database." % dataset_id) # Obtain submission result. submission_result = submission.get_result(dataset) # It means it was not even compiled (for some reason). if submission_result is None: raise ValueError("Submission result %d(%d) was not found." % (submission_id, dataset_id)) # Check if it's ready to be scored. if not submission_result.needs_scoring(): if submission_result.scored(): logger.info("Submission result %d(%d) is already scored.", submission_id, dataset_id) return else: raise ValueError("The state of the submission result " "%d(%d) doesn't allow scoring." % (submission_id, dataset_id)) # Instantiate the score type. score_type = get_score_type(dataset=dataset) # Compute score and fill it in the database. submission_result.score, \ submission_result.score_details, \ submission_result.public_score, \ submission_result.public_score_details, \ submission_result.ranking_score_details = \ score_type.compute_score(submission_result) # Store it. session.commit() # If dataset is the active one, update RWS. if dataset is submission.task.active_dataset: self.proxy_service.submission_scored( submission_id=submission.id) def _sweeper_loop(self): """Regularly check the database for unscored results. Try to sweep the database once every SWEEPER_TIMEOUT seconds but make sure that no two sweeps run simultaneously. That is, start a new sweep SWEEPER_TIMEOUT seconds after the previous one started or when the previous one finished, whatever comes last. The search_jobs_not_done RPC method can interfere with this regularity, as it tries to run a sweeper as soon as possible: immediately, if no sweeper is running, or as soon as the current one terminates. Any error during the sweep is sent to the logger and then suppressed, because the loop must go on. """ while True: self._sweeper_start = monotonic_time() self._sweeper_event.clear() try: self._sweep() except Exception: logger.error("Unexpected error when searching for unscored " "submissions.", exc_info=True) self._sweeper_event.wait(max(self._sweeper_start + self.SWEEPER_TIMEOUT - monotonic_time(), 0)) def _sweep(self): """Check the database for unscored submission results. Obtain a list of all the submission results in the database, check each of them to see if it's still unscored and, in case, put it in the queue. """ counter = 0 with SessionGen() as session: for sr in get_submission_results(session=session): if sr is not None and sr.needs_scoring(): self._scorer_queue.put((sr.submission_id, sr.dataset_id)) counter += 1 if counter > 0: logger.info("Found %d unscored submissions.", counter) @rpc_method def search_jobs_not_done(self): """Make the sweeper loop fire the sweeper as soon as possible. """ self._sweeper_event.set() @rpc_method def new_evaluation(self, submission_id, dataset_id): """Schedule the given submission result for scoring. Put it in the queue to have it scored, sooner or later. Usually called by EvaluationService when it's done with a result. submission_id (int): the id of the submission that has to be scored. dataset_id (int): the id of the dataset to use. """ self._scorer_queue.put((submission_id, dataset_id)) @rpc_method def invalidate_submission(self, submission_id=None, dataset_id=None, user_id=None, task_id=None, contest_id=None): """Invalidate (and re-score) some submission results. Invalidate the scores of the submission results that: - belong to submission_id or, if None, to any submission of user_id and/or task_id or, if both None, to any submission of contest_id or, if None, to any submission in the database. - belong to dataset_id or, if None, to any dataset of task_id or, if None, to any dataset of contest_id or, if None, to any dataset in the database. submission_id (int|None): id of the submission whose results should be invalidated, or None. dataset_id (int|None): id of the dataset whose results should be invalidated, or None. user_id (int|None): id of the user whose results should be invalidated, or None. task_id (int|None): id of the task whose results should be invalidated, or None. contest_id (int|None): id of the contest whose results should be invalidated, or None. """ logger.info("Invalidation request received.") # We can put results in the scorer queue only after they have # been invalidated (and committed to the database). Therefore # we temporarily save them somewhere else. temp_queue = list() with SessionGen() as session: submission_results = \ get_submission_results(contest_id, user_id, task_id, submission_id, dataset_id, session=session) for sr in submission_results: if sr.scored(): sr.invalidate_score() temp_queue.append((sr.submission_id, sr.dataset_id)) session.commit() for item in temp_queue: self._scorer_queue.put(item) logger.info("Invalidated %d submissions.", len(temp_queue))
class HttpScanner(object): def __init__(self, args): """ Initialise HTTP scanner :param args: :return: """ self.args = args self.output = HttpScannerOutput(args) self._init_scan_options() # Reading files self.output.write_log("Reading files and deduplicating.", logging.INFO) self.hosts = self._file_to_list(args.hosts) self.urls = self._file_to_list(args.urls) # self._calc_urls() out = 'Loaded %i hosts %i urls' % (self.hosts_count, self.urls_count) if self.args.ports is not None: out += ' %i ports' % len(self.args.ports) self.output.print_and_log(out) if self.args.ports is not None and not self.args.syn: new_hosts = [] for host in self.hosts: for port in self.args.ports: # print(host, port) new_hosts.append(helper.generate_url(host, port)) self.hosts = new_hosts # self._calc_urls() self.output.print_and_log('%i full urls to scan' % self.full_urls_count) # Queue and workers self.hosts_queue = JoinableQueue() self.workers = [] def _file_to_list(self, filename, dedup=True): """ Get list from file :param filename: file to read :return: list of lines """ if not path.exists(filename) or not path.isfile(filename): self.output.print_and_log('File %s not found!' % filename, logging.ERROR) exit(-1) # Preparing lines list lines = filter(lambda line: line is not None and len(line) > 0, open(filename).read().split('\n')) if len(lines) == 0: self.output.print_and_log('File %s is empty!' % filename, logging.ERROR) exit(-1) return helper.deduplicate(lines) if dedup else lines def _init_scan_options(self): # Session self.session = session() self.session.timeout = self.args.timeout self.session.verify = False # TODO: debug and check # self.session.mount("http://", HTTPAdapter(max_retries=self.args.max_retries)) # self.session.mount("https://", HTTPAdapter(max_retries=self.args.max_retries)) # http://stackoverflow.com/questions/15431044/can-i-set-max-retries-for-requests-request # Max retries adapters.DEFAULT_RETRIES = self.args.max_retries # TOR if self.args.tor: self.output.write_log("TOR usage detected. Making some checks.") self.session.proxies = { 'http': 'socks5://127.0.0.1:9050', 'https': 'socks5://127.0.0.1:9050' } url = 'http://ifconfig.me/ip' real_ip, tor_ip = None, None # Ger real IP address try: real_ip = get(url).text.strip() except Exception as exception: self.output.print_and_log("Couldn't get real IP address. Check yout internet connection.", logging.ERROR) self.output.write_log(str(exception), logging.ERROR) exit(-1) # Get TOR IP address try: tor_ip = self.session.get(url).text.strip() except Exception as exception: self.output.print_and_log("TOR socks proxy doesn't seem to be working.", logging.ERROR) self.output.write_log(str(exception), logging.ERROR) exit(-1) # Show IP addresses self.output.print_and_log('Real IP: %s TOR IP: %s' % (real_ip, tor_ip)) if real_ip == tor_ip: self.output.print_and_log("TOR doesn't work! Stop to be secure.", logging.ERROR) exit(-1) # Proxy if self.args.proxy is not None: self.session.proxies = {"https": self.args.proxy, "http": self.args.proxy} # Auth if self.args.auth is not None: items = self.args.auth.split(':') self.session.auth = (items[0], items[1]) # Cookies self.cookies = {} if self.args.cookies is not None: self.cookies = Cookies.from_request(self.args.cookies) # Cookies from file if self.args.load_cookies is not None: if not path.exists(self.args.load_cookies) or not path.isfile(self.args.load_cookies): self.output.print_and_log('Could not find cookie file: %s' % self.args.load_cookies, logging.ERROR) exit(-1) self.cookies = MozillaCookieJar(self.args.load_cookies) self.cookies.load() self.session.cookies = self.cookies # User-Agent self.ua = UserAgent() if self.args.random_agent else None def worker(self, worker_id): self.output.write_log('Worker %i started.' % worker_id) while not self.hosts_queue.empty(): host = self.hosts_queue.get() try: self.scan_host(worker_id, host) finally: self.output.write_log('Worker %i finished.' % worker_id) self.hosts_queue.task_done() def _head_available(self, host): """ Determine if HEAD requests is allowed :param host: :return: """ # Trying to use OPTIONS request try: response = self.session.options(host, headers=self._fill_headers()) o = response.headers['allow'] if 'allow' in response.headers else None if o is not None and o.find('HEAD') != -1: return True except: # TODO: fix pass try: return False if self.session.head(host, headers=self._fill_headers()).status_code == 405 else True except: # TODO: fix return False def scan_host(self, worker_id, host): # check if resolvable ip = helper.url_to_ip(host) if ip is None: self.output.write_log('Could not resolve %s Skipping...' % host, logging.WARNING) self.output.urls_scanned += len(self.urls) return # Check for HEAD host_url = helper.host_to_url(host) head_available = False if self.args.head: head_available = self._head_available(host) if head_available: self.output.write_log('HEAD is supported for %s' % host) errors_count, urls_scanned = 0, 0 for url in self.urls: full_url = urljoin(host_url, url) r = self.scan_url(full_url, head_available) urls_scanned += 1 self.output.urls_scanned += 1 # Output r['worker'] = worker_id self.output.write(**r) if r['exception'] is not None: errors_count += 1 # Skip host on errors if self.args.skip is not None and errors_count == self.args.skip: self.output.write_log('Errors limit reached on %s Skipping other urls.' % host, logging.WARNING) self.output.urls_scanned += len(self.urls) - urls_scanned break # cookies bugfix? self.session.cookies.clear() def _fill_headers(self): # Fill UserAgent in headers headers = {} if self.args.user_agent is not None: headers['User-agent'] = self.args.user_agent elif self.args.random_agent: headers['User-agent'] = self.ua.random # Fill Referer in headers if self.args.referer is not None: headers['Referer'] = self.args.referer return headers def _parse_response(self, url, response, exception): res = {'url': url, 'response': response, 'exception': exception} if response is None or exception is not None: res.update({ 'status': -1, 'length': -1, }) return res try: length = int(response.headers['content-length']) if 'content-length' in response.headers else len( response.text) except Exception as exception: self.output.write_log( "Exception while getting content length for URL: %s Exception: %s" % (url, str(exception)), logging.ERROR) length = 0 res.update({ 'status': response.status_code, 'length': length, }) return res def scan_url(self, url, use_head=False): self.output.write_log('Scanning %s' % url, logging.DEBUG) # Query URL and handle exceptions response, exception = None, None method = 'HEAD' if use_head else 'GET' try: # TODO: add support for user:password in URL response = self.session.request(method, url, headers=self._fill_headers(), allow_redirects=self.args.allow_redirects) except ConnectionError as ex: self.output.write_log('Connection error while quering %s' % url, logging.ERROR) exception = ex except HTTPError as ex: self.output.write_log('HTTP error while quering %s' % url, logging.ERROR) exception = ex except Timeout as ex: self.output.write_log('Timeout while quering %s' % url, logging.ERROR) exception = ex except TooManyRedirects as ex: self.output.write_log('Too many redirects while quering %s' % url, logging.ERROR) exception = ex except Exception as ex: self.output.write_log('Unknown exception while quering %s' % url, logging.ERROR) exception = ex # print('cookies: %s' % self.cookies) print('session.cookies: %s' % self.session.cookies) # self.session.cookies = self.cookies return self._parse_response(url, response, exception) def signal_handler(self): """ Signal hdndler :return: """ # TODO: add saving status via pickle self.output.print_and_log('Signal caught. Stopping...', logging.WARNING) self.stop() exit(signal.SIGINT) def _calc_urls(self): # Calculations self.urls_count = len(self.urls) self.hosts_count = len(self.hosts) self.full_urls_count = len(self.urls) * len(self.hosts) self.output.args.urls_count = self.full_urls_count def start(self): """ Start mulithreaded scan :return: """ # Set signal handler gevent.signal(signal.SIGTERM, self.signal_handler) gevent.signal(signal.SIGINT, self.signal_handler) gevent.signal(signal.SIGQUIT, self.signal_handler) # ICMP scan if self.args.icmp: if geteuid() != 0: self.output.print_and_log('To use ICMP scan option you must run as root. Skipping ICMP scan', logging.WARNING) else: self.output.print_and_log('Starting ICMP scan.') self.hosts = helper.icmp_scan(self.hosts, self.args.timeout) self._calc_urls() self.output.print_and_log('After ICMP scan %i hosts %i urls loaded, %i urls to scan' % (self.hosts_count, self.urls_count, self.full_urls_count)) # SYN scan if self.args.syn: if self.args.tor or self.args.proxy is not None: self.output.print_and_log('SYN scan via tor or proxy is impossible!', logging.WARNING) self.output.print_and_log('Stopping to prevent deanonymization!', logging.WARNING) exit(-1) if geteuid() != 0: self.output.print_and_log('To use SYN scan option you must run as root. Skipping SYN scan', logging.WARNING) else: self.output.print_and_log('Starting SYN scan.') self.hosts = helper.syn_scan(self.hosts, self.args.ports, self.args.timeout) self._calc_urls() self.output.print_and_log('After SYN scan %i hosts %i urls loaded, %i urls to scan' % (self.hosts_count, self.urls_count, self.full_urls_count)) # Check threds count vs hosts count if self.args.threads > self.hosts_count: self.output.write_log('Too many threads! Fixing threads count to %i' % self.hosts_count, logging.WARNING) threads_count = self.hosts_count else: threads_count = self.args.threads # Output urls count self.output.args.urls_count = self.full_urls_count # Start workers self.workers = [spawn(self.worker, i) for i in range(threads_count)] # Fill and join queue [self.hosts_queue.put(host) for host in self.hosts] self.hosts_queue.join() def stop(self): """ Stop scan :return: """ # TODO: stop correctly gevent.killall(self.workers)
request['view_url'] ) if not(result is None): url = request['result_url'] data = urllib.urlencode(json.loads(result)) req = urllib2.Request(url,data) f = urllib2.urlopen(req) response = f.read() f.close() except Exception, e: log.error("Exception! - error returning results") log.error(e) finally: pqueue.task_done() #////////////////////////////////////////////////////////// # MAIN FUNCTION #////////////////////////////////////////////////////////// def main(): global datadb, resourcedb global um,pm,im #------------------------------- # setup logging #------------------------------- log.setLevel( logging.DEBUG )
class LeakQueue(object): def __init__(self, maxsize=0, workers=10): """ Setup the gevent queue and the workers. :param int maxsize: the max lenght of the queue, default the queue size is infinite. :param int workers: the number of workers, default=10. """ self.queue = JoinableQueue(maxsize=maxsize) [spawn(self.worker) for x in xrange(workers)] def __repr__(self): return u'{} items in queue'.format(self.queue.qsize()) def put(self, operation, item, date=None): """ Each item are queued for a later processing. :param str operation: the operation name. :param item: the item to queued. :param date date: when the item is trigger. :returns: True if insertions succeeds, False otherwise. """ try: self.queue.put({ "operation": operation, "item": item, "date": date or datetime.utcnow() }) self.flush() except Exception as e: logger.critical( 'unable to put an item in the queue :: {}'.format(e)) return False else: return True def flush(self, force=False): """ Flush the queue and block until all tasks are done. :param boolean force: force the queue flushing :returns: True if the flush occurs, False otherwise. """ if self.queue.full() or force: logger.info('queue is full ({} items) :: flush it !'.format( self.queue.qsize())) self.queue.join() return True return False def worker(self): while True: try: item = self.queue.get() logger.info('get item :: {}'.format(item)) if not self.worker_process(item): logger.info('re-queue item :: {}'.format(item)) self.queue.put(item) except Empty: logger.info('queue is empty') else: self.queue.task_done() def worker_process(self, item): """ Default action execute by each worker. Must return a True statement to remove the item, otherwise the worker put the item into the queue. """ g_sleep() return item
class Migrator: def __init__(self, scheme, create_devices=True, write_data=True, start_date="2000-01-01T00:00:00Z", end_date="2014-12-31T00:00:00Z", pool_size=3): self.scheme = scheme self.create_devices = create_devices self.should_write_data = write_data self.start_date = start_date self.end_date = end_date self.tdb = TDBClient(scheme.db_key, scheme.db_key, scheme.db_secret, base_url=scheme.db_baseurl) iq_endpoint = HTTPEndpoint(scheme.iq_baseurl, scheme.iq_key, scheme.iq_secret) self.tiq = TIQClient(iq_endpoint) self.queue = JoinableQueue() self.lock = Lock() self.dp_count = 0 self.req_count = 0 self.dp_reset = time.time() for i in range(pool_size): gevent.spawn(self.worker) def worker(self): while True: series = self.queue.get() try: self.migrate_series(series) finally: self.queue.task_done() def migrate_all_series(self, start_key="", limit=None): start_time = time.time() (keys, tags, attrs) = self.scheme.identity_series_filter() series_set = self.tdb.list_series(keys, tags, attrs) # Keep our own state of whether we passed the resume point, so we don't # need to assume client and server sort strings the same. found_first_series = False series_count = 0 for series in series_set: if not found_first_series and series.key < start_key: continue else: found_first_series = True if limit and series_count >= limit: print("Reached limit of %d devices, stopping." % (limit)) break if self.scheme.identity_series_client_filter(series): # If the series looks like an identity series, # queue it to be processed by the threadpool self.queue.put(series) series_count += 1 self.queue.join() end_time = time.time() print("Exporting {} devices took {} seconds".format(series_count, end_time - start_time)) def migrate_series(self, series): print(" Beginning to migrate series: %s" % (series.key)) error = False try: if self.create_devices: error = self.create_device(series) if self.should_write_data and not error: error = self.write_data(series) except Exception, e: logging.exception(e) error = True if not error: print("COMPLETED migrating for series %s" % (series.key)) else: print("ERROR migrating series %s" % (series.key))
class BaseLogger(Collected, Jobber): """\ This class implements one particular way to log things. """ storage = Loggers.storage q = None job = None ready = False _in_flush = False def __init__(self, level): self.level = level global logger_nr logger_nr += 1 if not hasattr(self, "name") or self.name is None: self.name = Name(self.__class__.__name__, "x" + str(logger_nr)) super(BaseLogger, self).__init__() self._init() def _init(self): """Fork off the writer thread. Override this to do nothing if you don't have one.""" self.q = JoinableQueue(100) self.start_job("job", self._writer) self.job.link(self.delete) if self.ready is False: self.ready = True else: self.stop_job("job") # concurrency issues? def _writer(self): errs = 0 for r in self.q: try: if r is FlushMe: self._flush() else: self._log(*r) except Exception as ex: errs += 1 fix_exception(ex) from moat.run import process_failure process_failure(ex) if errs > 10: reraise(ex) else: if errs: errs -= 1 finally: self.q.task_done() self.q.task_done() # for the StopIter # Collection stuff def list(self): yield super(BaseLogger, self) yield ("Type", self.__class__.__name__) yield ("Level", LogNames[self.level]) yield ("Queue", self.q.qsize()) def info(self): return LogNames[self.level] + ": " + self.__class__.__name__ def delete(self, ctx=None): if self.ready: self.ready = None super(BaseLogger, self).delete(ctx) try: if self.q: self.q.put(StopIteration, block=False) except Full: ## panic? pass if self.job is not None: self.job.join(timeout=1) self.stop_job("job") def _wlog(self, *a): try: self.q.put(a, block=False) except Full: ## panic? self.delete() def _log(self, level, *a): a = " ".join( (x if isinstance(x, six.string_types) else str(x) for x in a)) self._slog(level, a) def _slog(self, a): raise NotImplementedError("You need to override %s._log or ._slog" % (self.__class__.__name__, )) def _flush(self): pass def log(self, level, *a): if LogLevels[level] >= self.level: self._wlog(level, *a) if TESTING and not (hasattr(a[0], "startswith") and a[0].startswith("TEST")): self.flush() else: gevent.sleep(0) def log_event(self, event, level): if level >= self.level: for r in report_(event, 99): self._wlog(LogNames[level], r) if TESTING: self.flush() def log_failure(self, err, level=WARN): if level >= self.level: self._wlog(LogNames[level], format_exception(err)) if TESTING: self.flush() def flush(self): if self._in_flush: return if self.q is not None: try: self._in_flush = True self.q.put(FlushMe) self.q.join() finally: self._in_flush = False def end_logging(self): self.flush() self.delete()
class GeventConsumer(object): def __init__( self, consumer_config=None, topic=None, parse_func=None, num=8, auto_commit_offset=False, is_debug=False, ): if not parse_func: raise Exception("not parse func, system exit") self.parse = parse_func self.queue = Queue(100) self.stop_flag = Event() self.num = num self.debug = is_debug if not self.debug: self.auto_commit_offset = auto_commit_offset if isinstance(consumer_config, dict): consumer_config.update({'enable.auto.commit':self.auto_commit_offset}) self.consumer = Consumer(consumer_config) self.topic = topic self.consumer.subscribe(self.topic) def sign_handler(self, sig, frame): print(" >>> Termination_signal:[{}] to stop".format(sig)) self.stop_flag.set() def kafka_to_queue(self): logger.info("Start Producer thread") m = 0 time_diff = 0 start_time = time.time() while not self.stop_flag.is_set(): msg = self.consumer.poll(1) if msg is None: time.sleep(0.001) return err = msg.error() if err: if err.code() == KafkaError._PARTITION_EOF: logger.debug( '%s [%s] reached end at offset %s', msg.topic(), msg.partition(), msg.offset() ) else: logger.error('kafka failed, system exit') self.stop_flag.set() self.queue.put(msg) # 消费速度统计 m += 1 current_time = time.time() time_diff = current_time - start_time if time_diff > 10: rate = m / time_diff start_time = current_time m = 0 logger.info('consumer_rate:[%.2f]p/s, queue_size:[%d]' % (rate, self.queue.qsize())) logger.info("Producer thread has stopped") def consume(self): logger.info('Start Thread To Consumer') data = dict() stop = False while True: stop = self.stop_flag.is_set() if stop and self.queue.empty(): break msg = self.queue.get() try: data = self.parse(msg.value()) if data: self.handle_data(data, stop) finally: self.queue.task_done() if not stop and not self.auto_commit_offset: self.consumer.commit(msg) logger.info('Thread Consumer has stopped') def handle_data(self, data, stop): raise NotImplementedError def consume_forever(self): """ start consume forever """ signal(SIGTERM, self.sign_handler) signal(SIGINT, self.sign_handler) if self.debug: consume_func = self.mock_consume produce_func = self.mock_kafka else: consume_func = self.consume produce_func = self.kafka_to_queue task_list = [] for _ in range(self.num): task_list.append(gevent.spawn(consume_func)) produce_func() self.queue.join() if not self.debug: logger.info("closing kafka...") self.consumer.close() gevent.joinall(task_list, timeout=5) logger.info('Exiting with qsize:%d' % self.queue.qsize()) # ===========mock kafka and consumer======================= def mock_kafka(self): logger.info("Start Producer thread") m = 0 time_diff = 0 start_time = time.time() # jing5 msg msg = "23230254455354325631393046433232323232320101008e14080b0e0c38426e0101008422551354455354325631393046433232323232323131313131313131313131313131313131313131313131313131313131313131313130010000000002803365818a91eb00010002fffe050018fffe2eeb596f50830005e91efd02649c6b7eb1ac0d80000043c497fd0022f90a3d057b2403032581373635343332310082e99f008a06".decode('hex') while not self.stop_flag.is_set(): self.queue.put(msg) m += 1 # 消费速度统计 current_time = time.time() time_diff = current_time - start_time if time_diff > 5: rate = m / time_diff start_time = current_time m = 0 logger.info('consumer_rate:[%.2f]p/s, queue_size:[%d]' % (rate, self.queue.qsize())) logger.info("closing produce...") logger.info("Producer thread has stopped") def mock_consume(self): logger.info('Start Thread To Consumer') data = dict() stop = False while True: stop = self.stop_flag.is_set() if stop and self.queue.empty(): break msg = self.queue.get() try: data = self.parse(msg) self.handle_data(data, stop) except Exception as err: logger.error("consumer:{}".format(getcurrent())) finally: self.queue.task_done() logger.info('Thread Consumer has stopped')
class FastGet: def __init__(self, url, dic, threads=100, report_db=False, keepalive=None, table_name=None): self.url = url parts = urlparse(url) self.scheme, self.host, self.port = parts.scheme, parts.hostname, parts.port if not self.port: self.port = 443 if self.scheme == 'https' else 80 self.keepalive = keepalive try: instance = HehReq(self.host, int(self.port), self.scheme, self.keepalive) except Exception as e: logging.error('Init exception for %s: %s' % (self.url, e)) return if not keepalive: self.keepalive = instance.detect_keepalive() if self.keepalive == 0: logging.error('Keep-Alive value for %s appears to be 0, check the connection' % url) return logging.warning('Calculated Keep-Alive for %s: %s' % (url, self.keepalive)) self.report_db = report_db if report_db: self.table = table_name self.sql_conn(report_db) self.queue = JoinableQueue() [self.queue.put(dic[i:i + self.keepalive]) for i in xrange(0, len(dic), self.keepalive)] [spawn(self.worker) for _ in xrange(threads)] self.queue.join() def sql_conn(self, report_db): self.conn = MySQLdb.connect(report_db['host'], report_db['user'], report_db['passwd'], report_db['db']) self.cur = self.conn.cursor() if not self.table: self.table = 'scan_%s' % datetime.strftime(datetime.now(), '%Y_%m_%d_%H%M%S') self.cur.execute( 'create table %s(scheme varchar(16), host varchar(128), port smallint, uri varchar(128),\ code smallint, size int, type varchar(128))' % self.table) def report(self, result): if result[1] not in [302, 404]: logging.warning('Path %s://%s:%s/%s, response code %s, content-length %s, content-type %s' % ( self.scheme, self.host, self.port, result[0], result[1], result[2], result[3])) if self.report_db: p = [self.scheme, self.host, self.port] + list(result) self.cur.execute('insert into %s values(%%s,%%s,%%s,%%s,%%s,%%s,%%s)' % self.table, p) def worker(self): try: instance = HehReq(self.host, int(self.port), self.scheme, self.keepalive) except Exception as e: logging.error('Worker init exception for %s: %s' % (self.url, e)) return while not self.queue.empty(): paths = self.queue.get() try: for x in instance.bulk_get(paths): self.report(x) except Exception as e: logging.error('Worker loop exception for %s: %s' % (self.url, e)) finally: if self.report_db: self.conn.commit() self.queue.task_done()
class RequestBase(object): def __init__(self,url,parameter,HTTPClients,ClientConnectionPool,task=None): if task is not None: self.celeryTask = task self.celeryTaskId = task.request.id else: self.celeryTask = None self.parameter = parameter self.url = url self.numberHTTPClients = HTTPClients self.numberClientConnectionPool = ClientConnectionPool self.http = HTTPClient.from_url(URL(url),concurrency=self.numberClientConnectionPool) self.clientPool = gevent.pool.Pool(self.numberHTTPClients) self.workQueue = JoinableQueue() self.resultList = {} self.workQueueMax = 0 self.workQueueDone = 0 self.countRequests = 0 self.status_codes = {} self.status_codes_count = {} self.meta = {} self.greenletList = {} self.initAdditionalStructures() self.progressMeta = None self.exitFlag = False self.pauseRequests = False def destroy(self): self.http.close() def initAdditionalStructures(self): pass def destroyAdditionstrucutres(self): pass def getProgress(self): return self.meta def updateProgress(self,state="PROGRESS"): '''Updates the status''' self.meta = {'state':state,'workQueueDone': self.workQueueDone, 'workQueueMax': self.workQueueMax,'current':len(self.resultList),'workQueue':self.workQueue.qsize(),'requests':self.countRequests} #iterate over status_codes dict and save the queue size. may be not the best solution from performance view for code,queue in self.status_codes.iteritems(): self.status_codes_count[code] = queue.qsize() self.meta['status_codes'] = self.status_codes_count if self.celeryTask is not None: self.celeryTask.update_state(task_id=self.celeryTaskId,state=state,meta=self.meta) def worker(self,http,clientId): while not self.workQueue.empty() or self.exitFlag: try: code = self.makeRequest(http,self.getWorkQueueItem()) finally: self.workQueue.task_done() def stop(self): self.exitFlag=True def buildRequestURL(self,workQueueItem): '''Function used to build the request URL from a workingQueue item''' pass def handleRequestSuccess(self,workQueueItem, result): '''Required function, called after every successful request''' pass def handleRequestFailure(self,result): '''Function called after a failed request. For example error code 404''' pass def makeRequest(self,http,workQueueItem): '''Makes the request to and ''' url_string = self.buildRequestURL(workQueueItem) self.countRequests += 1 try: response = http.get(URL(url_string).request_uri) statusCode = response.status_code #create a new queue if the response status_code did not exist and adds the item to the queue if str(statusCode) not in self.status_codes: self.status_codes[str(statusCode)] = JoinableQueue() self.status_codes[str(statusCode)].put(workQueueItem) try: self.handleRequestSuccess(workQueueItem,response) except SSLError,e: print e return statusCode except Exception,e: self.putWorkQueueItem(workQueueItem)
class Importer(object): def __init__(self, creds, pool_size=POOL_SIZE): self.client = get_session(creds['host'], creds['key'], creds['secret']) self.queue = JoinableQueue(maxsize=POOL_SIZE*2) for i in range(pool_size): gevent.spawn(self.worker) def worker(self): while True: job = self.queue.get() typ = job.get('type') try: if typ == 'device': self._process_device(job['data']) elif typ == 'datapoints': self._process_datapoints(job['data']) finally: self.queue.task_done() def write_devices(self, devices): for device in devices: self.queue.put({'type': 'device', 'data': device}) self.queue.join() def write_datapoints_from_file(self, infile): points = {} lineno = 0 for line in infile: lineno += 1 (device, sensor, ts, val) = line.split('\t') pts = points.setdefault(device, {}).setdefault(sensor, []) pts.append({'t': ts, 'v': float(val)}) if lineno % 1000 == 0: self.queue.put({'type': 'datapoints', 'data': points}) points = {} if points: self.queue.put({'type': 'datapoints', 'data': points}) self.queue.join() def _process_device(self, device, retries=5): res = self.client.create_device(device) if res.successful != tempoiq.response.SUCCESS: if 'A device with that key already exists' in res.body: print("Skipping creating existing device {}" .format(device['key'])) return if retries > 0: print("Retrying device create {}, error {}" .format(device['key'], res.body)) self._process_device(device, retries - 1) else: print("Retries exceeded; couldn't create device {}" .format(device['key'])) def _process_datapoints(self, write_request, retries=5): try: res = self.client.write(write_request) except Exception, e: print("ERROR with request: --->") print(json.dumps(write_request, default=WriteEncoder().default)) raise e if res.successful != tempoiq.response.SUCCESS: if retries > 0: print("Retrying write, error was: {}".format(res.body)) return self._process_datapoints(write_request, retries - 1) else: print("Retries exceeded; lost data!") print(json.dumps(write_request, default=WriteEncoder().default)) return True return False
class HttpScanner(object): def __init__(self, args): """ Initialise HTTP scanner :param args: :return: """ self.args = args self.output = HttpScannerOutput(args) self._init_scan_options() # Reading files self.output.write_log("Reading files and deduplicating.", logging.INFO) self.hosts = self._file_to_list(args.hosts) self.urls = self._file_to_list(args.urls) # self._calc_urls() out = 'Loaded %i hosts %i urls' % (self.hosts_count, self.urls_count) if self.args.ports is not None: out += ' %i ports' % len(self.args.ports) self.output.print_and_log(out) if self.args.ports is not None and not self.args.syn: new_hosts = [] for host in self.hosts: for port in self.args.ports: # print(host, port) new_hosts.append(helper.generate_url(host, port)) self.hosts = new_hosts # self._calc_urls() self.output.print_and_log('%i full urls to scan' % self.full_urls_count) # Queue and workers self.hosts_queue = JoinableQueue() self.workers = [] def _file_to_list(self, filename, dedup=True): """ Get list from file :param filename: file to read :return: list of lines """ if not path.exists(filename) or not path.isfile(filename): self.output.print_and_log('File %s not found!' % filename, logging.ERROR) exit(-1) # Preparing lines list lines = filter(lambda line: line is not None and len(line) > 0, open(filename).read().split('\n')) if len(lines) == 0: self.output.print_and_log('File %s is empty!' % filename, logging.ERROR) exit(-1) return helper.deduplicate(lines) if dedup else lines def _init_scan_options(self): # Session self.session = session() self.session.timeout = self.args.timeout self.session.verify = False # TODO: debug and check # self.session.mount("http://", HTTPAdapter(max_retries=self.args.max_retries)) # self.session.mount("https://", HTTPAdapter(max_retries=self.args.max_retries)) # http://stackoverflow.com/questions/15431044/can-i-set-max-retries-for-requests-request # Max retries adapters.DEFAULT_RETRIES = self.args.max_retries # TOR if self.args.tor: self.output.write_log("TOR usage detected. Making some checks.") self.session.proxies = { 'http': 'socks5://127.0.0.1:9050', 'https': 'socks5://127.0.0.1:9050' } url = 'http://ifconfig.me/ip' real_ip, tor_ip = None, None # Ger real IP address try: real_ip = get(url).text.strip() except Exception as exception: self.output.print_and_log( "Couldn't get real IP address. Check yout internet connection.", logging.ERROR) self.output.write_log(str(exception), logging.ERROR) exit(-1) # Get TOR IP address try: tor_ip = self.session.get(url).text.strip() except Exception as exception: self.output.print_and_log( "TOR socks proxy doesn't seem to be working.", logging.ERROR) self.output.write_log(str(exception), logging.ERROR) exit(-1) # Show IP addresses self.output.print_and_log('Real IP: %s TOR IP: %s' % (real_ip, tor_ip)) if real_ip == tor_ip: self.output.print_and_log( "TOR doesn't work! Stop to be secure.", logging.ERROR) exit(-1) # Proxy if self.args.proxy is not None: self.session.proxies = { "https": self.args.proxy, "http": self.args.proxy } # Auth if self.args.auth is not None: items = self.args.auth.split(':') self.session.auth = (items[0], items[1]) # Cookies self.cookies = {} if self.args.cookies is not None: self.cookies = Cookies.from_request(self.args.cookies) # Cookies from file if self.args.load_cookies is not None: if not path.exists(self.args.load_cookies) or not path.isfile( self.args.load_cookies): self.output.print_and_log( 'Could not find cookie file: %s' % self.args.load_cookies, logging.ERROR) exit(-1) self.cookies = MozillaCookieJar(self.args.load_cookies) self.cookies.load() self.session.cookies = self.cookies # User-Agent self.ua = UserAgent() if self.args.random_agent else None def worker(self, worker_id): self.output.write_log('Worker %i started.' % worker_id) while not self.hosts_queue.empty(): host = self.hosts_queue.get() try: self.scan_host(worker_id, host) finally: self.output.write_log('Worker %i finished.' % worker_id) self.hosts_queue.task_done() def _head_available(self, host): """ Determine if HEAD requests is allowed :param host: :return: """ # Trying to use OPTIONS request try: response = self.session.options(host, headers=self._fill_headers()) o = response.headers[ 'allow'] if 'allow' in response.headers else None if o is not None and o.find('HEAD') != -1: return True except: # TODO: fix pass try: return False if self.session.head( host, headers=self._fill_headers()).status_code == 405 else True except: # TODO: fix return False def scan_host(self, worker_id, host): # check if resolvable ip = helper.url_to_ip(host) if ip is None: self.output.write_log('Could not resolve %s Skipping...' % host, logging.WARNING) self.output.urls_scanned += len(self.urls) return # Check for HEAD host_url = helper.host_to_url(host) head_available = False if self.args.head: head_available = self._head_available(host) if head_available: self.output.write_log('HEAD is supported for %s' % host) errors_count, urls_scanned = 0, 0 for url in self.urls: full_url = urljoin(host_url, url) r = self.scan_url(full_url, head_available) urls_scanned += 1 self.output.urls_scanned += 1 # Output r['worker'] = worker_id self.output.write(**r) if r['exception'] is not None: errors_count += 1 # Skip host on errors if self.args.skip is not None and errors_count == self.args.skip: self.output.write_log( 'Errors limit reached on %s Skipping other urls.' % host, logging.WARNING) self.output.urls_scanned += len(self.urls) - urls_scanned break # cookies bugfix? self.session.cookies.clear() def _fill_headers(self): # Fill UserAgent in headers headers = {} if self.args.user_agent is not None: headers['User-agent'] = self.args.user_agent elif self.args.random_agent: headers['User-agent'] = self.ua.random # Fill Referer in headers if self.args.referer is not None: headers['Referer'] = self.args.referer return headers def _parse_response(self, url, response, exception): res = {'url': url, 'response': response, 'exception': exception} if response is None or exception is not None: res.update({ 'status': -1, 'length': -1, }) return res try: length = int(response.headers['content-length'] ) if 'content-length' in response.headers else len( response.text) except Exception as exception: self.output.write_log( "Exception while getting content length for URL: %s Exception: %s" % (url, str(exception)), logging.ERROR) length = 0 res.update({ 'status': response.status_code, 'length': length, }) return res def scan_url(self, url, use_head=False): self.output.write_log('Scanning %s' % url, logging.DEBUG) # Query URL and handle exceptions response, exception = None, None method = 'HEAD' if use_head else 'GET' try: # TODO: add support for user:password in URL response = self.session.request( method, url, headers=self._fill_headers(), allow_redirects=self.args.allow_redirects) except ConnectionError as ex: self.output.write_log('Connection error while quering %s' % url, logging.ERROR) exception = ex except HTTPError as ex: self.output.write_log('HTTP error while quering %s' % url, logging.ERROR) exception = ex except Timeout as ex: self.output.write_log('Timeout while quering %s' % url, logging.ERROR) exception = ex except TooManyRedirects as ex: self.output.write_log('Too many redirects while quering %s' % url, logging.ERROR) exception = ex except Exception as ex: self.output.write_log('Unknown exception while quering %s' % url, logging.ERROR) exception = ex # print('cookies: %s' % self.cookies) print('session.cookies: %s' % self.session.cookies) # self.session.cookies = self.cookies return self._parse_response(url, response, exception) def signal_handler(self): """ Signal hdndler :return: """ # TODO: add saving status via pickle self.output.print_and_log('Signal caught. Stopping...', logging.WARNING) self.stop() exit(signal.SIGINT) def _calc_urls(self): # Calculations self.urls_count = len(self.urls) self.hosts_count = len(self.hosts) self.full_urls_count = len(self.urls) * len(self.hosts) self.output.args.urls_count = self.full_urls_count def start(self): """ Start mulithreaded scan :return: """ # Set signal handler gevent.signal(signal.SIGTERM, self.signal_handler) gevent.signal(signal.SIGINT, self.signal_handler) gevent.signal(signal.SIGQUIT, self.signal_handler) # ICMP scan if self.args.icmp: if geteuid() != 0: self.output.print_and_log( 'To use ICMP scan option you must run as root. Skipping ICMP scan', logging.WARNING) else: self.output.print_and_log('Starting ICMP scan.') self.hosts = helper.icmp_scan(self.hosts, self.args.timeout) self._calc_urls() self.output.print_and_log( 'After ICMP scan %i hosts %i urls loaded, %i urls to scan' % (self.hosts_count, self.urls_count, self.full_urls_count)) # SYN scan if self.args.syn: if self.args.tor or self.args.proxy is not None: self.output.print_and_log( 'SYN scan via tor or proxy is impossible!', logging.WARNING) self.output.print_and_log( 'Stopping to prevent deanonymization!', logging.WARNING) exit(-1) if geteuid() != 0: self.output.print_and_log( 'To use SYN scan option you must run as root. Skipping SYN scan', logging.WARNING) else: self.output.print_and_log('Starting SYN scan.') self.hosts = helper.syn_scan(self.hosts, self.args.ports, self.args.timeout) self._calc_urls() self.output.print_and_log( 'After SYN scan %i hosts %i urls loaded, %i urls to scan' % (self.hosts_count, self.urls_count, self.full_urls_count)) # Check threds count vs hosts count if self.args.threads > self.hosts_count: self.output.write_log( 'Too many threads! Fixing threads count to %i' % self.hosts_count, logging.WARNING) threads_count = self.hosts_count else: threads_count = self.args.threads # Output urls count self.output.args.urls_count = self.full_urls_count # Start workers self.workers = [spawn(self.worker, i) for i in range(threads_count)] # Fill and join queue [self.hosts_queue.put(host) for host in self.hosts] self.hosts_queue.join() def stop(self): """ Stop scan :return: """ # TODO: stop correctly gevent.killall(self.workers)
class AsynSpiderWithGevent(MySpider): def __init__(self, out=BasicAnalysis(), **kwargs): super(AsynSpiderWithGevent, self).__init__(out, **kwargs) self.q = JoinableQueue() self.fetching, self.fetched = set(), set() def assign_jobs(self, jobs): for job in jobs: self.q.put(job) def run(self): if self.q.empty(): url = LIST_URL + urllib.urlencode(self.list_query) self.q.put(url) for _ in range(CONCURRENCY): gevent.spawn(self.worker) self.q.join() assert self.fetching == self.fetched self._out.finish() def worker(self): while True: self.fetch_url() def fetch_url(self): current_url = self.q.get() try: if current_url in self.fetching: return self.fetching.add(current_url) resp = requests.get(current_url, headers=HEADERS) self.fetched.add(current_url) xml = etree.fromstring(resp.content) has_total_count = xml.xpath("//totalcount/text()") if has_total_count: # 非空证明为列表,否则为详细页 total_count = int(has_total_count[0]) if total_count == 0: return # 列表跨界 if self.list_query["pageno"] == 1: pageno = 2 # while pageno < 10: while pageno <= total_count / PAGE_SIZE: self.list_query["pageno"] = pageno next_list_url = LIST_URL + urllib.urlencode( self.list_query) self.q.put(next_list_url) # logging.info(next_list_url) pageno += 1 job_ids = xml.xpath("//jobid/text()") job_detail_urls = [] for ID in job_ids: new_detail_query = DETAIL_QUERY.copy() new_detail_query["jobid"] = ID job_detail_urls.append(DETAIL_URL + urllib.urlencode(new_detail_query)) for detail_url in job_detail_urls: self.q.put(detail_url) # logging.info(detail_url) else: self._out.collect(xml) finally: self.q.task_done()
class BaseLogger(Collected,Jobber): """\ This class implements one particular way to log things. """ storage = Loggers.storage q = None job = None ready = False _in_flush = False def __init__(self, level): self.level = level global logger_nr logger_nr += 1 if not hasattr(self,"name") or self.name is None: self.name = Name(self.__class__.__name__, "x"+str(logger_nr)) super(BaseLogger,self).__init__() self._init() def _init(self): """Fork off the writer thread. Override this to do nothing if you don't have one.""" self.q = JoinableQueue(100) self.start_job("job",self._writer) self.job.link(self.delete) if self.ready is False: self.ready = True else: self.stop_job("job") # concurrency issues? def _writer(self): errs = 0 for r in self.q: try: if r is FlushMe: self._flush() else: self._log(*r) except Exception as ex: errs += 1 fix_exception(ex) from moat.run import process_failure process_failure(ex) if errs > 10: reraise(ex) else: if errs: errs -= 1 finally: self.q.task_done() self.q.task_done() # for the StopIter # Collection stuff def list(self): yield super(BaseLogger,self) yield ("Type",self.__class__.__name__) yield ("Level",LogNames[self.level]) yield ("Queue",self.q.qsize()) def info(self): return LogNames[self.level]+": "+self.__class__.__name__ def delete(self, ctx=None): if self.ready: self.ready = None super(BaseLogger,self).delete(ctx) try: if self.q: self.q.put(StopIteration,block=False) except Full: ## panic? pass if self.job is not None: self.job.join(timeout=1) self.stop_job("job") def _wlog(self, *a): try: self.q.put(a, block=False) except Full: ## panic? self.delete() def _log(self, level, *a): a=" ".join(( x if isinstance(x,six.string_types) else str(x) for x in a)) self._slog(level,a) def _slog(self, a): raise NotImplementedError("You need to override %s._log or ._slog" % (self.__class__.__name__,)) def _flush(self): pass def log(self, level, *a): if LogLevels[level] >= self.level: self._wlog(level,*a) if TESTING and not (hasattr(a[0],"startswith") and a[0].startswith("TEST")): self.flush() else: gevent.sleep(0) def log_event(self, event, level): if level >= self.level: for r in report_(event,99): self._wlog(LogNames[level],r) if TESTING: self.flush() def log_failure(self, err, level=WARN): if level >= self.level: self._wlog(LogNames[level],format_exception(err)) if TESTING: self.flush() def flush(self): if self._in_flush: return if self.q is not None: try: self._in_flush = True self.q.put(FlushMe) self.q.join() finally: self._in_flush = False def end_logging(self): self.flush() self.delete()
class Migrator: def __init__(self, scheme, create_devices=True, write_data=True, start_date="2000-01-01T00:00:00Z", end_date="2014-12-31T00:00:00Z", pool_size=3): self.scheme = scheme self.create_devices = create_devices self.should_write_data = write_data self.start_date = start_date self.end_date = end_date self.tdb = TDBClient(scheme.db_key, scheme.db_key, scheme.db_secret, base_url=scheme.db_baseurl) iq_endpoint = HTTPEndpoint(scheme.iq_baseurl, scheme.iq_key, scheme.iq_secret) self.tiq = TIQClient(iq_endpoint) self.queue = JoinableQueue() self.lock = Lock() self.dp_count = 0 self.req_count = 0 self.dp_reset = time.time() for i in range(pool_size): gevent.spawn(self.worker) def worker(self): while True: series = self.queue.get() try: self.migrate_series(series) finally: self.queue.task_done() def migrate_all_series(self, start_key="", limit=None): start_time = time.time() (keys, tags, attrs) = self.scheme.identity_series_filter() series_set = self.tdb.list_series(keys, tags, attrs) # Keep our own state of whether we passed the resume point, so we don't # need to assume client and server sort strings the same. found_first_series = False series_count = 0 for series in series_set: if not found_first_series and series.key < start_key: continue else: found_first_series = True if limit and series_count >= limit: print("Reached limit of %d devices, stopping." % (limit)) break if self.scheme.identity_series_client_filter(series): # If the series looks like an identity series, # queue it to be processed by the threadpool self.queue.put(series) series_count += 1 self.queue.join() end_time = time.time() print("Exporting {} devices took {} seconds".format( series_count, end_time - start_time)) def migrate_series(self, series): print(" Beginning to migrate series: %s" % (series.key)) error = False try: if self.create_devices: error = self.create_device(series) if self.should_write_data and not error: error = self.write_data(series) except Exception, e: logging.exception(e) error = True if not error: print("COMPLETED migrating for series %s" % (series.key)) else: print("ERROR migrating series %s" % (series.key))