idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
19,300 | def run_with_output ( self , * args , ** kwargs ) : for job in self . jobs : job . run_with_output ( * args , ** kwargs ) | Runs command on every first job in the run returns stdout . |
19,301 | def _run_raw ( self , * args , ** kwargs ) : for job in self . jobs : job . _run_raw ( * args , ** kwargs ) | _run_raw on every job in the run . |
19,302 | def keypair_setup ( ) : os . system ( 'mkdir -p ' + u . PRIVATE_KEY_LOCATION ) keypair_name = u . get_keypair_name ( ) keypair = u . get_keypair_dict ( ) . get ( keypair_name , None ) keypair_fn = u . get_keypair_fn ( ) if keypair : print ( "Reusing keypair " + keypair_name ) assert os . path . exists ( keypair_fn ) , "Keypair %s exists, but corresponding .pem file %s is not found, delete keypair %s through console and run again to recreate keypair/.pem together" % ( keypair_name , keypair_fn , keypair_name ) keypair_contents = open ( keypair_fn ) . read ( ) assert len ( keypair_contents ) > 0 else : print ( "Creating keypair " + keypair_name ) ec2 = u . get_ec2_resource ( ) assert not os . path . exists ( keypair_fn ) , "previous keypair exists, delete it with 'sudo rm %s' and also delete corresponding keypair through console" % ( keypair_fn ) keypair = ec2 . create_key_pair ( KeyName = keypair_name ) open ( keypair_fn , 'w' ) . write ( keypair . key_material ) os . system ( 'chmod 400 ' + keypair_fn ) return keypair | Creates keypair if necessary saves private key locally returns contents of private key file . |
19,303 | def placement_group_setup ( group_name ) : existing_placement_groups = u . get_placement_group_dict ( ) group = existing_placement_groups . get ( group_name , None ) if group : assert group . state == 'available' assert group . strategy == 'cluster' print ( "Reusing group " , group . name ) return group print ( "Creating group " + group_name ) ec2 = u . get_ec2_resource ( ) group = ec2 . create_placement_group ( GroupName = group_name , Strategy = 'cluster' ) return group | Creates placement_group group if necessary . Returns True if new placement_group group was created False otherwise . |
19,304 | def upload ( self , local_fn : str , remote_fn : str = '' , dont_overwrite : bool = False ) : raise NotImplementedError ( ) | Uploads given file to the task . If remote_fn is not specified dumps it into task current directory with the same name . |
19,305 | def _non_blocking_wrapper ( self , method , * args , ** kwargs ) : exceptions = [ ] def task_run ( task ) : try : getattr ( task , method ) ( * args , ** kwargs ) except Exception as e : exceptions . append ( e ) threads = [ threading . Thread ( name = f'task_{method}_{i}' , target = task_run , args = [ t ] ) for i , t in enumerate ( self . tasks ) ] for thread in threads : thread . start ( ) for thread in threads : thread . join ( ) if exceptions : raise exceptions [ 0 ] | Runs given method on every task in the job . Blocks until all tasks finish . Propagates exception from first failed task . |
19,306 | def get_default_vpc ( ) : ec2 = get_ec2_resource ( ) for vpc in ec2 . vpcs . all ( ) : if vpc . is_default : return vpc | Return default VPC or none if not present |
19,307 | def get_subnet_dict ( ) : subnet_dict = { } vpc = get_vpc ( ) for subnet in vpc . subnets . all ( ) : zone = subnet . availability_zone assert zone not in subnet_dict , "More than one subnet in %s, why?" % ( zone , ) subnet_dict [ zone ] = subnet return subnet_dict | Returns dictionary of availability zone - > subnet for current VPC . |
19,308 | def get_keypair_name ( ) : username = get_username ( ) assert '-' not in username , "username must not contain -, change $USER" validate_aws_name ( username ) assert len ( username ) < 30 return get_prefix ( ) + '-' + username | Returns current keypair name . |
19,309 | def get_keypair_fn ( ) : keypair_name = get_keypair_name ( ) account = get_account_number ( ) region = get_region ( ) fn = f'{PRIVATE_KEY_LOCATION}/{keypair_name}-{account}-{region}.pem' return fn | Location of . pem file for current keypair |
19,310 | def lookup_instance ( name : str , instance_type : str = '' , image_name : str = '' , states : tuple = ( 'running' , 'stopped' , 'initializing' ) ) : ec2 = get_ec2_resource ( ) instances = ec2 . instances . filter ( Filters = [ { 'Name' : 'instance-state-name' , 'Values' : states } ] ) prefix = get_prefix ( ) username = get_username ( ) result = [ ] for i in instances . all ( ) : instance_name = get_name ( i ) if instance_name != name : continue seen_prefix , seen_username = parse_key_name ( i . key_name ) if prefix != seen_prefix : print ( f"Found {name} launched under {seen_prefix}, ignoring" ) continue if username != seen_username : print ( f"Found {name} launched by {seen_username}, ignoring" ) continue if instance_type : assert i . instance_type == instance_type , f"Found existing instance for job {name} but different instance type ({i.instance_type}) than requested ({instance_type}), terminate {name} first or use new task name." if image_name : assert i . image . name == image_name , f"Found existing instance for job {name} but launched with different image ({i.image.name}) than requested ({image_name}), terminate {name} first or use new task name." result . append ( i ) assert len ( result ) < 2 , f"Found two instances with name {name}" if not result : return None else : return result [ 0 ] | Looks up AWS instance for given instance name like simple . worker . If no instance found in current AWS environment returns None . |
19,311 | def ssh_to_task ( task ) -> paramiko . SSHClient : username = task . ssh_username hostname = task . public_ip ssh_key_fn = get_keypair_fn ( ) print ( f"ssh -i {ssh_key_fn} {username}@{hostname}" ) pkey = paramiko . RSAKey . from_private_key_file ( ssh_key_fn ) ssh_client = paramiko . SSHClient ( ) ssh_client . set_missing_host_key_policy ( paramiko . AutoAddPolicy ( ) ) assert ssh_client counter = 1 while True : try : ssh_client . connect ( hostname = hostname , username = username , pkey = pkey ) if counter % 11 == 0 : hostname = task . public_ip break except Exception as e : print ( f'{task.name}: Exception connecting to {hostname} via ssh (could be a timeout): {e}' ) time . sleep ( RETRY_INTERVAL_SEC ) return ssh_client | Create ssh connection to task s machine |
19,312 | def delete_efs_by_id ( efs_id ) : start_time = time . time ( ) efs_client = get_efs_client ( ) sys . stdout . write ( "deleting %s ... " % ( efs_id , ) ) while True : try : response = efs_client . delete_file_system ( FileSystemId = efs_id ) if is_good_response ( response ) : print ( "succeeded" ) break time . sleep ( RETRY_INTERVAL_SEC ) except Exception as e : print ( "Failed with %s" % ( e , ) ) if time . time ( ) - start_time - RETRY_INTERVAL_SEC < RETRY_TIMEOUT_SEC : print ( "Retrying in %s sec" % ( RETRY_INTERVAL_SEC , ) ) time . sleep ( RETRY_INTERVAL_SEC ) else : print ( "Giving up" ) break | Deletion sometimes fails try several times . |
19,313 | def extract_attr_for_match ( items , ** kwargs ) : query_arg = None for arg , value in kwargs . items ( ) : if value == - 1 : assert query_arg is None , "Only single query arg (-1 valued) is allowed" query_arg = arg result = [ ] filterset = set ( kwargs . keys ( ) ) for item in items : match = True assert filterset . issubset ( item . keys ( ) ) , "Filter set contained %s which was not in record %s" % ( filterset . difference ( item . keys ( ) ) , item ) for arg in item : if arg == query_arg : continue if arg in kwargs : if item [ arg ] != kwargs [ arg ] : match = False break if match : result . append ( item [ query_arg ] ) assert len ( result ) <= 1 , "%d values matched %s, only allow 1" % ( len ( result ) , kwargs ) if result : return result [ 0 ] return None | Helper method to get attribute value for an item matching some criterion . Specify target criteria value as dict with target attribute having value - 1 |
19,314 | def get_instance_property ( instance , property_name ) : name = get_name ( instance ) while True : try : value = getattr ( instance , property_name ) if value is not None : break print ( f"retrieving {property_name} on {name} produced None, retrying" ) time . sleep ( RETRY_INTERVAL_SEC ) instance . reload ( ) continue except Exception as e : print ( f"retrieving {property_name} on {name} failed with {e}, retrying" ) time . sleep ( RETRY_INTERVAL_SEC ) try : instance . reload ( ) except Exception : pass continue return value | Retrieves property of an instance keeps retrying until getting a non - None |
19,315 | def wait_until_available ( resource ) : while True : resource . load ( ) if resource . state == 'available' : break time . sleep ( RETRY_INTERVAL_SEC ) | Waits until interval state becomes available |
19,316 | def maybe_create_placement_group ( name = '' , max_retries = 10 ) : if not name : return client = get_ec2_client ( ) while True : try : client . describe_placement_groups ( GroupNames = [ name ] ) print ( "Reusing placement_group group: " + name ) break except Exception : print ( "Creating placement_group group: " + name ) try : _response = client . create_placement_group ( GroupName = name , Strategy = 'cluster' ) except Exception : pass counter = 0 while True : try : res = client . describe_placement_groups ( GroupNames = [ name ] ) res_entry = res [ 'PlacementGroups' ] [ 0 ] if res_entry [ 'State' ] == 'available' : assert res_entry [ 'Strategy' ] == 'cluster' break except Exception as e : print ( "Got exception: %s" % ( e , ) ) counter += 1 if counter >= max_retries : assert False , f'Failed to create placement_group group {name} in {max_retries} attempts' time . sleep ( RETRY_INTERVAL_SEC ) | Creates placement_group group or reuses existing one . Crash if unable to create placement_group group . If name is empty ignores request . |
19,317 | def is_chief ( task : backend . Task , run_name : str ) : global run_task_dict if run_name not in run_task_dict : return True task_list = run_task_dict [ run_name ] assert task in task_list , f"Task {task.name} doesn't belong to run {run_name}" return task_list [ 0 ] == task | Returns True if task is chief task in the corresponding run |
19,318 | def ossystem ( cmd ) : p = subprocess . Popen ( cmd , shell = True , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) ( stdout , stderr ) = p . communicate ( ) return stdout . decode ( 'ascii' ) | Like os . system but returns output of command as string . |
19,319 | def _maybe_create_resources ( logging_task : Task = None ) : def log ( * args ) : if logging_task : logging_task . log ( * args ) else : util . log ( * args ) def should_create_resources ( ) : prefix = u . get_prefix ( ) if u . get_keypair_name ( ) not in u . get_keypair_dict ( ) : log ( f"Missing {u.get_keypair_name()} keypair, creating resources" ) return True vpcs = u . get_vpc_dict ( ) if prefix not in vpcs : log ( f"Missing {prefix} vpc, creating resources" ) return True vpc = vpcs [ prefix ] gateways = u . get_gateway_dict ( vpc ) if prefix not in gateways : log ( f"Missing {prefix} gateway, creating resources" ) return True return False try : if os . path . exists ( AWS_LOCK_FN ) : pid , ts , lock_taskname = open ( AWS_LOCK_FN ) . read ( ) . split ( '-' ) ts = int ( ts ) log ( f"waiting for aws resource creation, another resource initiation was " f"initiated {int(time.time()-ts)} seconds ago by " f"{lock_taskname}, delete lock file " f"{AWS_LOCK_FN} if this is an error" ) while True : if os . path . exists ( AWS_LOCK_FN ) : log ( f"waiting for lock file {AWS_LOCK_FN} to get deleted " f"initiated {int(time.time()-ts)} seconds ago by " ) time . sleep ( 2 ) continue else : break return with open ( AWS_LOCK_FN , 'w' ) as f : f . write ( f'{os.getpid()}-{int(time.time())}-{logging_task.name if logging_task else ""}' ) if not should_create_resources ( ) : util . log ( "Resources already created, no-op" ) os . remove ( AWS_LOCK_FN ) return create_lib . create_resources ( ) finally : if os . path . exists ( AWS_LOCK_FN ) : os . remove ( AWS_LOCK_FN ) | Use heuristics to decide to possibly create resources |
19,320 | def _set_aws_environment ( task : Task = None ) : current_zone = os . environ . get ( 'NCLUSTER_ZONE' , '' ) current_region = os . environ . get ( 'AWS_DEFAULT_REGION' , '' ) def log ( * args ) : if task : task . log ( * args ) else : util . log ( * args ) if current_region and current_zone : assert current_zone . startswith ( current_region ) , f'Current zone "{current_zone}" ($NCLUSTER_ZONE) is not ' f'in current region "{current_region} ($AWS_DEFAULT_REGION)' assert u . get_session ( ) . region_name == current_region if current_zone and not current_region : current_region = current_zone [ : - 1 ] os . environ [ 'AWS_DEFAULT_REGION' ] = current_region if not current_region : current_region = u . get_session ( ) . region_name if not current_region : log ( f"No default region available, using {NCLUSTER_DEFAULT_REGION}" ) current_region = NCLUSTER_DEFAULT_REGION os . environ [ 'AWS_DEFAULT_REGION' ] = current_region log ( f"Using account {u.get_account_number()}, region {current_region}, " f"zone {current_zone}" ) | Sets up AWS environment from NCLUSTER environment variables |
19,321 | def join ( self , ignore_errors = False ) : assert self . _status_fn , "Asked to join a task which hasn't had any commands executed on it" check_interval = 0.2 status_fn = self . _status_fn if not self . wait_for_file ( status_fn , max_wait_sec = 30 ) : self . log ( f"Retrying waiting for {status_fn}" ) while not self . exists ( status_fn ) : self . log ( f"Still waiting for {self._cmd}" ) self . wait_for_file ( status_fn , max_wait_sec = 30 ) contents = self . read ( status_fn ) if len ( contents ) == 0 : time . sleep ( check_interval ) contents = self . read ( status_fn ) status = int ( contents . strip ( ) ) self . last_status = status if status != 0 : extra_msg = '(ignoring error)' if ignore_errors else '(failing)' if util . is_set ( 'NCLUSTER_RUN_WITH_OUTPUT_ON_FAILURE' ) or True : self . log ( f"Start failing output {extra_msg}: \n{'*'*80}\n\n '{self.read(self._out_fn)}'" ) self . log ( f"\n{'*'*80}\nEnd failing output" ) if not ignore_errors : raise RuntimeError ( f"Command {self._cmd} returned status {status}" ) else : self . log ( f"Warning: command {self._cmd} returned status {status}" ) return status | Waits until last executed command completed . |
19,322 | def _run_with_output_on_failure ( self , cmd , non_blocking = False , ignore_errors = False , max_wait_sec = 365 * 24 * 3600 , check_interval = 0.2 ) -> str : if not self . _can_run : assert False , "Using .run before initialization finished" if '\n' in cmd : assert False , "Don't support multi-line for run2" cmd = cmd . strip ( ) if cmd . startswith ( '#' ) : return '' self . run_counter += 1 self . log ( "tmux> %s" , cmd ) self . _cmd = cmd self . _cmd_fn = f'{self.remote_scratch}/{self.run_counter}.cmd' self . _status_fn = f'{self.remote_scratch}/{self.run_counter}.status' self . _out_fn = f'{self.remote_scratch}/{self.run_counter}.out' cmd = util . shell_strip_comment ( cmd ) assert '&' not in cmd , f"cmd {cmd} contains &, that breaks things" self . file_write ( self . _cmd_fn , cmd + '\n' ) modified_cmd = f'{cmd} > >(tee -a {self._out_fn}) 2> >(tee -a {self._out_fn} >&2); echo $? > {self._status_fn}' modified_cmd = shlex . quote ( modified_cmd ) start_time = time . time ( ) tmux_window = self . tmux_session + ':' + str ( self . tmux_window_id ) tmux_cmd = f"tmux send-keys -t {tmux_window} {modified_cmd} Enter" self . _run_raw ( tmux_cmd , ignore_errors = ignore_errors ) if non_blocking : return 0 if not self . wait_for_file ( self . _status_fn , max_wait_sec = 60 ) : self . log ( f"Retrying waiting for {self._status_fn}" ) elapsed_time = time . time ( ) - start_time while not self . exists ( self . _status_fn ) and elapsed_time < max_wait_sec : self . log ( f"Still waiting for {cmd}" ) self . wait_for_file ( self . _status_fn , max_wait_sec = 60 ) elapsed_time = time . time ( ) - start_time contents = self . read ( self . _status_fn ) if len ( contents ) == 0 : time . sleep ( check_interval ) contents = self . read ( self . _status_fn ) status = int ( contents . strip ( ) ) self . last_status = status if status != 0 : extra_msg = '(ignoring error)' if ignore_errors else '(failing)' self . log ( f"Start failing output {extra_msg}: \n{'*'*80}\n\n '{self.read(self._out_fn)}'" ) self . log ( f"\n{'*'*80}\nEnd failing output" ) if not ignore_errors : raise RuntimeError ( f"Command {cmd} returned status {status}" ) else : self . log ( f"Warning: command {cmd} returned status {status}" ) return self . read ( self . _out_fn ) | Experimental version of run propagates error messages to client . This command will be default run eventually |
19,323 | def upload ( self , local_fn : str , remote_fn : str = '' , dont_overwrite : bool = False ) -> None : if '*' in local_fn : for local_subfn in glob . glob ( local_fn ) : self . upload ( local_subfn ) return if '#' in local_fn : self . log ( "skipping backup file {local_fn}" ) return if not self . sftp : self . sftp = u . call_with_retries ( self . ssh_client . open_sftp , 'self.ssh_client.open_sftp' ) def maybe_fix_mode ( local_fn_ , remote_fn_ ) : mode = oct ( os . stat ( local_fn_ ) [ stat . ST_MODE ] ) [ - 3 : ] if '7' in mode : self . log ( f"Making {remote_fn_} executable with mode {mode}" ) self . _run_raw ( f"chmod {mode} {remote_fn_}" ) def _put_dir ( source , target ) : def _safe_mkdir ( path , mode = 511 , ignore_existing = True ) : try : self . sftp . mkdir ( path , mode ) except IOError : if ignore_existing : pass else : raise assert os . path . isdir ( source ) _safe_mkdir ( target ) for item in os . listdir ( source ) : if os . path . isfile ( os . path . join ( source , item ) ) : self . sftp . put ( os . path . join ( source , item ) , os . path . join ( target , item ) ) maybe_fix_mode ( os . path . join ( source , item ) , os . path . join ( target , item ) ) else : _safe_mkdir ( f'{target}/{item}' ) _put_dir ( f'{source}/{item}' , f'{target}/{item}' ) if not remote_fn : remote_fn = os . path . basename ( local_fn ) self . log ( 'uploading ' + local_fn + ' to ' + remote_fn ) remote_fn = remote_fn . replace ( '~' , self . homedir ) if '/' in remote_fn : remote_dir = os . path . dirname ( remote_fn ) assert self . exists ( remote_dir ) , f"Remote dir {remote_dir} doesn't exist" if dont_overwrite and self . exists ( remote_fn ) : self . log ( "Remote file %s exists, skipping" % ( remote_fn , ) ) return assert os . path . exists ( local_fn ) , f"{local_fn} not found" if os . path . isdir ( local_fn ) : _put_dir ( local_fn , remote_fn ) else : assert os . path . isfile ( local_fn ) , "%s is not a file" % ( local_fn , ) if self . exists ( remote_fn ) and self . isdir ( remote_fn ) : remote_fn = remote_fn + '/' + os . path . basename ( local_fn ) self . sftp . put ( localpath = local_fn , remotepath = remote_fn ) maybe_fix_mode ( local_fn , remote_fn ) | Uploads file to remote instance . If location not specified dumps it into default directory . If remote location has files or directories with the same name behavior is undefined . |
19,324 | def _replace_lines ( fn , startswith , new_line ) : new_lines = [ ] for line in open ( fn ) : if line . startswith ( startswith ) : new_lines . append ( new_line ) else : new_lines . append ( line ) with open ( fn , 'w' ) as f : f . write ( '\n' . join ( new_lines ) ) | Replace lines starting with starts_with in fn with new_line . |
19,325 | def now_micros ( absolute = False ) -> int : micros = int ( time . time ( ) * 1e6 ) if absolute : return micros return micros - EPOCH_MICROS | Return current micros since epoch as integer . |
19,326 | def now_millis ( absolute = False ) -> int : millis = int ( time . time ( ) * 1e3 ) if absolute : return millis return millis - EPOCH_MICROS // 1000 | Return current millis since epoch as integer . |
19,327 | def install_pdb_handler ( ) : import signal import pdb def handler ( _signum , _frame ) : pdb . set_trace ( ) signal . signal ( signal . SIGQUIT , handler ) | Make CTRL + \ break into gdb . |
19,328 | def shell_add_echo ( script ) : new_script = "" for cmd in script . split ( '\n' ) : cmd = cmd . strip ( ) if not cmd : continue new_script += "echo \\* " + shlex . quote ( cmd ) + "\n" new_script += cmd + "\n" return new_script | Goes over each line script adds echo cmd in front of each cmd . |
19,329 | def random_id ( k = 5 ) : return '' . join ( random . choices ( string . ascii_lowercase + string . digits , k = k ) ) | Random id to use for AWS identifiers . |
19,330 | def alphanumeric_hash ( s : str , size = 5 ) : import hashlib import base64 hash_object = hashlib . md5 ( s . encode ( 'ascii' ) ) s = base64 . b32encode ( hash_object . digest ( ) ) result = s [ : size ] . decode ( 'ascii' ) . lower ( ) return result | Short alphanumeric string derived from hash of given string |
19,331 | def is_bash_builtin ( cmd ) : bash_builtins = [ 'alias' , 'bg' , 'bind' , 'alias' , 'bg' , 'bind' , 'break' , 'builtin' , 'caller' , 'cd' , 'command' , 'compgen' , 'complete' , 'compopt' , 'continue' , 'declare' , 'dirs' , 'disown' , 'echo' , 'enable' , 'eval' , 'exec' , 'exit' , 'export' , 'false' , 'fc' , 'fg' , 'getopts' , 'hash' , 'help' , 'history' , 'jobs' , 'kill' , 'let' , 'local' , 'logout' , 'mapfile' , 'popd' , 'printf' , 'pushd' , 'pwd' , 'read' , 'readarray' , 'readonly' , 'return' , 'set' , 'shift' , 'shopt' , 'source' , 'suspend' , 'test' , 'times' , 'trap' , 'true' , 'type' , 'typeset' , 'ulimit' , 'umask' , 'unalias' , 'unset' , 'wait' ] toks = cmd . split ( ) if toks and toks [ 0 ] in bash_builtins : return True return False | Return true if command is invoking bash built - in |
19,332 | def is_set ( name ) : val = os . environ . get ( name , '0' ) assert val == '0' or val == '1' , f"env var {name} has value {val}, expected 0 or 1" return val == '1' | Helper method to check if given property is set |
19,333 | def assert_script_in_current_directory ( ) : script = sys . argv [ 0 ] assert os . path . abspath ( os . path . dirname ( script ) ) == os . path . abspath ( '.' ) , f"Change into directory of script {script} and run again." | Assert fail if current directory is different from location of the script |
19,334 | def load_fixtures ( db , fixtures ) : conn = db . engine . connect ( ) metadata = db . metadata for fixture in fixtures : if 'model' in fixture : module_name , class_name = fixture [ 'model' ] . rsplit ( '.' , 1 ) module = importlib . import_module ( module_name ) model = getattr ( module , class_name ) for fields in fixture [ 'records' ] : obj = model ( ** fields ) db . session . add ( obj ) db . session . commit ( ) elif 'table' in fixture : table = Table ( fixture [ 'table' ] , metadata ) conn . execute ( table . insert ( ) , fixture [ 'records' ] ) else : raise ValueError ( "Fixture missing a 'model' or 'table' field: {0}" . format ( json . dumps ( fixture ) ) ) | Loads the given fixtures into the database . |
19,335 | def setup_handler ( setup_fixtures_fn , setup_fn ) : def handler ( obj ) : setup_fixtures_fn ( obj ) setup_fn ( obj ) return handler | Returns a function that adds fixtures handling to the setup method . |
19,336 | def teardown_handler ( teardown_fixtures_fn , teardown_fn ) : def handler ( obj ) : teardown_fn ( obj ) teardown_fixtures_fn ( obj ) return handler | Returns a function that adds fixtures handling to the teardown method . |
19,337 | def get_child_fn ( attrs , names , bases ) : def call_method ( obj , method ) : if isinstance ( obj , type ) : instance = None owner = obj else : instance = obj owner = obj . __class__ method . __get__ ( instance , owner ) ( ) default_name = names [ 0 ] def default_fn ( obj ) : for cls in bases : if hasattr ( cls , default_name ) : call_method ( obj , getattr ( cls , default_name ) ) default_fn . __name__ = default_name fns = [ ( name , attrs [ name ] ) for name in names if name in attrs ] if len ( fns ) > 1 : raise RuntimeError ( "Cannot have more than one setup or teardown method per context (class or test)." ) elif len ( fns ) == 1 : name , fn = fns [ 0 ] def child_fn ( obj ) : call_method ( obj , fn ) child_fn . __name__ = name return child_fn else : return default_fn | Returns a function from the child class that matches one of the names . |
19,338 | def print_msg ( msg , header , file = sys . stdout ) : DEFAULT_MSG_BLOCK_WIDTH = 60 side_boarder_length = ( DEFAULT_MSG_BLOCK_WIDTH - ( len ( header ) + 2 ) ) // 2 msg_block_width = side_boarder_length * 2 + ( len ( header ) + 2 ) side_boarder = '#' * side_boarder_length top_boarder = '{0} {1} {2}' . format ( side_boarder , header , side_boarder ) bottom_boarder = '#' * msg_block_width def pad ( line , length ) : padding_length = length - len ( line ) left_padding = ' ' * ( padding_length // 2 ) right_padding = ' ' * ( padding_length - len ( left_padding ) ) return '{0} {1} {2}' . format ( left_padding , line , right_padding ) words = msg . split ( ' ' ) lines = [ ] line = '' for word in words : if len ( line + ' ' + word ) <= msg_block_width - 4 : line = ( line + ' ' + word ) . strip ( ) else : lines . append ( '#{0}#' . format ( pad ( line , msg_block_width - 4 ) ) ) line = word lines . append ( '#{0}#' . format ( pad ( line , msg_block_width - 4 ) ) ) print ( file = file ) print ( top_boarder , file = file ) print ( '#{0}#' . format ( pad ( '' , msg_block_width - 4 ) ) , file = file ) for line in lines : print ( line , file = file ) print ( '#{0}#' . format ( pad ( '' , msg_block_width - 4 ) ) , file = file ) print ( bottom_boarder , file = file ) print ( file = file ) | Prints a boardered message to the screen |
19,339 | def can_persist_fixtures ( ) : if sys . hexversion >= 0x02070000 : return True filename = inspect . stack ( ) [ - 1 ] [ 1 ] executable = os . path . split ( filename ) [ 1 ] return executable in ( 'py.test' , 'nosetests' ) | Returns True if it s possible to persist fixtures across tests . |
19,340 | def read_since_ids ( users ) : since_ids = { } for user in users : if config . has_option ( SECTIONS [ 'INCREMENTS' ] , user ) : since_ids [ user ] = config . getint ( SECTIONS [ 'INCREMENTS' ] , user ) + 1 return since_ids | Read max ids of the last downloads |
19,341 | def set_max_ids ( max_ids ) : config . read ( CONFIG ) for user , max_id in max_ids . items ( ) : config . set ( SECTIONS [ 'INCREMENTS' ] , user , str ( max_id ) ) with open ( CONFIG , 'w' ) as f : config . write ( f ) | Set max ids of the current downloads |
19,342 | def authenticate ( self , username = None , password = None , actions = None , response = None , authorization = None ) : if response is None : with warnings . catch_warnings ( ) : _ignore_warnings ( self ) response = self . _sessions [ 0 ] . get ( self . _base_url , verify = self . _tlsverify ) if response . ok : return None if response . status_code != requests . codes . unauthorized : raise exceptions . DXFUnexpectedStatusCodeError ( response . status_code , requests . codes . unauthorized ) if self . _insecure : raise exceptions . DXFAuthInsecureError ( ) parsed = www_authenticate . parse ( response . headers [ 'www-authenticate' ] ) if username is not None and password is not None : headers = { 'Authorization' : 'Basic ' + base64 . b64encode ( _to_bytes_2and3 ( username + ':' + password ) ) . decode ( 'utf-8' ) } elif authorization is not None : headers = { 'Authorization' : authorization } else : headers = { } if 'bearer' in parsed : info = parsed [ 'bearer' ] if actions and self . _repo : scope = 'repository:' + self . _repo + ':' + ',' . join ( actions ) elif 'scope' in info : scope = info [ 'scope' ] else : scope = '' url_parts = list ( urlparse . urlparse ( info [ 'realm' ] ) ) query = urlparse . parse_qs ( url_parts [ 4 ] ) query . update ( { 'service' : info [ 'service' ] , 'scope' : scope } ) url_parts [ 4 ] = urlencode ( query , True ) url_parts [ 0 ] = 'https' if self . _auth_host : url_parts [ 1 ] = self . _auth_host auth_url = urlparse . urlunparse ( url_parts ) with warnings . catch_warnings ( ) : _ignore_warnings ( self ) r = self . _sessions [ 0 ] . get ( auth_url , headers = headers , verify = self . _tlsverify ) _raise_for_status ( r ) rjson = r . json ( ) self . token = rjson [ 'access_token' ] if 'access_token' in rjson else rjson [ 'token' ] return self . _token self . _headers = headers return None | Authenticate to the registry using a username and password an authorization header or otherwise as the anonymous user . |
19,343 | def list_repos ( self , batch_size = None , iterate = False ) : it = PaginatingResponse ( self , '_base_request' , '_catalog' , 'repositories' , params = { 'n' : batch_size } ) return it if iterate else list ( it ) | List all repositories in the registry . |
19,344 | def pull_blob ( self , digest , size = False , chunk_size = None ) : if chunk_size is None : chunk_size = 8192 r = self . _request ( 'get' , 'blobs/' + digest , stream = True ) class Chunks ( object ) : def __iter__ ( self ) : sha256 = hashlib . sha256 ( ) for chunk in r . iter_content ( chunk_size ) : sha256 . update ( chunk ) yield chunk dgst = 'sha256:' + sha256 . hexdigest ( ) if dgst != digest : raise exceptions . DXFDigestMismatchError ( dgst , digest ) return ( Chunks ( ) , long ( r . headers [ 'content-length' ] ) ) if size else Chunks ( ) | Download a blob from the registry given the hash of its content . |
19,345 | def blob_size ( self , digest ) : r = self . _request ( 'head' , 'blobs/' + digest ) return long ( r . headers [ 'content-length' ] ) | Return the size of a blob in the registry given the hash of its content . |
19,346 | def get_manifest_and_response ( self , alias ) : r = self . _request ( 'get' , 'manifests/' + alias , headers = { 'Accept' : _schema2_mimetype + ', ' + _schema1_mimetype } ) return r . content . decode ( 'utf-8' ) , r | Request the manifest for an alias and return the manifest and the response . |
19,347 | def get_alias ( self , alias = None , manifest = None , verify = True , sizes = False , dcd = None ) : return self . _get_alias ( alias , manifest , verify , sizes , dcd , False ) | Get the blob hashes assigned to an alias . |
19,348 | def _get_dcd ( self , alias ) : return self . _request ( 'head' , 'manifests/{}' . format ( alias ) , headers = { 'Accept' : _schema2_mimetype } , ) . headers . get ( 'Docker-Content-Digest' ) | Get the Docker - Content - Digest header for an alias . |
19,349 | def get_name ( self , name_case = DdlParseBase . NAME_CASE . original ) : if name_case == self . NAME_CASE . lower : return self . _name . lower ( ) elif name_case == self . NAME_CASE . upper : return self . _name . upper ( ) else : return self . _name | Get Name converted case |
19,350 | def bigquery_data_type ( self ) : BQ_DATA_TYPE_DIC = OrderedDict ( ) BQ_DATA_TYPE_DIC [ "STRING" ] = { None : [ re . compile ( r"(CHAR|TEXT|CLOB|JSON|UUID)" ) ] } BQ_DATA_TYPE_DIC [ "INTEGER" ] = { None : [ re . compile ( r"INT|SERIAL|YEAR" ) ] } BQ_DATA_TYPE_DIC [ "FLOAT" ] = { None : [ re . compile ( r"(FLOAT|DOUBLE)" ) , "REAL" , "MONEY" ] } BQ_DATA_TYPE_DIC [ "DATETIME" ] = { None : [ "DATETIME" , "TIMESTAMP" , "TIMESTAMP WITHOUT TIME ZONE" ] , self . DATABASE . oracle : [ "DATE" ] } BQ_DATA_TYPE_DIC [ "TIMESTAMP" ] = { None : [ "TIMESTAMPTZ" , "TIMESTAMP WITH TIME ZONE" ] } BQ_DATA_TYPE_DIC [ "DATE" ] = { None : [ "DATE" ] } BQ_DATA_TYPE_DIC [ "TIME" ] = { None : [ "TIME" ] } BQ_DATA_TYPE_DIC [ "BOOLEAN" ] = { None : [ re . compile ( r"BOOL" ) ] } for bq_type , conditions in BQ_DATA_TYPE_DIC . items ( ) : for source_db , source_datatypes in conditions . items ( ) : for source_datatype in source_datatypes : if isinstance ( source_datatype , str ) : if self . _data_type == source_datatype and ( self . _source_database == source_db or ( self . _source_database is not None and source_db is None ) ) : return bq_type elif re . search ( source_datatype , self . _data_type ) and ( self . _source_database == source_db or ( self . _source_database is not None and source_db is None ) ) : return bq_type if self . _data_type in [ "NUMERIC" , "NUMBER" , "DECIMAL" ] : if self . _scale is not None : return "FLOAT" if self . _data_type == "NUMBER" and self . _source_database == self . DATABASE . oracle and self . _length is None : return "FLOAT" return "INTEGER" raise ValueError ( "Unknown data type : '{}'" . format ( self . _data_type ) ) | Get BigQuery Legacy SQL data type |
19,351 | def to_bigquery_field ( self , name_case = DdlParseBase . NAME_CASE . original ) : col_name = self . get_name ( name_case ) mode = self . bigquery_mode if self . array_dimensional <= 1 : type = self . bigquery_legacy_data_type else : type = "RECORD" fields = OrderedDict ( ) fields_cur = fields for i in range ( 1 , self . array_dimensional ) : is_last = True if i == self . array_dimensional - 1 else False fields_cur [ 'fields' ] = [ OrderedDict ( ) ] fields_cur = fields_cur [ 'fields' ] [ 0 ] fields_cur [ 'name' ] = "dimension_{}" . format ( i ) fields_cur [ 'type' ] = self . bigquery_legacy_data_type if is_last else "RECORD" fields_cur [ 'mode' ] = self . bigquery_mode if is_last else "REPEATED" col = OrderedDict ( ) col [ 'name' ] = col_name col [ 'type' ] = type col [ 'mode' ] = mode if self . array_dimensional > 1 : col [ 'fields' ] = fields [ 'fields' ] return json . dumps ( col ) | Generate BigQuery JSON field define |
19,352 | def to_bigquery_ddl ( self , name_case = DdlParseBase . NAME_CASE . original ) : if self . schema is None : dataset = "dataset" elif name_case == self . NAME_CASE . lower : dataset = self . schema . lower ( ) elif name_case == self . NAME_CASE . upper : dataset = self . schema . upper ( ) else : dataset = self . schema cols_defs = [ ] for col in self . columns . values ( ) : col_name = col . get_name ( name_case ) if col . array_dimensional < 1 : type = col . bigquery_standard_data_type not_null = " NOT NULL" if col . not_null else "" else : type_front = "ARRAY<" type_back = ">" for i in range ( 1 , col . array_dimensional ) : type_front += "STRUCT<dimension_{} ARRAY<" . format ( i ) type_back += ">>" type = "{}{}{}" . format ( type_front , col . bigquery_standard_data_type , type_back ) not_null = "" cols_defs . append ( "{name} {type}{not_null}" . format ( name = col_name , type = type , not_null = not_null , ) ) return textwrap . dedent ( ) . format ( dataset = dataset , table = self . get_name ( name_case ) , colmns_define = ",\n " . join ( cols_defs ) , ) | Generate BigQuery CREATE TABLE statements |
19,353 | def parse ( self , ddl = None , source_database = None ) : if ddl is not None : self . _ddl = ddl if source_database is not None : self . source_database = source_database if self . _ddl is None : raise ValueError ( "DDL is not specified" ) ret = self . _DDL_PARSE_EXPR . parseString ( self . _ddl ) if "schema" in ret : self . _table . schema = ret [ "schema" ] self . _table . name = ret [ "table" ] self . _table . is_temp = True if "temp" in ret else False for ret_col in ret [ "columns" ] : if ret_col . getName ( ) == "column" : col = self . _table . columns . append ( column_name = ret_col [ "name" ] , data_type_array = ret_col [ "type" ] , array_brackets = ret_col [ 'array_brackets' ] if "array_brackets" in ret_col else None ) if "constraint" in ret_col : col . constraint = ret_col [ "constraint" ] elif ret_col . getName ( ) == "constraint" : for col_name in ret_col [ "constraint_columns" ] : col = self . _table . columns [ col_name ] if ret_col [ "type" ] == "PRIMARY KEY" : col . not_null = True col . primary_key = True elif ret_col [ "type" ] in [ "UNIQUE" , "UNIQUE KEY" ] : col . unique = True elif ret_col [ "type" ] == "NOT NULL" : col . not_null = True return self . _table | Parse DDL script . |
19,354 | def launch ( program , sock , stderr = True , cwd = None , env = None ) : if stderr is True : err = sock elif stderr is False : err = open ( os . devnull , 'wb' ) elif stderr is None : err = None p = subprocess . Popen ( program , shell = type ( program ) not in ( list , tuple ) , stdin = sock , stdout = sock , stderr = err , cwd = cwd , env = env , close_fds = True ) sock . close ( ) return p | A static method for launching a process that is connected to a given socket . Same rules from the Process constructor apply . |
19,355 | def respond ( self , packet , peer , flags = 0 ) : self . sock . sendto ( packet , flags , peer ) | Send a message back to a peer . |
19,356 | def shutdown_rd ( self ) : if self . _sock_send is not None : self . sock . close ( ) else : return self . shutdown ( socket . SHUT_RD ) | Send a shutdown signal for reading - you may no longer read from this socket . |
19,357 | def shutdown_wr ( self ) : if self . _sock_send is not None : self . _sock_send . close ( ) else : return self . shutdown ( socket . SHUT_WR ) | Send a shutdown signal for writing - you may no longer write to this socket . |
19,358 | def _recv_predicate ( self , predicate , timeout = 'default' , raise_eof = True ) : if timeout == 'default' : timeout = self . _timeout self . timed_out = False start = time . time ( ) try : while True : cut_at = predicate ( self . buf ) if cut_at > 0 : break if timeout is not None : time_elapsed = time . time ( ) - start if time_elapsed > timeout : raise socket . timeout self . _settimeout ( timeout - time_elapsed ) data = self . _recv ( 4096 ) self . _log_recv ( data , False ) self . buf += data if not data : if raise_eof : raise NetcatError ( "Connection dropped!" ) cut_at = len ( self . buf ) break except KeyboardInterrupt : self . _print_header ( '\n======== Connection interrupted! ========' ) raise except socket . timeout : self . timed_out = True if self . _raise_timeout : raise NetcatTimeout ( ) return b'' except socket . error as exc : raise NetcatError ( 'Socket error: %r' % exc ) self . _settimeout ( self . _timeout ) ret = self . buf [ : cut_at ] self . buf = self . buf [ cut_at : ] self . _log_recv ( ret , True ) return ret | Receive until predicate returns a positive integer . The returned number is the size to return . |
19,359 | def recv_until ( self , s , max_size = None , timeout = 'default' ) : self . _print_recv_header ( '======== Receiving until {0}{timeout_text} ========' , timeout , repr ( s ) ) if max_size is None : max_size = 2 ** 62 def _predicate ( buf ) : try : return min ( buf . index ( s ) + len ( s ) , max_size ) except ValueError : return 0 if len ( buf ) < max_size else max_size return self . _recv_predicate ( _predicate , timeout ) | Recieve data from the socket until the given substring is observed . Data in the same datagram as the substring following the substring will not be returned and will be cached for future receives . |
19,360 | def recv_all ( self , timeout = 'default' ) : self . _print_recv_header ( '======== Receiving until close{timeout_text} ========' , timeout ) return self . _recv_predicate ( lambda s : 0 , timeout , raise_eof = False ) | Return all data recieved until connection closes . |
19,361 | def recv_exactly ( self , n , timeout = 'default' ) : self . _print_recv_header ( '======== Receiving until exactly {0}B{timeout_text} ========' , timeout , n ) return self . _recv_predicate ( lambda s : n if len ( s ) >= n else 0 , timeout ) | Recieve exactly n bytes |
19,362 | def send ( self , s ) : self . _print_header ( '======== Sending ({0}) ========' . format ( len ( s ) ) ) self . _log_send ( s ) out = len ( s ) while s : s = s [ self . _send ( s ) : ] return out | Sends all the given data to the socket . |
19,363 | def interact ( self , insock = sys . stdin , outsock = sys . stdout ) : self . _print_header ( '======== Beginning interactive session ========' ) if hasattr ( outsock , 'buffer' ) : outsock = outsock . buffer self . timed_out = False save_verbose = self . verbose self . verbose = 0 try : if self . buf : outsock . write ( self . buf ) outsock . flush ( ) self . buf = b'' while True : readable_socks = select ( self . sock , insock ) for readable in readable_socks : if readable is insock : data = os . read ( insock . fileno ( ) , 4096 ) self . send ( data ) if not data : raise NetcatError else : data = self . recv ( timeout = None ) outsock . write ( data ) outsock . flush ( ) if not data : raise NetcatError except KeyboardInterrupt : self . verbose = save_verbose self . _print_header ( '\n======== Connection interrupted! ========' ) raise except ( socket . error , NetcatError ) : self . verbose = save_verbose self . _print_header ( '\n======== Connection dropped! ========' ) finally : self . verbose = save_verbose | Connects the socket to the terminal for user interaction . Alternate input and output files may be specified . |
19,364 | def recv_line ( self , max_size = None , timeout = 'default' , ending = None ) : if ending is None : ending = self . LINE_ENDING return self . recv_until ( ending , max_size , timeout ) | Recieve until the next newline default \\ n . The newline string can be changed by changing nc . LINE_ENDING . The newline will be returned as part of the string . |
19,365 | def send_line ( self , line , ending = None ) : if ending is None : ending = self . LINE_ENDING return self . send ( line + ending ) | Write the string to the wire followed by a newline . The newline string can be changed by changing nc . LINE_ENDING . |
19,366 | def is_active ( self , timperiods ) : now = int ( time . time ( ) ) timperiod = timperiods [ self . modulation_period ] if not timperiod or timperiod . is_time_valid ( now ) : return True return False | Know if this result modulation is active now |
19,367 | def object ( self , o_type , o_name = None ) : o_found = self . _get_object ( o_type = o_type , o_name = o_name ) if not o_found : return { '_status' : u'ERR' , '_message' : u'Required %s not found.' % o_type } return o_found | Get an object from the scheduler . |
19,368 | def monitoring_problems ( self ) : if self . app . type != 'scheduler' : return { '_status' : u'ERR' , '_message' : u"This service is only available for a scheduler daemon" } res = self . identity ( ) res . update ( self . app . get_monitoring_problems ( ) ) return res | Get Alignak scheduler monitoring status |
19,369 | def _wait_new_conf ( self ) : self . app . sched . stop_scheduling ( ) super ( SchedulerInterface , self ) . _wait_new_conf ( ) | Ask the scheduler to drop its configuration and wait for a new one . |
19,370 | def _initial_broks ( self , broker_name ) : with self . app . conf_lock : logger . info ( "A new broker just connected : %s" , broker_name ) return self . app . sched . fill_initial_broks ( broker_name ) | Get initial_broks from the scheduler |
19,371 | def _broks ( self , broker_name ) : logger . debug ( "Getting broks for %s from the scheduler" , broker_name ) for broker_link in list ( self . app . brokers . values ( ) ) : if broker_name == broker_link . name : break else : logger . warning ( "Requesting broks for an unknown broker: %s" , broker_name ) return { } with self . app . broks_lock : res = self . app . get_broks ( broker_name ) return serialize ( res , True ) | Get the broks from a scheduler used by brokers |
19,372 | def _get_objects ( self , o_type ) : if o_type not in [ t for t in self . app . sched . pushed_conf . types_creations ] : return None try : _ , _ , strclss , _ , _ = self . app . sched . pushed_conf . types_creations [ o_type ] o_list = getattr ( self . app . sched , strclss ) except Exception : return None return o_list | Get an object list from the scheduler |
19,373 | def _get_object ( self , o_type , o_name = None ) : try : o_found = None o_list = self . _get_objects ( o_type ) if o_list : if o_name is None : return serialize ( o_list , True ) if o_list else None o_found = o_list . find_by_name ( o_name ) if not o_found : o_found = o_list [ o_name ] except Exception : return None return serialize ( o_found , True ) if o_found else None | Get an object from the scheduler |
19,374 | def is_a_module ( self , module_type ) : if hasattr ( self , 'type' ) : return module_type in self . type return module_type in self . module_types | Is the module of the required type? |
19,375 | def serialize ( self ) : res = super ( Module , self ) . serialize ( ) cls = self . __class__ for prop in self . __dict__ : if prop in cls . properties or prop in cls . running_properties or prop in [ 'properties' , 'my_daemon' ] : continue res [ prop ] = getattr ( self , prop ) return res | A module may have some properties that are not defined in the class properties list . Serializing a module is the same as serializing an Item but we also also include all the existing properties that are not defined in the properties or running_properties class list . |
19,376 | def linkify_s_by_plug ( self ) : for module in self : new_modules = [ ] for related in getattr ( module , 'modules' , [ ] ) : related = related . strip ( ) if not related : continue o_related = self . find_by_name ( related ) if o_related is not None : new_modules . append ( o_related . uuid ) else : self . add_error ( "the module '%s' for the module '%s' is unknown!" % ( related , module . get_name ( ) ) ) module . modules = new_modules | Link a module to some other modules |
19,377 | def get_start_of_day ( year , month , day ) : try : timestamp = time . mktime ( ( year , month , day , 00 , 00 , 00 , 0 , 0 , - 1 ) ) except ( OverflowError , ValueError ) : timestamp = 0.0 return int ( timestamp ) | Get the timestamp associated to the first second of a specific day |
19,378 | def get_end_of_day ( year , month , day ) : timestamp = time . mktime ( ( year , month , day , 23 , 59 , 59 , 0 , 0 , - 1 ) ) return int ( timestamp ) | Get the timestamp associated to the last second of a specific day |
19,379 | def get_sec_from_morning ( timestamp ) : t_lt = time . localtime ( timestamp ) return t_lt . tm_hour * 3600 + t_lt . tm_min * 60 + t_lt . tm_sec | Get the number of seconds elapsed since the beginning of the day deducted from the provided timestamp |
19,380 | def find_day_by_weekday_offset ( year , month , weekday , offset ) : cal = calendar . monthcalendar ( year , month ) if offset < 0 : offset = abs ( offset ) cal . reverse ( ) nb_found = 0 try : for i in range ( 0 , offset + 1 ) : if cal [ i ] [ weekday ] != 0 : nb_found += 1 if nb_found == offset : return cal [ i ] [ weekday ] return None except KeyError : return None | Get the day number based on a date and offset |
19,381 | def find_day_by_offset ( year , month , offset ) : ( _ , days_in_month ) = calendar . monthrange ( year , month ) if offset >= 0 : return min ( offset , days_in_month ) return max ( 1 , days_in_month + offset + 1 ) | Get the month day based on date and offset |
19,382 | def is_time_valid ( self , timestamp ) : sec_from_morning = get_sec_from_morning ( timestamp ) return ( self . is_valid and self . hstart * 3600 + self . mstart * 60 <= sec_from_morning <= self . hend * 3600 + self . mend * 60 ) | Check if time is valid for this Timerange |
19,383 | def is_time_valid ( self , timestamp ) : if self . is_time_day_valid ( timestamp ) : for timerange in self . timeranges : if timerange . is_time_valid ( timestamp ) : return True return False | Check if time is valid for one of the timerange . |
19,384 | def get_min_sec_from_morning ( self ) : mins = [ ] for timerange in self . timeranges : mins . append ( timerange . get_sec_from_morning ( ) ) return min ( mins ) | Get the first second from midnight where a timerange is effective |
19,385 | def is_time_day_valid ( self , timestamp ) : ( start_time , end_time ) = self . get_start_and_end_time ( timestamp ) return start_time <= timestamp <= end_time | Check if it is within start time and end time of the DateRange |
19,386 | def get_next_future_timerange_invalid ( self , timestamp ) : sec_from_morning = get_sec_from_morning ( timestamp ) ends = [ ] for timerange in self . timeranges : tr_end = timerange . hend * 3600 + timerange . mend * 60 if tr_end >= sec_from_morning : if tr_end == 86400 : tr_end = 86399 ends . append ( tr_end ) if ends != [ ] : return min ( ends ) return None | Get next invalid time for timeranges |
19,387 | def get_next_valid_day ( self , timestamp ) : if self . get_next_future_timerange_valid ( timestamp ) is None : ( start_time , _ ) = self . get_start_and_end_time ( get_day ( timestamp ) + 86400 ) else : ( start_time , _ ) = self . get_start_and_end_time ( timestamp ) if timestamp <= start_time : return get_day ( start_time ) if self . is_time_day_valid ( timestamp ) : return get_day ( timestamp ) return None | Get next valid day for timerange |
19,388 | def get_next_valid_time_from_t ( self , timestamp ) : if self . is_time_valid ( timestamp ) : return timestamp t_day = self . get_next_valid_day ( timestamp ) if t_day is None : return t_day if timestamp < t_day : sec_from_morning = self . get_next_future_timerange_valid ( t_day ) else : sec_from_morning = self . get_next_future_timerange_valid ( timestamp ) if sec_from_morning is not None : if t_day is not None and sec_from_morning is not None : return t_day + sec_from_morning timestamp = get_day ( timestamp ) + 86400 t_day2 = self . get_next_valid_day ( timestamp ) sec_from_morning = self . get_next_future_timerange_valid ( t_day2 ) if t_day2 is not None and sec_from_morning is not None : return t_day2 + sec_from_morning return None | Get next valid time for time range |
19,389 | def get_next_invalid_day ( self , timestamp ) : if self . is_time_day_invalid ( timestamp ) : return timestamp next_future_timerange_invalid = self . get_next_future_timerange_invalid ( timestamp ) if next_future_timerange_invalid is None : ( start_time , end_time ) = self . get_start_and_end_time ( get_day ( timestamp ) ) else : ( start_time , end_time ) = self . get_start_and_end_time ( timestamp ) if next_future_timerange_invalid is not None : if start_time <= timestamp <= end_time : return get_day ( timestamp ) if start_time >= timestamp : return get_day ( start_time ) else : return get_day ( end_time + 1 ) return None | Get next day where timerange is not active |
19,390 | def get_next_invalid_time_from_t ( self , timestamp ) : if not self . is_time_valid ( timestamp ) : return timestamp t_day = self . get_next_invalid_day ( timestamp ) if timestamp < t_day : sec_from_morning = self . get_next_future_timerange_invalid ( t_day ) else : sec_from_morning = self . get_next_future_timerange_invalid ( timestamp ) if t_day is not None and sec_from_morning is not None : return t_day + sec_from_morning + 1 if t_day is not None and sec_from_morning is None : return t_day timestamp = get_day ( timestamp ) + 86400 t_day2 = self . get_next_invalid_day ( timestamp ) sec_from_morning = self . get_next_future_timerange_invalid ( t_day2 ) if t_day2 is not None and sec_from_morning is not None : return t_day2 + sec_from_morning + 1 if t_day2 is not None and sec_from_morning is None : return t_day2 return None | Get next invalid time for time range |
19,391 | def get_start_and_end_time ( self , ref = None ) : return ( get_start_of_day ( self . syear , int ( self . smon ) , self . smday ) , get_end_of_day ( self . eyear , int ( self . emon ) , self . emday ) ) | Specific function to get start time and end time for CalendarDaterange |
19,392 | def get_start_and_end_time ( self , ref = None ) : now = time . localtime ( ref ) self . syear = now . tm_year self . month = now . tm_mon self . wday = now . tm_wday day_id = Daterange . get_weekday_id ( self . day ) today_morning = get_start_of_day ( now . tm_year , now . tm_mon , now . tm_mday ) tonight = get_end_of_day ( now . tm_year , now . tm_mon , now . tm_mday ) day_diff = ( day_id - now . tm_wday ) % 7 morning = datetime . fromtimestamp ( today_morning ) + timedelta ( days = day_diff ) night = datetime . fromtimestamp ( tonight ) + timedelta ( days = day_diff ) return ( int ( morning . strftime ( "%s" ) ) , int ( night . strftime ( "%s" ) ) ) | Specific function to get start time and end time for StandardDaterange |
19,393 | def get_start_and_end_time ( self , ref = None ) : now = time . localtime ( ref ) if self . syear == 0 : self . syear = now . tm_year day_start = find_day_by_weekday_offset ( self . syear , self . smon , self . swday , self . swday_offset ) start_time = get_start_of_day ( self . syear , self . smon , day_start ) if self . eyear == 0 : self . eyear = now . tm_year day_end = find_day_by_weekday_offset ( self . eyear , self . emon , self . ewday , self . ewday_offset ) end_time = get_end_of_day ( self . eyear , self . emon , day_end ) now_epoch = time . mktime ( now ) if start_time > end_time : if now_epoch > end_time : day_end = find_day_by_weekday_offset ( self . eyear + 1 , self . emon , self . ewday , self . ewday_offset ) end_time = get_end_of_day ( self . eyear + 1 , self . emon , day_end ) else : day_start = find_day_by_weekday_offset ( self . syear - 1 , self . smon , self . swday , self . swday_offset ) start_time = get_start_of_day ( self . syear - 1 , self . smon , day_start ) else : if now_epoch > end_time : day_start = find_day_by_weekday_offset ( self . syear + 1 , self . smon , self . swday , self . swday_offset ) start_time = get_start_of_day ( self . syear + 1 , self . smon , day_start ) day_end = find_day_by_weekday_offset ( self . eyear + 1 , self . emon , self . ewday , self . ewday_offset ) end_time = get_end_of_day ( self . eyear + 1 , self . emon , day_end ) return ( start_time , end_time ) | Specific function to get start time and end time for MonthWeekDayDaterange |
19,394 | def get_start_and_end_time ( self , ref = None ) : now = time . localtime ( ref ) if self . syear == 0 : self . syear = now . tm_year day_start = find_day_by_offset ( self . syear , self . smon , self . smday ) start_time = get_start_of_day ( self . syear , self . smon , day_start ) if self . eyear == 0 : self . eyear = now . tm_year day_end = find_day_by_offset ( self . eyear , self . emon , self . emday ) end_time = get_end_of_day ( self . eyear , self . emon , day_end ) now_epoch = time . mktime ( now ) if start_time > end_time : if now_epoch > end_time : day_end = find_day_by_offset ( self . eyear + 1 , self . emon , self . emday ) end_time = get_end_of_day ( self . eyear + 1 , self . emon , day_end ) else : day_start = find_day_by_offset ( self . syear - 1 , self . smon , self . emday ) start_time = get_start_of_day ( self . syear - 1 , self . smon , day_start ) else : if now_epoch > end_time : day_start = find_day_by_offset ( self . syear + 1 , self . smon , self . smday ) start_time = get_start_of_day ( self . syear + 1 , self . smon , day_start ) day_end = find_day_by_offset ( self . eyear + 1 , self . emon , self . emday ) end_time = get_end_of_day ( self . eyear + 1 , self . emon , day_end ) return ( start_time , end_time ) | Specific function to get start time and end time for MonthDateDaterange |
19,395 | def get_start_and_end_time ( self , ref = None ) : now = time . localtime ( ref ) if self . syear == 0 : self . syear = now . tm_year month_start_id = now . tm_mon day_start = find_day_by_weekday_offset ( self . syear , month_start_id , self . swday , self . swday_offset ) start_time = get_start_of_day ( self . syear , month_start_id , day_start ) if self . eyear == 0 : self . eyear = now . tm_year month_end_id = now . tm_mon day_end = find_day_by_weekday_offset ( self . eyear , month_end_id , self . ewday , self . ewday_offset ) end_time = get_end_of_day ( self . eyear , month_end_id , day_end ) if start_time > end_time : month_end_id += 1 if month_end_id > 12 : month_end_id = 1 self . eyear += 1 day_end = find_day_by_weekday_offset ( self . eyear , month_end_id , self . ewday , self . ewday_offset ) end_time = get_end_of_day ( self . eyear , month_end_id , day_end ) now_epoch = time . mktime ( now ) if end_time < now_epoch : month_end_id += 1 month_start_id += 1 if month_end_id > 12 : month_end_id = 1 self . eyear += 1 if month_start_id > 12 : month_start_id = 1 self . syear += 1 day_start = find_day_by_weekday_offset ( self . syear , month_start_id , self . swday , self . swday_offset ) start_time = get_start_of_day ( self . syear , month_start_id , day_start ) day_end = find_day_by_weekday_offset ( self . eyear , month_end_id , self . ewday , self . ewday_offset ) end_time = get_end_of_day ( self . eyear , month_end_id , day_end ) return ( start_time , end_time ) | Specific function to get start time and end time for WeekDayDaterange |
19,396 | def get_start_and_end_time ( self , ref = None ) : now = time . localtime ( ref ) if self . syear == 0 : self . syear = now . tm_year month_start_id = now . tm_mon day_start = find_day_by_offset ( self . syear , month_start_id , self . smday ) start_time = get_start_of_day ( self . syear , month_start_id , day_start ) if self . eyear == 0 : self . eyear = now . tm_year month_end_id = now . tm_mon day_end = find_day_by_offset ( self . eyear , month_end_id , self . emday ) end_time = get_end_of_day ( self . eyear , month_end_id , day_end ) now_epoch = time . mktime ( now ) if start_time > end_time : month_start_id -= 1 if month_start_id < 1 : month_start_id = 12 self . syear -= 1 day_start = find_day_by_offset ( self . syear , month_start_id , self . smday ) start_time = get_start_of_day ( self . syear , month_start_id , day_start ) if end_time < now_epoch : month_end_id += 1 month_start_id += 1 if month_end_id > 12 : month_end_id = 1 self . eyear += 1 if month_start_id > 12 : month_start_id = 1 self . syear += 1 day_start = find_day_by_offset ( self . syear , month_start_id , self . smday ) start_time = get_start_of_day ( self . syear , month_start_id , day_start ) day_end = find_day_by_offset ( self . eyear , month_end_id , self . emday ) end_time = get_end_of_day ( self . eyear , month_end_id , day_end ) return ( start_time , end_time ) | Specific function to get start time and end time for MonthDayDaterange |
19,397 | def get_unknown_check_result_brok ( cmd_line ) : match = re . match ( r'^\[([0-9]{10})] PROCESS_(SERVICE)_CHECK_RESULT;' r'([^\;]*);([^\;]*);([^\;]*);([^\|]*)(?:\|(.*))?' , cmd_line ) if not match : match = re . match ( r'^\[([0-9]{10})] PROCESS_(HOST)_CHECK_RESULT;' r'([^\;]*);([^\;]*);([^\|]*)(?:\|(.*))?' , cmd_line ) if not match : return None data = { 'time_stamp' : int ( match . group ( 1 ) ) , 'host_name' : match . group ( 3 ) , } if match . group ( 2 ) == 'SERVICE' : data [ 'service_description' ] = match . group ( 4 ) data [ 'return_code' ] = match . group ( 5 ) data [ 'output' ] = match . group ( 6 ) data [ 'perf_data' ] = match . group ( 7 ) else : data [ 'return_code' ] = match . group ( 4 ) data [ 'output' ] = match . group ( 5 ) data [ 'perf_data' ] = match . group ( 6 ) return Brok ( { 'type' : 'unknown_%s_check_result' % match . group ( 2 ) . lower ( ) , 'data' : data } ) | Create unknown check result brok and fill it with command data |
19,398 | def get_name ( self ) : dependent_host_name = 'unknown' if getattr ( self , 'dependent_host_name' , None ) : dependent_host_name = getattr ( getattr ( self , 'dependent_host_name' ) , 'host_name' , 'unknown' ) host_name = 'unknown' if getattr ( self , 'host_name' , None ) : host_name = getattr ( getattr ( self , 'host_name' ) , 'host_name' , 'unknown' ) return dependent_host_name + '/' + host_name | Get name based on dependent_host_name and host_name attributes Each attribute is substituted by unknown if attribute does not exist |
19,399 | def linkify_hd_by_h ( self , hosts ) : for hostdep in self : try : h_name = hostdep . host_name dh_name = hostdep . dependent_host_name host = hosts . find_by_name ( h_name ) if host is None : err = "Error: the host dependency got a bad host_name definition '%s'" % h_name hostdep . add_error ( err ) dephost = hosts . find_by_name ( dh_name ) if dephost is None : err = "Error: the host dependency got " "a bad dependent_host_name definition '%s'" % dh_name hostdep . add_error ( err ) if host : hostdep . host_name = host . uuid if dephost : hostdep . dependent_host_name = dephost . uuid except AttributeError as exp : err = "Error: the host dependency miss a property '%s'" % exp hostdep . add_error ( err ) | Replace dependent_host_name and host_name in host dependency by the real object |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.