idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
26,600
def _load_custom ( self , settings_name = 'localsettings.py' ) : if settings_name [ - 3 : ] == '.py' : settings_name = settings_name [ : - 3 ] new_settings = { } try : settings = importlib . import_module ( settings_name ) new_settings = self . _convert_to_dict ( settings ) except ImportError : log . info ( "No overrid...
Load the user defined settings overriding the defaults
26,601
def _convert_to_dict ( self , setting ) : the_dict = { } set = dir ( setting ) for key in set : if key in self . ignore : continue value = getattr ( setting , key ) the_dict [ key ] = value return the_dict
Converts a settings file into a dictionary ignoring python defaults
26,602
def load_domain_config ( self , loaded_config ) : self . domain_config = { } if loaded_config : if 'domains' in loaded_config : for domain in loaded_config [ 'domains' ] : item = loaded_config [ 'domains' ] [ domain ] if 'window' in item and 'hits' in item : self . logger . debug ( "Added domain {dom} to loaded config"...
Loads the domain_config and sets up queue_dict
26,603
def update_domain_queues ( self ) : for key in self . domain_config : final_key = "{name}:{domain}:queue" . format ( name = self . spider . name , domain = key ) if final_key in self . queue_dict : self . queue_dict [ final_key ] [ 0 ] . window = float ( self . domain_config [ key ] [ 'window' ] ) self . logger . debug...
Check to update existing queues already in memory new queues are created elsewhere
26,604
def create_queues ( self ) : newConf = self . check_config ( ) self . queue_keys = self . redis_conn . keys ( self . spider . name + ":*:queue" ) for key in self . queue_keys : throttle_key = "" if self . add_type : throttle_key = self . spider . name + ":" if self . add_ip : throttle_key = throttle_key + self . my_ip ...
Updates the in memory list of the redis queues Creates new throttled queue instances if it does not have them
26,605
def expire_queues ( self ) : curr_time = time . time ( ) for key in list ( self . queue_dict ) : diff = curr_time - self . queue_dict [ key ] [ 1 ] if diff > self . queue_timeout : self . logger . debug ( "Expiring domain queue key " + key ) del self . queue_dict [ key ] if key in self . queue_keys : self . queue_keys ...
Expires old queue_dict keys that have not been used in a long time . Prevents slow memory build up when crawling lots of different domains
26,606
def update_ipaddress ( self ) : self . old_ip = self . my_ip self . my_ip = '127.0.0.1' try : obj = urllib . request . urlopen ( settings . get ( 'PUBLIC_IP_URL' , 'http://ip.42.pl/raw' ) ) results = self . ip_regex . findall ( obj . read ( ) ) if len ( results ) > 0 : self . my_ip = results [ 0 ] else : raise IOError ...
Updates the scheduler so it knows its own ip address
26,607
def is_blacklisted ( self , appid , crawlid ) : key_check = '{appid}||{crawlid}' . format ( appid = appid , crawlid = crawlid ) redis_key = self . spider . name + ":blacklist" return self . redis_conn . sismember ( redis_key , key_check )
Checks the redis blacklist for crawls that should not be propagated either from expiring or stopped
26,608
def enqueue_request ( self , request ) : if not request . dont_filter and self . dupefilter . request_seen ( request ) : self . logger . debug ( "Request not added back to redis" ) return req_dict = self . request_to_dict ( request ) if not self . is_blacklisted ( req_dict [ 'meta' ] [ 'appid' ] , req_dict [ 'meta' ] [...
Pushes a request from the spider into the proper throttled queue
26,609
def request_to_dict ( self , request ) : req_dict = { 'url' : to_unicode ( request . url ) , 'method' : request . method , 'headers' : dict ( request . headers ) , 'body' : request . body , 'cookies' : request . cookies , 'meta' : request . meta , '_encoding' : request . _encoding , 'priority' : request . priority , 'd...
Convert Request object to a dict . modified from scrapy . utils . reqser
26,610
def find_item ( self ) : random . shuffle ( self . queue_keys ) count = 0 while count <= self . item_retries : for key in self . queue_keys : if key . split ( ':' ) [ 1 ] in self . black_domains : continue item = self . queue_dict [ key ] [ 0 ] . pop ( ) if item : self . queue_dict [ key ] [ 1 ] = time . time ( ) retur...
Finds an item from the throttled queues
26,611
def next_request ( self ) : t = time . time ( ) if t - self . update_time > self . update_interval : self . update_time = t self . create_queues ( ) self . expire_queues ( ) if t - self . update_ip_time > self . ip_update_interval : self . update_ip_time = t self . update_ipaddress ( ) self . report_self ( ) item = sel...
Logic to handle getting a new url request from a bunch of different queues
26,612
def parse_cookie ( self , string ) : results = re . findall ( '([^=]+)=([^\;]+);?\s?' , string ) my_dict = { } for item in results : my_dict [ item [ 0 ] ] = item [ 1 ] return my_dict
Parses a cookie string like returned in a Set - Cookie header
26,613
def _clean_item ( self , item ) : item_copy = dict ( item ) del item_copy [ 'body' ] del item_copy [ 'links' ] del item_copy [ 'response_headers' ] del item_copy [ 'request_headers' ] del item_copy [ 'status_code' ] del item_copy [ 'status_msg' ] item_copy [ 'action' ] = 'ack' item_copy [ 'logger' ] = self . logger . n...
Cleans the item to be logged
26,614
def _kafka_success ( self , item , spider , response ) : item [ 'success' ] = True item = self . _clean_item ( item ) item [ 'spiderid' ] = spider . name self . logger . info ( "Sent page to Kafka" , item )
Callback for successful send
26,615
def _kafka_failure ( self , item , spider , response ) : item [ 'success' ] = False item [ 'exception' ] = traceback . format_exc ( ) item [ 'spiderid' ] = spider . name item = self . _clean_item ( item ) self . logger . error ( "Failed to send page to Kafka" , item )
Callback for failed send
26,616
def reconstruct_headers ( self , response ) : header_dict = { } for key in list ( response . headers . keys ( ) ) : key_item_list = [ ] key_list = response . headers . getlist ( key ) for item in key_list : key_item_list . append ( item ) header_dict [ key ] = key_item_list return header_dict
Purpose of this method is to reconstruct the headers dictionary that is normally passed in with a response object from scrapy .
26,617
def handle ( self , dict ) : ex_res = self . extract ( dict [ 'url' ] ) key = "{sid}:{dom}.{suf}:queue" . format ( sid = dict [ 'spiderid' ] , dom = ex_res . domain , suf = ex_res . suffix ) val = ujson . dumps ( dict ) self . redis_conn . zadd ( key , val , - dict [ 'priority' ] ) if 'expires' in dict and dict [ 'expi...
Processes a vaild crawl request
26,618
def timeout ( timeout_time , default ) : def timeout_function ( f ) : def f2 ( * args ) : def timeout_handler ( signum , frame ) : raise MethodTimer . DecoratorTimeout ( ) old_handler = signal . signal ( signal . SIGALRM , timeout_handler ) signal . alarm ( timeout_time ) try : retval = f ( * args ) except MethodTimer ...
Decorate a method so it is required to execute in a given time period or return a default value .
26,619
def _setup_stats_status_codes ( self , spider_name ) : self . stats_dict [ spider_name ] = { 'status_codes' : { } } self . stats_dict [ spider_name ] [ 'status_codes' ] = { } hostname = self . _get_hostname ( ) for status_code in self . settings [ 'STATS_RESPONSE_CODES' ] : temp_key = 'stats:crawler:{h}:{n}:{s}' . form...
Sets up the status code stats collectors
26,620
def setup ( self , settings ) : self . producer = self . _create_producer ( settings ) self . topic_prefix = settings [ 'KAFKA_TOPIC_PREFIX' ] self . use_appid_topics = settings [ 'KAFKA_APPID_TOPICS' ] self . logger . debug ( "Successfully connected to Kafka in {name}" . format ( name = self . __class__ . __name__ ) )
Setup the handler
26,621
def _send_to_kafka ( self , master ) : appid_topic = "{prefix}.outbound_{appid}" . format ( prefix = self . topic_prefix , appid = master [ 'appid' ] ) firehose_topic = "{prefix}.outbound_firehose" . format ( prefix = self . topic_prefix ) try : if self . use_appid_topics : f1 = self . producer . send ( appid_topic , m...
Sends the message back to Kafka
26,622
def _load_plugins ( self ) : plugins = self . settings [ 'PLUGINS' ] self . plugins_dict = { } for key in plugins : if plugins [ key ] is None : continue self . logger . debug ( "Trying to load plugin {cls}" . format ( cls = key ) ) the_class = self . _import_class ( key ) instance = the_class ( ) instance . _set_logge...
Sets up all plugins defaults and settings . py
26,623
def _setup_stats ( self ) : self . stats_dict = { } redis_conn = redis . Redis ( host = self . settings [ 'REDIS_HOST' ] , port = self . settings [ 'REDIS_PORT' ] , db = self . settings . get ( 'REDIS_DB' ) ) try : redis_conn . info ( ) self . logger . debug ( "Connected to Redis in StatsCollector Setup" ) self . redis...
Sets up the stats collection
26,624
def _setup_stats_total ( self , redis_conn ) : self . stats_dict [ 'total' ] = { } self . stats_dict [ 'fail' ] = { } temp_key1 = 'stats:kafka-monitor:total' temp_key2 = 'stats:kafka-monitor:fail' for item in self . settings [ 'STATS_TIMES' ] : try : time = getattr ( StatsCollector , item ) self . stats_dict [ 'total' ...
Sets up the total stats collectors
26,625
def _main_loop ( self ) : self . logger . debug ( "Processing messages" ) old_time = 0 while True : self . _process_messages ( ) if self . settings [ 'STATS_DUMP' ] != 0 : new_time = int ( old_div ( time . time ( ) , self . settings [ 'STATS_DUMP' ] ) ) if new_time != old_time : self . _dump_stats ( ) old_time = new_ti...
Continuous loop that reads from a kafka topic and tries to validate incoming messages
26,626
def _dump_stats ( self ) : extras = { } if 'total' in self . stats_dict : self . logger . debug ( "Compiling total/fail dump stats" ) for key in self . stats_dict [ 'total' ] : final = 'total_{t}' . format ( t = key ) extras [ final ] = self . stats_dict [ 'total' ] [ key ] . value ( ) for key in self . stats_dict [ 'f...
Dumps the stats out
26,627
def run ( self ) : self . _setup_kafka ( ) self . _load_plugins ( ) self . _setup_stats ( ) self . _main_loop ( )
Set up and run
26,628
def _report_self ( self ) : key = "stats:kafka-monitor:self:{m}:{u}" . format ( m = socket . gethostname ( ) , u = self . my_uuid ) self . redis_conn . set ( key , time . time ( ) ) self . redis_conn . expire ( key , self . settings [ 'HEARTBEAT_TIMEOUT' ] )
Reports the kafka monitor uuid to redis
26,629
def feed ( self , json_item ) : @ MethodTimer . timeout ( self . settings [ 'KAFKA_FEED_TIMEOUT' ] , False ) def _feed ( json_item ) : producer = self . _create_producer ( ) topic = self . settings [ 'KAFKA_INCOMING_TOPIC' ] if not self . logger . json : self . logger . info ( 'Feeding JSON into {0}\n{1}' . format ( to...
Feeds a json item into the Kafka topic
26,630
def check_precondition ( self , key , value ) : timeout = float ( value ) curr_time = self . get_current_time ( ) if curr_time > timeout : return True return False
Override to check for timeout
26,631
def get_time_window ( self , redis_conn = None , host = 'localhost' , port = 6379 , key = 'time_window_counter' , cycle_time = 5 , start_time = None , window = SECONDS_1_HOUR , roll = True , keep_max = 12 ) : counter = TimeWindow ( key = key , cycle_time = cycle_time , start_time = start_time , window = window , roll =...
Generate a new TimeWindow Useful for collecting number of hits generated between certain times
26,632
def get_rolling_time_window ( self , redis_conn = None , host = 'localhost' , port = 6379 , key = 'rolling_time_window_counter' , cycle_time = 5 , window = SECONDS_1_HOUR ) : counter = RollingTimeWindow ( key = key , cycle_time = cycle_time , window = window ) counter . setup ( redis_conn = redis_conn , host = host , p...
Generate a new RollingTimeWindow Useful for collect data about the number of hits in the past X seconds
26,633
def get_counter ( self , redis_conn = None , host = 'localhost' , port = 6379 , key = 'counter' , cycle_time = 5 , start_time = None , window = SECONDS_1_HOUR , roll = True , keep_max = 12 , start_at = 0 ) : counter = Counter ( key = key , cycle_time = cycle_time , start_time = start_time , window = window , roll = rol...
Generate a new Counter Useful for generic distributed counters
26,634
def get_unique_counter ( self , redis_conn = None , host = 'localhost' , port = 6379 , key = 'unique_counter' , cycle_time = 5 , start_time = None , window = SECONDS_1_HOUR , roll = True , keep_max = 12 ) : counter = UniqueCounter ( key = key , cycle_time = cycle_time , start_time = start_time , window = window , roll ...
Generate a new UniqueCounter . Useful for exactly counting unique objects
26,635
def get_hll_counter ( self , redis_conn = None , host = 'localhost' , port = 6379 , key = 'hyperloglog_counter' , cycle_time = 5 , start_time = None , window = SECONDS_1_HOUR , roll = True , keep_max = 12 ) : counter = HyperLogLogCounter ( key = key , cycle_time = cycle_time , start_time = start_time , window = window ...
Generate a new HyperLogLogCounter . Useful for approximating extremely large counts of unique items
26,636
def setup ( self , redis_conn = None , host = 'localhost' , port = 6379 ) : if redis_conn is None : if host is not None and port is not None : self . redis_conn = redis . Redis ( host = host , port = port ) else : raise Exception ( "Please specify some form of connection " "to Redis" ) else : self . redis_conn = redis_...
Set up the redis connection
26,637
def setup ( self , redis_conn = None , host = 'localhost' , port = 6379 ) : AbstractCounter . setup ( self , redis_conn = redis_conn , host = host , port = port ) self . _threaded_start ( )
Set up the counting manager class
26,638
def _threaded_start ( self ) : self . active = True self . thread = Thread ( target = self . _main_loop ) self . thread . setDaemon ( True ) self . thread . start ( )
Spawns a worker thread to do the expiration checks
26,639
def _main_loop ( self ) : while self . active : self . expire ( ) if self . roll and self . is_expired ( ) : self . start_time = self . start_time + self . window self . _set_key ( ) self . purge_old ( ) time . sleep ( self . cycle_time ) self . _clean_up ( )
Main loop for the stats collector
26,640
def _set_key ( self ) : if self . roll : self . date = time . strftime ( self . date_format , time . gmtime ( self . start_time ) ) self . final_key = '{}:{}' . format ( self . key , self . date ) else : self . final_key = self . key
sets the final key to be used currently
26,641
def is_expired ( self ) : if self . window is not None : return ( self . _time ( ) - self . start_time ) >= self . window return False
Returns true if the time is beyond the window
26,642
def purge_old ( self ) : if self . keep_max is not None : keys = self . redis_conn . keys ( self . get_key ( ) + ':*' ) keys . sort ( reverse = True ) while len ( keys ) > self . keep_max : key = keys . pop ( ) self . redis_conn . delete ( key )
Removes keys that are beyond our keep_max limit
26,643
def _encode_item ( self , item ) : if self . encoding . __name__ == 'pickle' : return self . encoding . dumps ( item , protocol = - 1 ) else : return self . encoding . dumps ( item )
Encode an item object
26,644
def threaded_start ( self , no_init = False ) : thread = Thread ( target = self . init_connections , kwargs = { 'no_init' : no_init } ) thread . setDaemon ( True ) thread . start ( ) thread . join ( )
Spawns a worker thread to set up the zookeeper connection
26,645
def init_connections ( self , no_init = False ) : success = False self . set_valid ( False ) if not no_init : if self . zoo_client : self . zoo_client . remove_listener ( self . state_listener ) self . old_data = '' self . old_pointed = '' while not success : try : if self . zoo_client is None : self . zoo_client = Kaz...
Sets up the initial Kazoo Client and watches
26,646
def setup ( self ) : self . zoo_client . add_listener ( self . state_listener ) if self . ensure : self . zoo_client . ensure_path ( self . my_file )
Ensures the path to the watched file exists and we have a state listener
26,647
def state_listener ( self , state ) : if state == KazooState . SUSPENDED : self . set_valid ( False ) self . call_error ( self . BAD_CONNECTION ) elif state == KazooState . LOST and not self . do_not_restart : self . threaded_start ( ) elif state == KazooState . CONNECTED : self . zoo_client . stop ( )
Restarts the session if we get anything besides CONNECTED
26,648
def close ( self , kill_restart = True ) : self . do_not_restart = kill_restart self . zoo_client . stop ( ) self . zoo_client . close ( )
Use when you would like to close everything down
26,649
def get_file_contents ( self , pointer = False ) : if self . pointer : if pointer : return self . old_pointed else : return self . old_data else : return self . old_data
Gets any file contents you care about . Defaults to the main file
26,650
def update_file ( self , path ) : try : result , stat = self . zoo_client . get ( path , watch = self . watch_file ) except ZookeeperError : self . set_valid ( False ) self . call_error ( self . INVALID_GET ) return False if self . pointer : if result is not None and len ( result ) > 0 : self . pointed_at_expired = Fal...
Updates the file watcher and calls the appropriate method for results
26,651
def update_pointed ( self ) : if not self . pointed_at_expired : try : conf_string , stat2 = self . zoo_client . get ( self . point_path , watch = self . watch_pointed ) except ZookeeperError : self . old_data = '' self . set_valid ( False ) self . pointed_at_expired = True self . call_error ( self . INVALID_PATH ) ret...
Grabs the latest file contents based on the pointer uri
26,652
def set_valid ( self , boolean ) : old_state = self . is_valid ( ) self . valid_file = boolean if old_state != self . valid_file : self . call_valid ( self . valid_file )
Sets the state and calls the change if needed
26,653
def setup ( self , settings ) : self . extract = tldextract . TLDExtract ( ) self . redis_conn = redis . Redis ( host = settings [ 'REDIS_HOST' ] , port = settings [ 'REDIS_PORT' ] , db = settings . get ( 'REDIS_DB' ) ) try : self . redis_conn . info ( ) self . logger . debug ( "Connected to Redis in ZookeeperHandler" ...
Setup redis and tldextract
26,654
def get_log_dict ( self , action , appid , spiderid = None , uuid = None , crawlid = None ) : extras = { } extras [ 'action' ] = action extras [ 'appid' ] = appid if spiderid is not None : extras [ 'spiderid' ] = spiderid if uuid is not None : extras [ 'uuid' ] = uuid if crawlid is not None : extras [ 'crawlid' ] = cra...
Returns a basic dictionary for logging
26,655
def _load_plugins ( self ) : plugins = self . settings [ 'PLUGINS' ] self . plugins_dict = { } for key in plugins : if plugins [ key ] is None : continue self . logger . debug ( "Trying to load plugin {cls}" . format ( cls = key ) ) the_class = self . import_class ( key ) instance = the_class ( ) instance . redis_conn ...
Sets up all plugins and defaults
26,656
def _main_loop ( self ) : self . logger . debug ( "Running main loop" ) old_time = 0 while True : for plugin_key in self . plugins_dict : obj = self . plugins_dict [ plugin_key ] self . _process_plugin ( obj ) if self . settings [ 'STATS_DUMP' ] != 0 : new_time = int ( old_div ( time . time ( ) , self . settings [ 'STA...
The internal while true main loop for the redis monitor
26,657
def _process_plugin ( self , plugin ) : instance = plugin [ 'instance' ] regex = plugin [ 'regex' ] for key in self . redis_conn . scan_iter ( match = regex ) : lock = self . _create_lock_object ( key ) try : if lock . acquire ( blocking = False ) : val = self . redis_conn . get ( key ) self . _process_key_val ( instan...
Logic to handle each plugin that is active
26,658
def _create_lock_object ( self , key ) : return redis_lock . Lock ( self . redis_conn , key , expire = self . settings [ 'REDIS_LOCK_EXPIRATION' ] , auto_renewal = True )
Returns a lock object split for testing
26,659
def _process_failures ( self , key ) : if self . settings [ 'RETRY_FAILURES' ] : self . logger . debug ( "going to retry failure" ) failkey = self . _get_fail_key ( key ) current = self . redis_conn . get ( failkey ) if current is None : current = 0 else : current = int ( current ) if current < self . settings [ 'RETRY...
Handles the retrying of the failed key
26,660
def _setup_stats ( self ) : self . stats_dict = { } if self . settings [ 'STATS_TOTAL' ] : self . _setup_stats_total ( ) if self . settings [ 'STATS_PLUGINS' ] : self . _setup_stats_plugins ( )
Sets up the stats
26,661
def _setup_stats_plugins ( self ) : self . stats_dict [ 'plugins' ] = { } for key in self . plugins_dict : plugin_name = self . plugins_dict [ key ] [ 'instance' ] . __class__ . __name__ temp_key = 'stats:redis-monitor:{p}' . format ( p = plugin_name ) self . stats_dict [ 'plugins' ] [ plugin_name ] = { } for item in s...
Sets up the plugin stats collectors
26,662
def _dump_crawl_stats ( self ) : extras = { } spiders = { } spider_set = set ( ) total_spider_count = 0 keys = self . redis_conn . keys ( 'stats:crawler:*:*:*' ) for key in keys : elements = key . split ( ":" ) spider = elements [ 3 ] if spider not in spiders : spiders [ spider ] = 0 if len ( elements ) == 6 : response...
Dumps flattened crawling stats so the spiders do not have to
26,663
def _dump_queue_stats ( self ) : extras = { } keys = self . redis_conn . keys ( '*:*:queue' ) total_backlog = 0 for key in keys : elements = key . split ( ":" ) spider = elements [ 0 ] domain = elements [ 1 ] spider = 'queue_' + spider if spider not in extras : extras [ spider ] = { } extras [ spider ] [ 'spider_backlo...
Dumps basic info about the queue lengths for the spider types
26,664
def close ( self ) : for plugin_key in self . plugins_dict : obj = self . plugins_dict [ plugin_key ] instance = obj [ 'instance' ] instance . close ( )
Closes the Redis Monitor and plugins
26,665
def get_all_stats ( self ) : self . logger . debug ( "Gathering all stats" ) the_dict = { } the_dict [ 'kafka-monitor' ] = self . get_kafka_monitor_stats ( ) the_dict [ 'redis-monitor' ] = self . get_redis_monitor_stats ( ) the_dict [ 'crawler' ] = self . get_crawler_stats ( ) the_dict [ 'rest' ] = self . get_rest_stat...
Gather all stats objects
26,666
def _get_plugin_stats ( self , name ) : the_dict = { } keys = self . redis_conn . keys ( 'stats:{n}:*' . format ( n = name ) ) for key in keys : elements = key . split ( ":" ) main = elements [ 2 ] end = elements [ 3 ] if main == 'total' or main == 'fail' : if main not in the_dict : the_dict [ main ] = { } the_dict [ m...
Used for getting stats for Plugin based stuff like Kafka Monitor and Redis Monitor
26,667
def _get_key_value ( self , key , is_hll = False ) : if is_hll : return self . redis_conn . execute_command ( "PFCOUNT" , key ) else : return self . redis_conn . zcard ( key )
Returns the proper key value for the stats
26,668
def get_crawler_stats ( self ) : self . logger . debug ( "Gathering crawler stats" ) the_dict = { } the_dict [ 'spiders' ] = self . get_spider_stats ( ) [ 'spiders' ] the_dict [ 'machines' ] = self . get_machine_stats ( ) [ 'machines' ] the_dict [ 'queue' ] = self . get_queue_stats ( ) [ 'queues' ] return the_dict
Gather crawler stats
26,669
def get_queue_stats ( self ) : self . logger . debug ( "Gathering queue based stats" ) the_dict = { } keys = self . redis_conn . keys ( '*:*:queue' ) total_backlog = 0 for key in keys : elements = key . split ( ":" ) spider = elements [ 0 ] domain = elements [ 1 ] spider = 'queue_' + spider if spider not in the_dict : ...
Gather queue stats
26,670
def main ( ) : import argparse from kazoo . client import KazooClient parser = argparse . ArgumentParser ( description = "Crawler config file pusher to Zookeeper" ) parser . add_argument ( '-f' , '--file' , action = 'store' , required = True , help = "The yaml file to use" ) parser . add_argument ( '-i' , '--id' , acti...
A manual configuration file pusher for the crawlers . This will update Zookeeper with the contents of the file specified in the args .
26,671
def is_subdict ( self , a , b ) : return all ( ( k in b and b [ k ] == v ) for k , v in a . iteritems ( ) )
Return True if a is a subdict of b
26,672
def _check_log_level ( self , level ) : if level not in list ( self . level_dict . keys ( ) ) : self . log_level = 'DEBUG' self . logger . warn ( "Unknown log level '{lev}', defaulting to DEBUG" . format ( lev = level ) )
Ensures a valid log level
26,673
def _get_formatter ( self , json ) : if json : return jsonlogger . JsonFormatter ( ) else : return logging . Formatter ( self . format_string )
Return the proper log formatter
26,674
def debug ( self , message , extra = { } ) : if self . level_dict [ 'DEBUG' ] >= self . level_dict [ self . log_level ] : extras = self . add_extras ( extra , "DEBUG" ) self . _write_message ( message , extras ) self . fire_callbacks ( 'DEBUG' , message , extra )
Writes an error message to the log
26,675
def _write_message ( self , message , extra ) : if not self . json : self . _write_standard ( message , extra ) else : self . _write_json ( message , extra )
Writes the log output
26,676
def _write_standard ( self , message , extra ) : level = extra [ 'level' ] if self . include_extra : del extra [ 'timestamp' ] del extra [ 'level' ] del extra [ 'logger' ] if len ( extra ) > 0 : message += " " + str ( extra ) if level == 'INFO' : self . logger . info ( message ) elif level == 'DEBUG' : self . logger . ...
Writes a standard log statement
26,677
def _write_json ( self , message , extra ) : self . logger . info ( message , extra = extra )
The JSON logger doesn t obey log levels
26,678
def add_extras ( self , dict , level ) : my_copy = copy . deepcopy ( dict ) if 'level' not in my_copy : my_copy [ 'level' ] = level if 'timestamp' not in my_copy : my_copy [ 'timestamp' ] = self . _get_time ( ) if 'logger' not in my_copy : my_copy [ 'logger' ] = self . name return my_copy
Adds the log level to the dict object
26,679
def _increment_504_stat ( self , request ) : for key in self . stats_dict : if key == 'lifetime' : unique = request . url + str ( time . time ( ) ) self . stats_dict [ key ] . increment ( unique ) else : self . stats_dict [ key ] . increment ( ) self . logger . debug ( "Incremented status_code '504' stats" )
Increments the 504 stat counters
26,680
def clear ( self ) : self . redis_conn . delete ( self . window_key ) self . redis_conn . delete ( self . moderate_key ) self . queue . clear ( )
Clears all data associated with the throttled queue
26,681
def pop ( self , * args ) : if self . allowed ( ) : if self . elastic_kick_in < self . limit : self . elastic_kick_in += 1 return self . queue . pop ( * args ) else : return None
Non - blocking from throttled queue standpoint tries to return a queue pop request only will return a request if the given time window has not been exceeded
26,682
def allowed ( self ) : expires = time . time ( ) - self . window self . redis_conn . zremrangebyscore ( self . window_key , '-inf' , expires ) if self . moderation : with self . redis_conn . pipeline ( ) as pipe : try : pipe . watch ( self . moderate_key ) curr_time = time . time ( ) if self . is_moderated ( curr_time ...
Check to see if the pop request is allowed
26,683
def check_elastic ( self ) : if self . elastic and self . elastic_kick_in == self . limit : value = self . redis_conn . zcard ( self . window_key ) if self . limit - value > self . elastic_buffer : return True return False
Checks if we need to break moderation in order to maintain our desired throttle limit
26,684
def is_moderated ( self , curr_time , pipe ) : value = pipe . get ( self . moderate_key ) if value is None : value = 0.0 else : value = float ( value ) if ( curr_time - value ) < self . moderation : return True return False
Tests to see if the moderation limit is not exceeded
26,685
def _get_bin ( self , key ) : sortedDict = { } for item in self . redis_conn . zscan_iter ( key ) : my_item = ujson . loads ( item [ 0 ] ) my_score = - item [ 1 ] if my_score not in sortedDict : sortedDict [ my_score ] = [ ] sortedDict [ my_score ] . append ( my_item ) return sortedDict
Returns a binned dictionary based on redis zscore
26,686
def _build_appid_info ( self , master , dict ) : master [ 'total_crawlids' ] = 0 master [ 'total_pending' ] = 0 master [ 'total_domains' ] = 0 master [ 'crawlids' ] = { } master [ 'appid' ] = dict [ 'appid' ] master [ 'spiderid' ] = dict [ 'spiderid' ] domain_dict = { } match_string = '{sid}:*:queue' . format ( sid = d...
Builds the appid info object
26,687
def _build_crawlid_info ( self , master , dict ) : master [ 'total_pending' ] = 0 master [ 'total_domains' ] = 0 master [ 'appid' ] = dict [ 'appid' ] master [ 'crawlid' ] = dict [ 'crawlid' ] master [ 'spiderid' ] = dict [ 'spiderid' ] master [ 'domains' ] = { } timeout_key = 'timeout:{sid}:{aid}:{cid}' . format ( sid...
Builds the crawlid info object
26,688
def _purge_crawl ( self , spiderid , appid , crawlid ) : total = self . _mini_purge ( spiderid , appid , crawlid ) total = total + self . _mini_purge ( spiderid , appid , crawlid ) total = total + self . _mini_purge ( spiderid , appid , crawlid ) return total
Wrapper for purging the crawlid from the queues
26,689
def _mini_purge ( self , spiderid , appid , crawlid ) : total_purged = 0 match_string = '{sid}:*:queue' . format ( sid = spiderid ) for key in self . redis_conn . scan_iter ( match = match_string ) : for item in self . redis_conn . zscan_iter ( key ) : item_key = item [ 0 ] item = ujson . loads ( item_key ) if 'meta' i...
Actually purges the crawlid from the queue
26,690
def log_call ( call_name ) : def decorator ( f ) : @ wraps ( f ) def wrapper ( * args , ** kw ) : instance = args [ 0 ] instance . logger . info ( call_name , { "content" : request . get_json ( ) } ) return f ( * args , ** kw ) return wrapper return decorator
Log the API call to the logger .
26,691
def error_catch ( f ) : @ wraps ( f ) def wrapper ( * args , ** kw ) : instance = args [ 0 ] try : result = f ( * args , ** kw ) if isinstance ( result , tuple ) : return jsonify ( result [ 0 ] ) , result [ 1 ] else : return jsonify ( result ) , 200 except Exception as e : ret_dict = instance . _create_ret_object ( ins...
Handle unexpected errors within the rest function .
26,692
def validate_json ( f ) : @ wraps ( f ) def wrapper ( * args , ** kw ) : instance = args [ 0 ] try : if request . get_json ( ) is None : ret_dict = instance . _create_ret_object ( instance . FAILURE , None , True , instance . MUST_JSON ) instance . logger . error ( instance . MUST_JSON ) return jsonify ( ret_dict ) , 4...
Validate that the call is JSON .
26,693
def validate_schema ( schema_name ) : def decorator ( f ) : @ wraps ( f ) def wrapper ( * args , ** kw ) : instance = args [ 0 ] try : instance . validator ( instance . schemas [ schema_name ] ) . validate ( request . get_json ( ) ) except ValidationError , e : ret_dict = instance . _create_ret_object ( instance . FAIL...
Validate the JSON against a required schema_name .
26,694
def _load_schemas ( self ) : for filename in os . listdir ( self . settings [ 'SCHEMA_DIR' ] ) : if filename [ - 4 : ] == 'json' : name = filename [ : - 5 ] with open ( self . settings [ 'SCHEMA_DIR' ] + filename ) as the_file : self . schemas [ name ] = json . load ( the_file ) self . logger . debug ( "Successfully lo...
Loads any schemas for JSON validation
26,695
def _spawn_redis_connection_thread ( self ) : self . logger . debug ( "Spawn redis connection thread" ) self . redis_connected = False self . _redis_thread = Thread ( target = self . _setup_redis ) self . _redis_thread . setDaemon ( True ) self . _redis_thread . start ( )
Spawns a redis connection thread
26,696
def _spawn_kafka_connection_thread ( self ) : self . logger . debug ( "Spawn kafka connection thread" ) self . kafka_connected = False self . _kafka_thread = Thread ( target = self . _setup_kafka ) self . _kafka_thread . setDaemon ( True ) self . _kafka_thread . start ( )
Spawns a kafka connection thread
26,697
def _consumer_loop ( self ) : self . logger . debug ( "running main consumer thread" ) while not self . closed : if self . kafka_connected : self . _process_messages ( ) time . sleep ( self . settings [ 'KAFKA_CONSUMER_SLEEP_TIME' ] )
The main consumer loop
26,698
def _process_messages ( self ) : try : for message in self . consumer : try : if message is None : self . logger . debug ( "no message" ) break loaded_dict = json . loads ( message . value ) self . logger . debug ( "got valid kafka message" ) with self . uuids_lock : if 'uuid' in loaded_dict : if loaded_dict [ 'uuid' ]...
Processes messages received from kafka
26,699
def _send_result_to_redis ( self , result ) : if self . redis_connected : self . logger . debug ( "Sending result to redis" ) try : key = "rest:poll:{u}" . format ( u = result [ 'uuid' ] ) self . redis_conn . set ( key , json . dumps ( result ) ) except ConnectionError : self . logger . error ( "Lost connection to Redi...
Sends the result of a poll to redis to be used potentially by another process