idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
19,200 | def set_initial_status ( self , response ) : self . _raise_if_bad_http_status_and_method ( response ) if self . _is_empty ( response ) : self . resource = None else : try : self . resource = self . _deserialize ( response ) except DeserializationError : self . resource = None self . set_async_url_if_present ( response ) if response . status_code in { 200 , 201 , 202 , 204 } : if self . async_url or self . location_url or response . status_code == 202 : self . status = 'InProgress' elif response . status_code == 201 : status = self . _get_provisioning_state ( response ) self . status = status or 'InProgress' elif response . status_code == 200 : status = self . _get_provisioning_state ( response ) self . status = status or 'Succeeded' elif response . status_code == 204 : self . status = 'Succeeded' self . resource = None else : raise OperationFailed ( "Invalid status found" ) return raise OperationFailed ( "Operation failed or cancelled" ) | Process first response after initiating long running operation and set self . status attribute . | 259 | 15 |
19,201 | def parse_resource ( self , response ) : self . _raise_if_bad_http_status_and_method ( response ) if not self . _is_empty ( response ) : self . resource = self . _deserialize ( response ) else : self . resource = None | Assuming this response is a resource use the deserialization callback to parse it . If body is empty assuming no resource to return . | 61 | 26 |
19,202 | def get_status_from_async ( self , response ) : self . _raise_if_bad_http_status_and_method ( response ) if self . _is_empty ( response ) : raise BadResponse ( 'The response from long running operation ' 'does not contain a body.' ) self . status = self . _get_async_status ( response ) if not self . status : raise BadResponse ( "No status found in body" ) # Status can contains information, see ARM spec: # https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/Addendum.md#operation-resource-format # "properties": { # /\* The resource provider can choose the values here, but it should only be # returned on a successful operation (status being "Succeeded"). \*/ #}, # So try to parse it try : self . resource = self . _deserialize ( response ) except Exception : self . resource = None | Process the latest status update retrieved from a azure - asyncoperation header . | 220 | 15 |
19,203 | def initialize ( self , client , initial_response , deserialization_callback ) : self . _client = client self . _response = initial_response self . _operation = LongRunningOperation ( initial_response , deserialization_callback , self . _lro_options ) try : self . _operation . set_initial_status ( initial_response ) except BadStatus : self . _operation . status = 'Failed' raise CloudError ( initial_response ) except BadResponse as err : self . _operation . status = 'Failed' raise CloudError ( initial_response , str ( err ) ) except OperationFailed : raise CloudError ( initial_response ) | Set the initial status of this LRO . | 142 | 9 |
19,204 | def worker ( ) : import torch import torch . distributed as dist from torch . multiprocessing import Process import numpy as np print ( "Initializing distributed pytorch" ) os . environ [ 'MASTER_ADDR' ] = str ( args . master_addr ) os . environ [ 'MASTER_PORT' ] = str ( args . master_port ) # Use TCP backend. Gloo needs nightly, where it currently fails with # dist.init_process_group('gloo', rank=args.rank, # AttributeError: module 'torch.distributed' has no attribute 'init_process_group' dist . init_process_group ( 'tcp' , rank = args . rank , world_size = args . size ) tensor = torch . ones ( args . size_mb * 250 * 1000 ) * ( args . rank + 1 ) time_list = [ ] outfile = 'out' if args . rank == 0 else '/dev/null' log = util . FileLogger ( outfile ) for i in range ( args . iters ) : # print('before: rank ', args.rank, ' has data ', tensor[0]) start_time = time . perf_counter ( ) if args . rank == 0 : dist . send ( tensor = tensor , dst = 1 ) else : dist . recv ( tensor = tensor , src = 0 ) elapsed_time_ms = ( time . perf_counter ( ) - start_time ) * 1000 time_list . append ( elapsed_time_ms ) # print('after: rank ', args.rank, ' has data ', tensor[0]) rate = args . size_mb / ( elapsed_time_ms / 1000 ) log ( '%03d/%d added %d MBs in %.1f ms: %.2f MB/second' % ( i , args . iters , args . size_mb , elapsed_time_ms , rate ) ) min = np . min ( time_list ) median = np . median ( time_list ) log ( f"min: {min:8.2f}, median: {median:8.2f}, mean: {np.mean(time_list):8.2f}" ) | Initialize the distributed environment . | 489 | 6 |
19,205 | def make_job ( name : str = '' , run_name : str = '' , num_tasks : int = 0 , install_script : str = '' , * * kwargs ) -> backend . Job : return _backend . make_job ( name = name , run_name = run_name , num_tasks = num_tasks , install_script = install_script , * * kwargs ) | Create a job using current backend . Blocks until all tasks are up and initialized . | 92 | 16 |
19,206 | def make_task ( name = '' , run_name = '' , * * kwargs ) -> Task : ncluster_globals . task_launched = True name = ncluster_globals . auto_assign_task_name_if_needed ( name ) # tmux can't use . for session names tmux_session = name . replace ( '.' , '=' ) tmux_window_id = 0 util . log ( f'killing session {tmux_session}' ) if not util . is_set ( "NCLUSTER_NOKILL_TMUX" ) : os . system ( f'tmux kill-session -t {tmux_session}' ) os . system ( f'tmux new-session -s {tmux_session} -n {tmux_window_id} -d' ) task = Task ( name , tmux_session = tmux_session , # propagate optional args run_name = run_name , * * kwargs ) ncluster_globals . register_task ( task , run_name ) return task | Create task also create dummy run if not specified . | 248 | 10 |
19,207 | def _run_raw ( self , cmd , ignore_errors = False ) : # TODO: capture stdout/stderr for feature parity with aws_backend result = os . system ( cmd ) if result != 0 : if ignore_errors : self . log ( f"command ({cmd}) failed." ) assert False , "_run_raw failed" | Runs command directly skipping tmux interface | 77 | 9 |
19,208 | def upload ( self , local_fn , remote_fn = None , dont_overwrite = False ) : # support wildcard through glob if '*' in local_fn : for local_subfn in glob . glob ( local_fn ) : self . upload ( local_subfn ) return if remote_fn is None : remote_fn = os . path . basename ( local_fn ) if dont_overwrite and self . exists ( remote_fn ) : self . log ( "Remote file %s exists, skipping" % ( remote_fn , ) ) return if not remote_fn . startswith ( '/' ) : remote_fn = self . taskdir + '/' + remote_fn remote_fn = remote_fn . replace ( '~' , self . homedir ) self . log ( 'uploading ' + local_fn + ' to ' + remote_fn ) local_fn = os . path . abspath ( local_fn ) self . _run_raw ( "cp -R %s %s" % ( local_fn , remote_fn ) ) | Uploads file to remote instance . If location not specified dumps it into default directory . Creates missing directories in path name . | 234 | 25 |
19,209 | def logdir ( self ) : run_name = ncluster_globals . get_run_for_task ( self ) logdir = ncluster_globals . get_logdir ( run_name ) if logdir : return logdir # create logdir. Only single task in a group creates the logdir if ncluster_globals . is_chief ( self , run_name ) : chief = self else : chief = ncluster_globals . get_chief ( run_name ) chief . setup_logdir ( ) return ncluster_globals . get_logdir ( run_name ) | Returns logging directory creating one if necessary . See Logdir section of design doc on naming convention . | 140 | 19 |
19,210 | 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 . | 43 | 14 |
19,211 | def _run_raw ( self , * args , * * kwargs ) : for job in self . jobs : job . _run_raw ( * args , * * kwargs ) | _run_raw on every job in the run . | 41 | 11 |
19,212 | 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 ) # check that local pem file exists and is readable 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 . | 341 | 17 |
19,213 | 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 . | 134 | 22 |
19,214 | 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 . | 37 | 26 |
19,215 | 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 . | 138 | 26 |
19,216 | 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 | 47 | 9 |
19,217 | 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 . | 89 | 14 |
19,218 | 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 # to avoid exceeding AWS 127 char limit return get_prefix ( ) + '-' + username | Returns current keypair name . | 69 | 6 |
19,219 | 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 | 73 | 10 |
19,220 | 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 ( ) # look for an existing instance matching job, ignore instances launched # by different user or under different resource name 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 . | 379 | 24 |
19,221 | 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 : # occasionally re-obtain public ip, machine could've gotten restarted 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 | 240 | 7 |
19,222 | 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 . | 212 | 9 |
19,223 | def extract_attr_for_match ( items , * * kwargs ) : # find the value of attribute to return 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 | 235 | 27 |
19,224 | 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 | 140 | 16 |
19,225 | 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 | 40 | 7 |
19,226 | 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 # no Exception means group name was found except Exception : print ( "Creating placement_group group: " + name ) try : _response = client . create_placement_group ( GroupName = name , Strategy = 'cluster' ) except Exception : # because of race can get InvalidPlacementGroup.Duplicate 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 . | 281 | 29 |
19,227 | 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 | 86 | 11 |
19,228 | 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 . | 68 | 12 |
19,229 | 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 ( ) : """Check if gateway, keypair, vpc exist.""" 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 : # this locking is approximate, still possible for threads to slip through 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 | 536 | 10 |
19,230 | 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 # setting from ~/.aws # zone is set, set region from zone if current_zone and not current_region : current_region = current_zone [ : - 1 ] os . environ [ 'AWS_DEFAULT_REGION' ] = current_region # neither zone nor region not set, use default setting for region # if default is not set, use NCLUSTER_DEFAULT_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 # zone not set, use first zone of the region # if not current_zone: # current_zone = current_region + 'a' # os.environ['NCLUSTER_ZONE'] = current_zone log ( f"Using account {u.get_account_number()}, region {current_region}, " f"zone {current_zone}" ) | Sets up AWS environment from NCLUSTER environment variables | 419 | 12 |
19,231 | 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 empty wait a bit to allow for race condition 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 . | 369 | 8 |
19,232 | 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 ( '#' ) : # ignore empty/commented out lines 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" # modify command to dump shell success status into file self . file_write ( self . _cmd_fn , cmd + '\n' ) # modified_cmd = f'{cmd} > {out_fn} 2>&1; echo $? > {status_fn}' # https://stackoverflow.com/a/692407/419116 # $cmd > >(tee -a fn) 2> >(tee -a fn >&2) 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 empty wait a bit to allow for race condition 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 | 869 | 19 |
19,233 | def upload ( self , local_fn : str , remote_fn : str = '' , dont_overwrite : bool = False ) -> None : # support wildcard through glob if '*' in local_fn : for local_subfn in glob . glob ( local_fn ) : self . upload ( local_subfn ) return if '#' in local_fn : # hashes also give problems from shell commands 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_ ) : """Makes remote file execute for locally executable files""" mode = oct ( os . stat ( local_fn_ ) [ stat . ST_MODE ] ) [ - 3 : ] if '7' in mode : self . log ( f"Making {remote_fn_} executable with mode {mode}" ) # use raw run, in case tmux is unavailable self . _run_raw ( f"chmod {mode} {remote_fn_}" ) # augmented SFTP client that can transfer directories, from # https://stackoverflow.com/a/19974994/419116 def _put_dir ( source , target ) : """ Uploads the contents of the source directory to the target path.""" def _safe_mkdir ( path , mode = 511 , ignore_existing = True ) : """ Augments mkdir by adding an option to not fail if the folder exists asdf asdf asdf as""" 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 , ) # this crashes with IOError when upload failed 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 . | 859 | 32 |
19,234 | 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 . | 91 | 15 |
19,235 | 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 . | 45 | 9 |
19,236 | 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 . | 47 | 9 |
19,237 | 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 . | 46 | 9 |
19,238 | 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 . | 74 | 15 |
19,239 | def random_id ( k = 5 ) : # https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python return '' . join ( random . choices ( string . ascii_lowercase + string . digits , k = k ) ) | Random id to use for AWS identifiers . | 75 | 8 |
19,240 | 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 | 83 | 11 |
19,241 | def is_bash_builtin ( cmd ) : # from compgen -b 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 | 318 | 10 |
19,242 | 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 | 59 | 9 |
19,243 | 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 | 66 | 13 |
19,244 | 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 . | 191 | 9 |
19,245 | 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 . | 40 | 12 |
19,246 | 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 . | 50 | 14 |
19,247 | def get_child_fn ( attrs , names , bases ) : def call_method ( obj , method ) : """Calls a method as either a class method or an instance method. """ # The __get__ method takes an instance and an owner which changes # depending on the calling object. If the calling object is a class, # the instance is None and the owner will be the object itself. If the # calling object is an instance, the instance will be the calling object # and the owner will be its class. For more info on the __get__ method, # see http://docs.python.org/2/reference/datamodel.html#object.__get__. if isinstance ( obj , type ) : instance = None owner = obj else : instance = obj owner = obj . __class__ method . __get__ ( instance , owner ) ( ) # Create a default function that calls the default method on each parent 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 # Get all of the functions in the child class that match the list of names fns = [ ( name , attrs [ name ] ) for name in names if name in attrs ] # Raise an error if more than one setup/teardown method is found if len ( fns ) > 1 : raise RuntimeError ( "Cannot have more than one setup or teardown method per context (class or test)." ) # If one setup/teardown function was found, return it elif len ( fns ) == 1 : name , fn = fns [ 0 ] def child_fn ( obj ) : call_method ( obj , fn ) child_fn . __name__ = name return child_fn # Otherwise, return the default function else : return default_fn | Returns a function from the child class that matches one of the names . | 424 | 14 |
19,248 | def print_msg ( msg , header , file = sys . stdout ) : DEFAULT_MSG_BLOCK_WIDTH = 60 # Calculate the length of the boarder on each side of the header and the # total length of the bottom boarder side_boarder_length = ( DEFAULT_MSG_BLOCK_WIDTH - ( len ( header ) + 2 ) ) // 2 msg_block_width = side_boarder_length * 2 + ( len ( header ) + 2 ) # Create the top and bottom boarders 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 ) : """Returns a string padded and centered by the given 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 the full message 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 | 494 | 9 |
19,249 | def can_persist_fixtures ( ) : # If we're running python 2.7 or greater, we're fine if sys . hexversion >= 0x02070000 : return True # Otherwise, nose and py.test support the setUpClass and tearDownClass # methods, so if we're using either of those, go ahead and run the tests 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 . | 118 | 12 |
19,250 | 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 | 73 | 8 |
19,251 | 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 | 75 | 8 |
19,252 | def authenticate ( self , username = None , password = None , actions = None , response = None , authorization = None ) : # pylint: disable=too-many-arguments,too-many-locals 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 # pylint: disable=no-member 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 . | 573 | 20 |
19,253 | 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 . | 70 | 7 |
19,254 | 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 ) : # pylint: disable=too-few-public-methods 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 . | 194 | 13 |
19,255 | 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 . | 43 | 16 |
19,256 | 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 . | 81 | 14 |
19,257 | def get_alias ( self , alias = None , manifest = None , verify = True , sizes = False , dcd = None ) : # pylint: disable=too-many-arguments return self . _get_alias ( alias , manifest , verify , sizes , dcd , False ) | Get the blob hashes assigned to an alias . | 63 | 9 |
19,258 | def _get_dcd ( self , alias ) : # https://docs.docker.com/registry/spec/api/#deleting-an-image # Note When deleting a manifest from a registry version 2.3 or later, # the following header must be used when HEAD or GET-ing the manifest # to obtain the correct digest to delete: # Accept: application/vnd.docker.distribution.manifest.v2+json 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 . | 153 | 12 |
19,259 | 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 | 79 | 4 |
19,260 | def bigquery_data_type ( self ) : # BigQuery data type = {source_database: [data type, ...], ...} 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 | 651 | 7 |
19,261 | 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 : # no or one dimensional array data type type = self . bigquery_legacy_data_type else : # multiple dimensional array data type 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 | 305 | 7 |
19,262 | 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 : # no array data type type = col . bigquery_standard_data_type not_null = " NOT NULL" if col . not_null else "" else : # one or multiple dimensional array data type 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 ( """\ #standardSQL CREATE TABLE `project.{dataset}.{table}` ( {colmns_define} )""" ) . format ( dataset = dataset , table = self . get_name ( name_case ) , colmns_define = ",\n " . join ( cols_defs ) , ) | Generate BigQuery CREATE TABLE statements | 390 | 8 |
19,263 | 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 ) # print(ret.dump()) 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" : # add 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" : # set column 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 . | 420 | 6 |
19,264 | def launch ( program , sock , stderr = True , cwd = None , env = None ) : if stderr is True : err = sock # redirect to socket elif stderr is False : err = open ( os . devnull , 'wb' ) # hide elif stderr is None : err = None # redirect to console 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 . | 139 | 23 |
19,265 | def respond ( self , packet , peer , flags = 0 ) : self . sock . sendto ( packet , flags , peer ) | Send a message back to a peer . | 27 | 8 |
19,266 | 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 . | 41 | 16 |
19,267 | 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 . | 45 | 16 |
19,268 | 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 . | 301 | 18 |
19,269 | 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 . | 134 | 40 |
19,270 | 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 . | 66 | 9 |
19,271 | 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 | 77 | 5 |
19,272 | 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 . | 66 | 10 |
19,273 | def interact ( self , insock = sys . stdin , outsock = sys . stdout ) : self . _print_header ( '======== Beginning interactive session ========' ) if hasattr ( outsock , 'buffer' ) : outsock = outsock . buffer # pylint: disable=no-member 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 . | 294 | 20 |
19,274 | 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 . | 54 | 40 |
19,275 | 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 . | 36 | 29 |
19,276 | 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 | 56 | 8 |
19,277 | 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 . | 84 | 8 |
19,278 | 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 | 81 | 8 |
19,279 | def _wait_new_conf ( self ) : # Stop the scheduling loop self . app . sched . stop_scheduling ( ) super ( SchedulerInterface , self ) . _wait_new_conf ( ) | Ask the scheduler to drop its configuration and wait for a new one . | 46 | 15 |
19,280 | 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 | 60 | 9 |
19,281 | 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 { } # Now get the broks for this specific broker 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 | 133 | 11 |
19,282 | 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 : # pylint: disable=broad-except return None return o_list | Get an object list from the scheduler | 111 | 8 |
19,283 | 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 # We expected a name... o_found = o_list . find_by_name ( o_name ) if not o_found : # ... but perharps we got an object uuid o_found = o_list [ o_name ] except Exception : # pylint: disable=broad-except return None return serialize ( o_found , True ) if o_found else None | Get an object from the scheduler | 154 | 7 |
19,284 | 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? | 43 | 8 |
19,285 | 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 . | 84 | 51 |
19,286 | 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 | 132 | 7 |
19,287 | def get_start_of_day ( year , month , day ) : # DST is not known in the provided date try : timestamp = time . mktime ( ( year , month , day , 00 , 00 , 00 , 0 , 0 , - 1 ) ) except ( OverflowError , ValueError ) : # Windows mktime sometimes crashes on (1970, 1, 1, ...) timestamp = 0.0 return int ( timestamp ) | Get the timestamp associated to the first second of a specific day | 92 | 12 |
19,288 | def get_end_of_day ( year , month , day ) : # DST is not known in the provided date 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 | 59 | 12 |
19,289 | 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 | 55 | 17 |
19,290 | def find_day_by_weekday_offset ( year , month , weekday , offset ) : # thanks calendar :) cal = calendar . monthcalendar ( year , month ) # If we ask for a -1 day, just reverse cal if offset < 0 : offset = abs ( offset ) cal . reverse ( ) # ok go for it nb_found = 0 try : for i in range ( 0 , offset + 1 ) : # in cal 0 mean "there are no day here :)" 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 | 145 | 10 |
19,291 | 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 | 66 | 9 |
19,292 | 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 | 71 | 10 |
19,293 | 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 . | 52 | 12 |
19,294 | 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 | 49 | 12 |
19,295 | 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 | 48 | 14 |
19,296 | 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 : # Remove the last second of the day for 00->24h" if tr_end == 86400 : tr_end = 86399 ends . append ( tr_end ) if ends != [ ] : return min ( ends ) return None | Get next invalid time for timeranges | 128 | 7 |
19,297 | def get_next_valid_day ( self , timestamp ) : if self . get_next_future_timerange_valid ( timestamp ) is None : # this day is finish, we check for next period ( 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 | 138 | 7 |
19,298 | def get_next_valid_time_from_t ( self , timestamp ) : if self . is_time_valid ( timestamp ) : return timestamp # First we search for the day of t t_day = self . get_next_valid_day ( timestamp ) if t_day is None : return t_day # We search for the min of all tr.start > sec_from_morning # if it's the next day, use a start of the day search for timerange if timestamp < t_day : sec_from_morning = self . get_next_future_timerange_valid ( t_day ) else : # it is in this day, so look from t (can be in the evening or so) 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 # Then we search for the next day of t # The sec will be the min of the day 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 # I did not found any valid time return None | Get next valid time for time range | 325 | 7 |
19,299 | def get_next_invalid_day ( self , timestamp ) : # pylint: disable=no-else-return if self . is_time_day_invalid ( timestamp ) : return timestamp next_future_timerange_invalid = self . get_next_future_timerange_invalid ( timestamp ) # If today there is no more unavailable timerange, search the next day if next_future_timerange_invalid is None : # this day is finish, we check for next period ( 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 ) # (start_time, end_time) = self.get_start_and_end_time(t) # The next invalid day can be t day if there a possible # invalid time range (timerange is not 00->24 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 : # Else, there is no possibility than in our start_time<->end_time we got # any invalid time (full period out). So it's end_time+1 sec (tomorrow of end_time) return get_day ( end_time + 1 ) return None | Get next day where timerange is not active | 323 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.