idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
27,800 | def _gap_progenitor_setup ( self ) : self . _gap_progenitor = self . _progenitor ( ) . flip ( ) # new orbit, flip velocities # Make sure we do not use physical coordinates self . _gap_progenitor . turn_physical_off ( ) # Now integrate backward in time until tdisrupt ts = numpy . linspace ( 0. , self . _tdisrupt , 1001 ) self . _gap_progenitor . integrate ( ts , self . _pot ) # Flip its velocities, should really write a function for this self . _gap_progenitor . _orb . orbit [ : , 1 ] = - self . _gap_progenitor . _orb . orbit [ : , 1 ] self . _gap_progenitor . _orb . orbit [ : , 2 ] = - self . _gap_progenitor . _orb . orbit [ : , 2 ] self . _gap_progenitor . _orb . orbit [ : , 4 ] = - self . _gap_progenitor . _orb . orbit [ : , 4 ] return None | Setup an Orbit instance that s the progenitor integrated backwards | 247 | 12 |
27,801 | def _sample_aAt ( self , n ) : # Use streamdf's _sample_aAt to generate unperturbed frequencies, # angles Om , angle , dt = super ( streamgapdf , self ) . _sample_aAt ( n ) # Now rewind angles by timpact, apply the kicks, and run forward again dangle_at_impact = angle - numpy . tile ( self . _progenitor_angle . T , ( n , 1 ) ) . T - ( Om - numpy . tile ( self . _progenitor_Omega . T , ( n , 1 ) ) . T ) * self . _timpact dangle_par_at_impact = numpy . dot ( dangle_at_impact . T , self . _dsigomeanProgDirection ) * self . _gap_sigMeanSign # Calculate and apply kicks (points not yet released have zero kick) dOr = self . _kick_interpdOr ( dangle_par_at_impact ) dOp = self . _kick_interpdOp ( dangle_par_at_impact ) dOz = self . _kick_interpdOz ( dangle_par_at_impact ) Om [ 0 , : ] += dOr Om [ 1 , : ] += dOp Om [ 2 , : ] += dOz angle [ 0 , : ] += self . _kick_interpdar ( dangle_par_at_impact ) + dOr * self . _timpact angle [ 1 , : ] += self . _kick_interpdap ( dangle_par_at_impact ) + dOp * self . _timpact angle [ 2 , : ] += self . _kick_interpdaz ( dangle_par_at_impact ) + dOz * self . _timpact return ( Om , angle , dt ) | Sampling frequencies angles and times part of sampling for stream with gap | 408 | 13 |
27,802 | def worker ( f , ii , chunk , out_q , err_q , lock ) : vals = [ ] # iterate over slice for val in chunk : try : result = f ( val ) except Exception as e : err_q . put ( e ) return vals . append ( result ) # output the result and task ID to output queue out_q . put ( ( ii , vals ) ) | A worker function that maps an input function over a slice of the input iterable . | 87 | 17 |
27,803 | def run_tasks ( procs , err_q , out_q , num ) : # function to terminate processes that are still running. die = ( lambda vals : [ val . terminate ( ) for val in vals if val . exitcode is None ] ) try : for proc in procs : proc . start ( ) for proc in procs : proc . join ( ) except Exception as e : # kill all slave processes on ctrl-C try : die ( procs ) finally : raise e if not err_q . empty ( ) : # kill all on any exception from any one slave try : die ( procs ) finally : raise err_q . get ( ) # Processes finish in arbitrary order. Process IDs double # as index in the resultant array. results = [ None ] * num while not out_q . empty ( ) : idx , result = out_q . get ( ) results [ idx ] = result # Remove extra dimension added by array_split return list ( numpy . concatenate ( results ) ) | A function that executes populated processes and processes the resultant array . Checks error queue for any exceptions . | 221 | 19 |
27,804 | def parallel_map ( function , sequence , numcores = None ) : if not callable ( function ) : raise TypeError ( "input function '%s' is not callable" % repr ( function ) ) if not numpy . iterable ( sequence ) : raise TypeError ( "input '%s' is not iterable" % repr ( sequence ) ) size = len ( sequence ) if not _multi or size == 1 : return map ( function , sequence ) if numcores is None : numcores = _ncpus if platform . system ( ) == 'Windows' : # JB: don't think this works on Win return list ( map ( function , sequence ) ) # Returns a started SyncManager object which can be used for sharing # objects between processes. The returned manager object corresponds # to a spawned child process and has methods which will create shared # objects and return corresponding proxies. manager = multiprocessing . Manager ( ) # Create FIFO queue and lock shared objects and return proxies to them. # The managers handles a server process that manages shared objects that # each slave process has access to. Bottom line -- thread-safe. out_q = manager . Queue ( ) err_q = manager . Queue ( ) lock = manager . Lock ( ) # if sequence is less than numcores, only use len sequence number of # processes if size < numcores : numcores = size # group sequence into numcores-worth of chunks sequence = numpy . array_split ( sequence , numcores ) procs = [ multiprocessing . Process ( target = worker , args = ( function , ii , chunk , out_q , err_q , lock ) ) for ii , chunk in enumerate ( sequence ) ] return run_tasks ( procs , err_q , out_q , numcores ) | A parallelized version of the native Python map function that utilizes the Python multiprocessing module to divide and conquer sequence . | 393 | 25 |
27,805 | def _u0Eq ( logu , delta , pot , E , Lz22 ) : u = numpy . exp ( logu ) sinh2u = numpy . sinh ( u ) ** 2. cosh2u = numpy . cosh ( u ) ** 2. dU = cosh2u * actionAngleStaeckel . potentialStaeckel ( u , numpy . pi / 2. , pot , delta ) return - ( E * sinh2u - dU - Lz22 / delta ** 2. / sinh2u ) | The equation that needs to be minimized to find u0 | 126 | 11 |
27,806 | def _JrSphericalIntegrand ( r , E , L , pot ) : return nu . sqrt ( 2. * ( E - potentialAxi ( r , pot ) ) - L ** 2. / r ** 2. ) | The J_r integrand | 49 | 6 |
27,807 | def rot ( self , t = 0. , transposed = False ) : rotmat = np . array ( [ [ np . cos ( self . _pa + self . _omegab * t ) , np . sin ( self . _pa + self . _omegab * t ) ] , [ - np . sin ( self . _pa + self . _omegab * t ) , np . cos ( self . _pa + self . _omegab * t ) ] ] ) if transposed : return rotmat . T else : return rotmat | 2D Rotation matrix for non - zero pa or pattern speed to goto the aligned coordinates | 120 | 18 |
27,808 | def _JzIntegrand ( z , Ez , pot ) : return nu . sqrt ( 2. * ( Ez - potentialVertical ( z , pot ) ) ) | The J_z integrand | 36 | 6 |
27,809 | def quoted ( s ) : # strip any existing quotes s = s . strip ( u'"' ) # don't add quotes for minus or leading space if s [ 0 ] in ( u'-' , u' ' ) : return s if u' ' in s or u'/' in s : return u'"%s"' % s else : return s | quotes a string if necessary . | 74 | 7 |
27,810 | def install ( path , remove = False , prefix = sys . prefix , recursing = False ) : # this sys.prefix is intentional. We want to reflect the state of the root installation. if sys . platform == 'win32' and not exists ( join ( sys . prefix , '.nonadmin' ) ) : if isUserAdmin ( ) : _install ( path , remove , prefix , mode = 'system' ) else : from pywintypes import error try : if not recursing : retcode = runAsAdmin ( [ join ( sys . prefix , 'python' ) , '-c' , "import menuinst; menuinst.install(%r, %r, %r, %r)" % ( path , bool ( remove ) , prefix , True ) ] ) else : retcode = 1 except error : retcode = 1 if retcode != 0 : logging . warn ( "Insufficient permissions to write menu folder. " "Falling back to user location" ) _install ( path , remove , prefix , mode = 'user' ) else : _install ( path , remove , prefix , mode = 'user' ) | install Menu and shortcuts | 241 | 4 |
27,811 | def add_child ( parent , tag , text = None ) : elem = ET . SubElement ( parent , tag ) if text is not None : elem . text = text return elem | Add a child element of specified tag type to parent . The new child element is returned . | 41 | 18 |
27,812 | def _writePlistInfo ( self ) : pl = Plist ( CFBundleExecutable = self . executable , CFBundleGetInfoString = '%s-1.0.0' % self . name , CFBundleIconFile = basename ( self . icns ) , CFBundleIdentifier = 'com.%s' % self . name , CFBundlePackageType = 'APPL' , CFBundleVersion = '1.0.0' , CFBundleShortVersionString = '1.0.0' , ) writePlist ( pl , join ( self . contents_dir , 'Info.plist' ) ) | Writes the Info . plist file in the Contests directory . | 141 | 14 |
27,813 | def readlines ( self , offset = 0 ) : try : with open ( self . _filepath ) as fp : # For full read go through existing lines in file if self . _full_read : fp . seek ( offset ) for row in fp : yield row # Okay now dynamically tail the file if self . _tail : while True : current = fp . tell ( ) row = fp . readline ( ) if row : yield row else : fp . seek ( current ) time . sleep ( self . _sleep ) except IOError as err : print ( 'Error reading the file {0}: {1}' . format ( self . _filepath , err ) ) return | Open the file for reading and yield lines as they are added | 148 | 12 |
27,814 | def get_files ( dir_name ) : return [ ( os . path . join ( '.' , d ) , [ os . path . join ( d , f ) for f in files ] ) for d , _ , files in os . walk ( dir_name ) ] | Simple directory walker | 58 | 4 |
27,815 | def readrows ( self ) : # For each file (may be just one) create a BroLogReader and use it for self . _filepath in self . _files : # Check if the file is zipped tmp = None if self . _filepath . endswith ( '.gz' ) : tmp = tempfile . NamedTemporaryFile ( delete = False ) with gzip . open ( self . _filepath , 'rb' ) as f_in , open ( tmp . name , 'wb' ) as f_out : shutil . copyfileobj ( f_in , f_out ) # Set the file path to the new temp file self . _filepath = tmp . name # Create a BroLogReader reader = bro_log_reader . BroLogReader ( self . _filepath ) for row in reader . readrows ( ) : yield row # Clean up any temp files try : if tmp : os . remove ( tmp . name ) print ( 'Removed temporary file {:s}...' . format ( tmp . name ) ) except IOError : pass | The readrows method reads simply combines the rows of multiple files OR gunzips the file and then reads the rows | 227 | 23 |
27,816 | def most_recent ( path , startswith = None , endswith = None ) : candidate_files = [ ] for filename in all_files_in_directory ( path ) : if startswith and not os . path . basename ( filename ) . startswith ( startswith ) : continue if endswith and not filename . endswith ( endswith ) : continue candidate_files . append ( { 'name' : filename , 'modtime' : os . path . getmtime ( filename ) } ) # Return the most recent modtime most_recent = sorted ( candidate_files , key = lambda k : k [ 'modtime' ] , reverse = True ) return most_recent [ 0 ] [ 'name' ] if most_recent else None | Recursively inspect all files under a directory and return the most recent | 166 | 14 |
27,817 | def yara_match ( file_path , rules ) : print ( 'New Extracted File: {:s}' . format ( file_path ) ) print ( 'Mathes:' ) pprint ( rules . match ( file_path ) ) | Callback for a newly extracted file | 52 | 6 |
27,818 | def readrows ( self ) : # Loop forever or until max_rows is reached num_rows = 0 while True : # Yield the rows from the internal reader for row in self . log_reader . readrows ( ) : yield self . replace_timestamp ( row ) # Sleep and count rows time . sleep ( next ( self . eps_timer ) ) num_rows += 1 # Check for max_rows if self . max_rows and ( num_rows >= self . max_rows ) : return | Using the BroLogReader this method yields each row of the log file replacing timestamps looping and emitting rows based on EPS rate | 108 | 27 |
27,819 | def _parse_bro_header ( self , bro_log ) : # Open the Bro logfile with open ( bro_log , 'r' ) as bro_file : # Skip until you find the #fields line _line = bro_file . readline ( ) while not _line . startswith ( '#fields' ) : _line = bro_file . readline ( ) # Read in the field names field_names = _line . strip ( ) . split ( self . _delimiter ) [ 1 : ] # Read in the types _line = bro_file . readline ( ) field_types = _line . strip ( ) . split ( self . _delimiter ) [ 1 : ] # Setup the type converters type_converters = [ ] for field_type in field_types : type_converters . append ( self . type_mapper . get ( field_type , self . type_mapper [ 'unknown' ] ) ) # Keep the header offset offset = bro_file . tell ( ) # Return the header info return offset , field_names , field_types , type_converters | Parse the Bro log header section . | 245 | 8 |
27,820 | def make_dict ( self , field_values ) : data_dict = { } for key , value , field_type , converter in zip ( self . field_names , field_values , self . field_types , self . type_converters ) : try : # We have to deal with the '-' based on the field_type data_dict [ key ] = self . dash_mapper . get ( field_type , '-' ) if value == '-' else converter ( value ) except ValueError as exc : print ( 'Conversion Issue for key:{:s} value:{:s}\n{:s}' . format ( key , str ( value ) , str ( exc ) ) ) data_dict [ key ] = value if self . _strict : raise exc return data_dict | Internal method that makes sure any dictionary elements are properly cast into the correct types . | 172 | 16 |
27,821 | def str_to_mac ( mac_string ) : sp = mac_string . split ( ':' ) mac_string = '' . join ( sp ) return binascii . unhexlify ( mac_string ) | Convert a readable string to a MAC address | 48 | 9 |
27,822 | def inet_to_str ( inet ) : # First try ipv4 and then ipv6 try : return socket . inet_ntop ( socket . AF_INET , inet ) except ValueError : return socket . inet_ntop ( socket . AF_INET6 , inet ) | Convert inet object to a string | 68 | 8 |
27,823 | def str_to_inet ( address ) : # First try ipv4 and then ipv6 try : return socket . inet_pton ( socket . AF_INET , address ) except socket . error : return socket . inet_pton ( socket . AF_INET6 , address ) | Convert an a string IP address to a inet struct | 63 | 12 |
27,824 | def signal_catcher ( callback ) : def _catch_exit_signal ( sig_num , _frame ) : print ( 'Received signal {:d} invoking callback...' . format ( sig_num ) ) callback ( ) signal . signal ( signal . SIGINT , _catch_exit_signal ) signal . signal ( signal . SIGQUIT , _catch_exit_signal ) signal . signal ( signal . SIGTERM , _catch_exit_signal ) yield | Catch signals and invoke the callback method | 104 | 8 |
27,825 | def entropy ( string ) : p , lns = Counter ( string ) , float ( len ( string ) ) return - sum ( count / lns * math . log ( count / lns , 2 ) for count in p . values ( ) ) | Compute entropy on the string | 52 | 6 |
27,826 | def on_any_event ( self , event ) : if os . path . isfile ( event . src_path ) : self . callback ( event . src_path , * * self . kwargs ) | File created or modified | 45 | 4 |
27,827 | def lookup ( self , ip_address ) : # Is this already in our cache if self . ip_lookup_cache . get ( ip_address ) : domain = self . ip_lookup_cache . get ( ip_address ) # Is the ip_address local or special elif not self . lookup_internal and net_utils . is_internal ( ip_address ) : domain = 'internal' elif net_utils . is_special ( ip_address ) : domain = net_utils . is_special ( ip_address ) # Look it up at this point else : domain = self . _reverse_dns_lookup ( ip_address ) # Cache it self . ip_lookup_cache . set ( ip_address , domain ) # Return the domain return domain | Try to do a reverse dns lookup on the given ip_address | 168 | 14 |
27,828 | def add_rows ( self , list_of_rows ) : for row in list_of_rows : self . row_deque . append ( row ) self . time_deque . append ( time . time ( ) ) # Update the data structure self . update ( ) | Add a list of rows to the DataFrameCache class | 59 | 11 |
27,829 | def update ( self ) : expire_time = time . time ( ) - self . max_time while self . row_deque and self . time_deque [ 0 ] < expire_time : self . row_deque . popleft ( ) # FIFO self . time_deque . popleft ( ) | Update the deque removing rows based on time | 71 | 9 |
27,830 | def _compress ( self ) : # Don't compress too often now = time . time ( ) if self . _last_compression + self . _compression_timer < now : self . _last_compression = now for key in list ( self . _store . keys ( ) ) : self . get ( key ) | Internal method to compress the cache . This method will expire any old items in the cache making the cache smaller | 70 | 21 |
27,831 | def save_vtq ( ) : global vtq print ( 'Saving VirusTotal Query Cache...' ) pickle . dump ( vtq , open ( 'vtq.pkl' , 'wb' ) , protocol = pickle . HIGHEST_PROTOCOL ) sys . exit ( ) | Exit on Signal | 66 | 3 |
27,832 | def fit_transform ( self , df ) : self . index_ = df . index self . columns_ = df . columns self . cat_columns_ = df . select_dtypes ( include = [ 'category' ] ) . columns self . non_cat_columns_ = df . columns . drop ( self . cat_columns_ ) self . cat_map_ = { col : df [ col ] . cat for col in self . cat_columns_ } # Store all the information about categories/values so we can 'back map' later left = len ( self . non_cat_columns_ ) self . cat_blocks_ = { } for col in self . cat_columns_ : right = left + len ( df [ col ] . cat . categories ) self . cat_blocks_ [ col ] , left = slice ( left , right ) , right # This is to ensure that transform always produces the same columns in the same order df_with_dummies = pd . get_dummies ( df ) self . columns_in_order = df_with_dummies . columns . tolist ( ) # Return the numpy matrix return np . asarray ( df_with_dummies ) | Fit method for the DummyEncoder | 261 | 8 |
27,833 | def _make_df ( rows ) : # Make DataFrame df = pd . DataFrame ( rows ) . set_index ( 'ts' ) # TimeDelta Support: https://issues.apache.org/jira/browse/ARROW-835 for column in df . columns : if ( df [ column ] . dtype == 'timedelta64[ns]' ) : print ( 'Converting timedelta column {:s}...' . format ( column ) ) df [ column ] = df [ column ] . astype ( str ) return df | Internal Method to make and clean the dataframe in preparation for sending to Parquet | 119 | 16 |
27,834 | def create_queue ( self , credentials ) : if credentials : session = self . session or aiohttp . ClientSession ( loop = self . event_loop ) return Queue ( options = { 'credentials' : credentials , 'rootUrl' : self . config [ 'taskcluster_root_url' ] , } , session = session ) | Create a taskcluster queue . | 75 | 7 |
27,835 | def write_json ( self , path , contents , message ) : log . debug ( message . format ( path = path ) ) makedirs ( os . path . dirname ( path ) ) with open ( path , "w" ) as fh : json . dump ( contents , fh , indent = 2 , sort_keys = True ) | Write json to disk . | 73 | 5 |
27,836 | async def populate_projects ( self , force = False ) : if force or not self . projects : with tempfile . TemporaryDirectory ( ) as tmpdirname : self . projects = await load_json_or_yaml_from_url ( self , self . config [ 'project_configuration_url' ] , os . path . join ( tmpdirname , 'projects.yml' ) ) | Download the projects . yml file and populate self . projects . | 87 | 13 |
27,837 | async def do_run_task ( context , run_cancellable , to_cancellable_process ) : status = 0 try : if context . config [ 'verify_chain_of_trust' ] : chain = ChainOfTrust ( context , context . config [ 'cot_job_type' ] ) await run_cancellable ( verify_chain_of_trust ( chain ) ) status = await run_task ( context , to_cancellable_process ) generate_cot ( context ) except asyncio . CancelledError : log . info ( "CoT cancelled asynchronously" ) raise WorkerShutdownDuringTask except ScriptWorkerException as e : status = worst_level ( status , e . exit_code ) log . error ( "Hit ScriptWorkerException: {}" . format ( e ) ) except Exception as e : log . exception ( "SCRIPTWORKER_UNEXPECTED_EXCEPTION task {}" . format ( e ) ) raise return status | Run the task logic . | 217 | 5 |
27,838 | async def do_upload ( context , files ) : status = 0 try : await upload_artifacts ( context , files ) except ScriptWorkerException as e : status = worst_level ( status , e . exit_code ) log . error ( "Hit ScriptWorkerException: {}" . format ( e ) ) except aiohttp . ClientError as e : status = worst_level ( status , STATUSES [ 'intermittent-task' ] ) log . error ( "Hit aiohttp error: {}" . format ( e ) ) except Exception as e : log . exception ( "SCRIPTWORKER_UNEXPECTED_EXCEPTION upload {}" . format ( e ) ) raise return status | Upload artifacts and return status . | 152 | 6 |
27,839 | async def run_tasks ( context ) : running_tasks = RunTasks ( ) context . running_tasks = running_tasks status = await running_tasks . invoke ( context ) context . running_tasks = None return status | Run any tasks returned by claimWork . | 54 | 8 |
27,840 | async def async_main ( context , credentials ) : conn = aiohttp . TCPConnector ( limit = context . config [ 'aiohttp_max_connections' ] ) async with aiohttp . ClientSession ( connector = conn ) as session : context . session = session context . credentials = credentials await run_tasks ( context ) | Set up and run tasks for this iteration . | 73 | 9 |
27,841 | async def invoke ( self , context ) : try : # Note: claim_work(...) might not be safely interruptible! See # https://bugzilla.mozilla.org/show_bug.cgi?id=1524069 tasks = await self . _run_cancellable ( claim_work ( context ) ) if not tasks or not tasks . get ( 'tasks' , [ ] ) : await self . _run_cancellable ( asyncio . sleep ( context . config [ 'poll_interval' ] ) ) return None # Assume only a single task, but should more than one fall through, # run them sequentially. A side effect is our return status will # be the status of the final task run. status = None for task_defn in tasks . get ( 'tasks' , [ ] ) : prepare_to_run_task ( context , task_defn ) reclaim_fut = context . event_loop . create_task ( reclaim_task ( context , context . task ) ) try : status = await do_run_task ( context , self . _run_cancellable , self . _to_cancellable_process ) artifacts_paths = filepaths_in_dir ( context . config [ 'artifact_dir' ] ) except WorkerShutdownDuringTask : shutdown_artifact_paths = [ os . path . join ( 'public' , 'logs' , log_file ) for log_file in [ 'chain_of_trust.log' , 'live_backing.log' ] ] artifacts_paths = [ path for path in shutdown_artifact_paths if os . path . isfile ( os . path . join ( context . config [ 'artifact_dir' ] , path ) ) ] status = STATUSES [ 'worker-shutdown' ] status = worst_level ( status , await do_upload ( context , artifacts_paths ) ) await complete_task ( context , status ) reclaim_fut . cancel ( ) cleanup ( context ) return status except asyncio . CancelledError : return None | Claims and processes Taskcluster work . | 458 | 9 |
27,842 | async def cancel ( self ) : self . is_cancelled = True if self . future is not None : self . future . cancel ( ) if self . task_process is not None : log . warning ( "Worker is shutting down, but a task is running. Terminating task" ) await self . task_process . worker_shutdown_stop ( ) | Cancel current work . | 79 | 5 |
27,843 | async def request ( context , url , timeout = 60 , method = 'get' , good = ( 200 , ) , retry = tuple ( range ( 500 , 512 ) ) , return_type = 'text' , * * kwargs ) : session = context . session loggable_url = get_loggable_url ( url ) async with async_timeout . timeout ( timeout ) : log . debug ( "{} {}" . format ( method . upper ( ) , loggable_url ) ) async with session . request ( method , url , * * kwargs ) as resp : log . debug ( "Status {}" . format ( resp . status ) ) message = "Bad status {}" . format ( resp . status ) if resp . status in retry : raise ScriptWorkerRetryException ( message ) if resp . status not in good : raise ScriptWorkerException ( message ) if return_type == 'text' : return await resp . text ( ) elif return_type == 'json' : return await resp . json ( ) else : return resp | Async aiohttp request wrapper . | 230 | 7 |
27,844 | async def retry_request ( * args , retry_exceptions = ( asyncio . TimeoutError , ScriptWorkerRetryException ) , retry_async_kwargs = None , * * kwargs ) : retry_async_kwargs = retry_async_kwargs or { } return await retry_async ( request , retry_exceptions = retry_exceptions , args = args , kwargs = kwargs , * * retry_async_kwargs ) | Retry the request function . | 116 | 6 |
27,845 | def makedirs ( path ) : if path : if not os . path . exists ( path ) : log . debug ( "makedirs({})" . format ( path ) ) os . makedirs ( path ) else : realpath = os . path . realpath ( path ) if not os . path . isdir ( realpath ) : raise ScriptWorkerException ( "makedirs: {} already exists and is not a directory!" . format ( path ) ) | Equivalent to mkdir - p . | 100 | 8 |
27,846 | def rm ( path ) : if path and os . path . exists ( path ) : if os . path . isdir ( path ) : shutil . rmtree ( path ) else : os . remove ( path ) | Equivalent to rm - rf . | 46 | 8 |
27,847 | def cleanup ( context ) : for name in 'work_dir' , 'artifact_dir' , 'task_log_dir' : path = context . config [ name ] if os . path . exists ( path ) : log . debug ( "rm({})" . format ( path ) ) rm ( path ) makedirs ( path ) | Clean up the work_dir and artifact_dir between task runs then recreate . | 73 | 16 |
27,848 | def calculate_sleep_time ( attempt , delay_factor = 5.0 , randomization_factor = .5 , max_delay = 120 ) : if attempt <= 0 : return 0 # We subtract one to get exponents: 1, 2, 3, 4, 5, .. delay = float ( 2 ** ( attempt - 1 ) ) * float ( delay_factor ) # Apply randomization factor. Only increase the delay here. delay = delay * ( randomization_factor * random . random ( ) + 1 ) # Always limit with a maximum delay return min ( delay , max_delay ) | Calculate the sleep time between retries in seconds . | 124 | 12 |
27,849 | async def retry_async ( func , attempts = 5 , sleeptime_callback = calculate_sleep_time , retry_exceptions = Exception , args = ( ) , kwargs = None , sleeptime_kwargs = None ) : kwargs = kwargs or { } attempt = 1 while True : try : return await func ( * args , * * kwargs ) except retry_exceptions : attempt += 1 if attempt > attempts : log . warning ( "retry_async: {}: too many retries!" . format ( func . __name__ ) ) raise sleeptime_kwargs = sleeptime_kwargs or { } sleep_time = sleeptime_callback ( attempt , * * sleeptime_kwargs ) log . debug ( "retry_async: {}: sleeping {} seconds before retry" . format ( func . __name__ , sleep_time ) ) await asyncio . sleep ( sleep_time ) | Retry func where func is an awaitable . | 212 | 10 |
27,850 | def create_temp_creds ( client_id , access_token , start = None , expires = None , scopes = None , name = None ) : now = arrow . utcnow ( ) . replace ( minutes = - 10 ) start = start or now . datetime expires = expires or now . replace ( days = 31 ) . datetime scopes = scopes or [ 'assume:project:taskcluster:worker-test-scopes' , ] creds = createTemporaryCredentials ( client_id , access_token , start , expires , scopes , name = name ) for key , value in creds . items ( ) : try : creds [ key ] = value . decode ( 'utf-8' ) except ( AttributeError , UnicodeDecodeError ) : pass return creds | Request temp TC creds with our permanent creds . | 176 | 11 |
27,851 | def filepaths_in_dir ( path ) : filepaths = [ ] for root , directories , filenames in os . walk ( path ) : for filename in filenames : filepath = os . path . join ( root , filename ) filepath = filepath . replace ( path , '' ) . lstrip ( '/' ) filepaths . append ( filepath ) return filepaths | Find all files in a directory and return the relative paths to those files . | 86 | 15 |
27,852 | def get_hash ( path , hash_alg = "sha256" ) : h = hashlib . new ( hash_alg ) with open ( path , "rb" ) as f : for chunk in iter ( functools . partial ( f . read , 4096 ) , b'' ) : h . update ( chunk ) return h . hexdigest ( ) | Get the hash of the file at path . | 76 | 9 |
27,853 | def load_json_or_yaml ( string , is_path = False , file_type = 'json' , exception = ScriptWorkerTaskException , message = "Failed to load %(file_type)s: %(exc)s" ) : if file_type == 'json' : _load_fh = json . load _load_str = json . loads else : _load_fh = yaml . safe_load _load_str = yaml . safe_load try : if is_path : with open ( string , 'r' ) as fh : contents = _load_fh ( fh ) else : contents = _load_str ( string ) return contents except ( OSError , ValueError , yaml . scanner . ScannerError ) as exc : if exception is not None : repl_dict = { 'exc' : str ( exc ) , 'file_type' : file_type } raise exception ( message % repl_dict ) | Load json or yaml from a filehandle or string and raise a custom exception on failure . | 213 | 19 |
27,854 | def write_to_file ( path , contents , file_type = 'text' ) : FILE_TYPES = ( 'json' , 'text' , 'binary' ) if file_type not in FILE_TYPES : raise ScriptWorkerException ( "Unknown file_type {} not in {}!" . format ( file_type , FILE_TYPES ) ) if file_type == 'json' : contents = format_json ( contents ) if file_type == 'binary' : with open ( path , 'wb' ) as fh : fh . write ( contents ) else : with open ( path , 'w' ) as fh : print ( contents , file = fh , end = "" ) | Write contents to path with optional formatting . | 155 | 8 |
27,855 | def read_from_file ( path , file_type = 'text' , exception = ScriptWorkerException ) : FILE_TYPE_MAP = { 'text' : 'r' , 'binary' : 'rb' } if file_type not in FILE_TYPE_MAP : raise exception ( "Unknown file_type {} not in {}!" . format ( file_type , FILE_TYPE_MAP ) ) try : with open ( path , FILE_TYPE_MAP [ file_type ] ) as fh : return fh . read ( ) except ( OSError , FileNotFoundError ) as exc : raise exception ( "Can't read_from_file {}: {}" . format ( path , str ( exc ) ) ) | Read from path . | 157 | 4 |
27,856 | async def download_file ( context , url , abs_filename , session = None , chunk_size = 128 ) : session = session or context . session loggable_url = get_loggable_url ( url ) log . info ( "Downloading %s" , loggable_url ) parent_dir = os . path . dirname ( abs_filename ) async with session . get ( url ) as resp : if resp . status == 404 : await _log_download_error ( resp , "404 downloading %(url)s: %(status)s; body=%(body)s" ) raise Download404 ( "{} status {}!" . format ( loggable_url , resp . status ) ) elif resp . status != 200 : await _log_download_error ( resp , "Failed to download %(url)s: %(status)s; body=%(body)s" ) raise DownloadError ( "{} status {} is not 200!" . format ( loggable_url , resp . status ) ) makedirs ( parent_dir ) with open ( abs_filename , "wb" ) as fd : while True : chunk = await resp . content . read ( chunk_size ) if not chunk : break fd . write ( chunk ) log . info ( "Done" ) | Download a file async . | 285 | 5 |
27,857 | def get_loggable_url ( url ) : loggable_url = url or "" for secret_string in ( "bewit=" , "AWSAccessKeyId=" , "access_token=" ) : parts = loggable_url . split ( secret_string ) loggable_url = parts [ 0 ] if loggable_url != url : loggable_url = "{}<snip>" . format ( loggable_url ) return loggable_url | Strip out secrets from taskcluster urls . | 108 | 11 |
27,858 | def match_url_regex ( rules , url , callback ) : parts = urlparse ( url ) path = unquote ( parts . path ) for rule in rules : if parts . scheme not in rule [ 'schemes' ] : continue if parts . netloc not in rule [ 'netlocs' ] : continue for regex in rule [ 'path_regexes' ] : m = re . search ( regex , path ) if m is None : continue result = callback ( m ) if result is not None : return result | Given rules and a callback find the rule that matches the url . | 113 | 13 |
27,859 | def add_enumerable_item_to_dict ( dict_ , key , item ) : dict_ . setdefault ( key , [ ] ) if isinstance ( item , ( list , tuple ) ) : dict_ [ key ] . extend ( item ) else : dict_ [ key ] . append ( item ) | Add an item to a list contained in a dict . | 66 | 11 |
27,860 | def get_single_item_from_sequence ( sequence , condition , ErrorClass = ValueError , no_item_error_message = 'No item matched condition' , too_many_item_error_message = 'Too many items matched condition' , append_sequence_to_error_message = True ) : filtered_sequence = [ item for item in sequence if condition ( item ) ] number_of_items_in_filtered_sequence = len ( filtered_sequence ) if number_of_items_in_filtered_sequence == 0 : error_message = no_item_error_message elif number_of_items_in_filtered_sequence > 1 : error_message = too_many_item_error_message else : return filtered_sequence [ 0 ] if append_sequence_to_error_message : error_message = '{}. Given: {}' . format ( error_message , sequence ) raise ErrorClass ( error_message ) | Return an item from a python sequence based on the given condition . | 207 | 13 |
27,861 | def get_task ( config ) : path = os . path . join ( config [ 'work_dir' ] , "task.json" ) message = "Can't read task from {}!\n%(exc)s" . format ( path ) contents = load_json_or_yaml ( path , is_path = True , message = message ) return contents | Read the task . json from work_dir . | 79 | 10 |
27,862 | def validate_json_schema ( data , schema , name = "task" ) : try : jsonschema . validate ( data , schema ) except jsonschema . exceptions . ValidationError as exc : raise ScriptWorkerTaskException ( "Can't validate {} schema!\n{}" . format ( name , str ( exc ) ) , exit_code = STATUSES [ 'malformed-payload' ] ) | Given data and a jsonschema let s validate it . | 92 | 13 |
27,863 | def validate_task_schema ( context , schema_key = 'schema_file' ) : schema_path = context . config schema_keys = schema_key . split ( '.' ) for key in schema_keys : schema_path = schema_path [ key ] task_schema = load_json_or_yaml ( schema_path , is_path = True ) log . debug ( 'Task is validated against this schema: {}' . format ( task_schema ) ) try : validate_json_schema ( context . task , task_schema ) except ScriptWorkerTaskException as e : raise TaskVerificationError ( 'Cannot validate task against schema. Task: {}.' . format ( context . task ) ) from e | Validate the task definition . | 161 | 6 |
27,864 | def validate_artifact_url ( valid_artifact_rules , valid_artifact_task_ids , url ) : def callback ( match ) : path_info = match . groupdict ( ) # make sure we're pointing at a valid task ID if 'taskId' in path_info and path_info [ 'taskId' ] not in valid_artifact_task_ids : return if 'filepath' not in path_info : return return path_info [ 'filepath' ] filepath = match_url_regex ( valid_artifact_rules , url , callback ) if filepath is None : raise ScriptWorkerTaskException ( "Can't validate url {}" . format ( url ) , exit_code = STATUSES [ 'malformed-payload' ] ) return unquote ( filepath ) . lstrip ( '/' ) | Ensure a URL fits in given scheme netloc and path restrictions . | 185 | 14 |
27,865 | def sync_main ( async_main , config_path = None , default_config = None , should_validate_task = True , loop_function = asyncio . get_event_loop ) : context = _init_context ( config_path , default_config ) _init_logging ( context ) if should_validate_task : validate_task_schema ( context ) loop = loop_function ( ) loop . run_until_complete ( _handle_asyncio_loop ( async_main , context ) ) | Entry point for scripts using scriptworker . | 115 | 8 |
27,866 | async def stop ( self ) : # negate pid so that signals apply to process group pgid = - self . process . pid try : os . kill ( pgid , signal . SIGTERM ) await asyncio . sleep ( 1 ) os . kill ( pgid , signal . SIGKILL ) except ( OSError , ProcessLookupError ) : return | Stop the current task process . | 77 | 6 |
27,867 | def ed25519_private_key_from_string ( string ) : try : return Ed25519PrivateKey . from_private_bytes ( base64 . b64decode ( string ) ) except ( UnsupportedAlgorithm , Base64Error ) as exc : raise ScriptWorkerEd25519Error ( "Can't create Ed25519PrivateKey: {}!" . format ( str ( exc ) ) ) | Create an ed25519 private key from string which is a seed . | 86 | 14 |
27,868 | def ed25519_public_key_from_string ( string ) : try : return Ed25519PublicKey . from_public_bytes ( base64 . b64decode ( string ) ) except ( UnsupportedAlgorithm , Base64Error ) as exc : raise ScriptWorkerEd25519Error ( "Can't create Ed25519PublicKey: {}!" . format ( str ( exc ) ) ) | Create an ed25519 public key from string which is a seed . | 86 | 14 |
27,869 | def _ed25519_key_from_file ( fn , path ) : try : return fn ( read_from_file ( path , exception = ScriptWorkerEd25519Error ) ) except ScriptWorkerException as exc : raise ScriptWorkerEd25519Error ( "Failed calling {} for {}: {}!" . format ( fn , path , str ( exc ) ) ) | Create an ed25519 key from the contents of path . | 81 | 12 |
27,870 | def ed25519_private_key_to_string ( key ) : return base64 . b64encode ( key . private_bytes ( encoding = serialization . Encoding . Raw , format = serialization . PrivateFormat . Raw , encryption_algorithm = serialization . NoEncryption ( ) ) , None ) . decode ( 'utf-8' ) | Convert an ed25519 private key to a base64 - encoded string . | 77 | 16 |
27,871 | def ed25519_public_key_to_string ( key ) : return base64 . b64encode ( key . public_bytes ( encoding = serialization . Encoding . Raw , format = serialization . PublicFormat . Raw , ) , None ) . decode ( 'utf-8' ) | Convert an ed25519 public key to a base64 - encoded string . | 64 | 16 |
27,872 | def verify_ed25519_signature ( public_key , contents , signature , message ) : try : public_key . verify ( signature , contents ) except InvalidSignature as exc : raise ScriptWorkerEd25519Error ( message % { 'exc' : str ( exc ) } ) | Verify that signature comes from public_key and contents . | 62 | 12 |
27,873 | def get_reversed_statuses ( context ) : _rev = { v : k for k , v in STATUSES . items ( ) } _rev . update ( dict ( context . config [ 'reversed_statuses' ] ) ) return _rev | Return a mapping of exit codes to status strings . | 58 | 10 |
27,874 | def get_repo ( task , source_env_prefix ) : repo = _extract_from_env_in_payload ( task , source_env_prefix + '_HEAD_REPOSITORY' ) if repo is not None : repo = repo . rstrip ( '/' ) return repo | Get the repo for a task . | 66 | 7 |
27,875 | def get_pull_request_number ( task , source_env_prefix ) : pull_request = _extract_from_env_in_payload ( task , source_env_prefix + '_PULL_REQUEST_NUMBER' ) if pull_request is not None : pull_request = int ( pull_request ) return pull_request | Get what Github pull request created the graph . | 77 | 9 |
27,876 | def get_and_check_project ( valid_vcs_rules , source_url ) : project_path = match_url_regex ( valid_vcs_rules , source_url , match_url_path_callback ) if project_path is None : raise ValueError ( "Unknown repo for source url {}!" . format ( source_url ) ) project = project_path . split ( '/' ) [ - 1 ] return project | Given vcs rules and a source_url return the project . | 95 | 13 |
27,877 | def get_and_check_tasks_for ( context , task , msg_prefix = '' ) : tasks_for = task [ 'extra' ] [ 'tasks_for' ] if tasks_for not in context . config [ 'valid_tasks_for' ] : raise ValueError ( '{}Unknown tasks_for: {}' . format ( msg_prefix , tasks_for ) ) return tasks_for | Given a parent task return the reason the parent task was spawned . | 91 | 13 |
27,878 | def get_repo_scope ( task , name ) : repo_scopes = [ ] for scope in task [ 'scopes' ] : if REPO_SCOPE_REGEX . match ( scope ) : repo_scopes . append ( scope ) if len ( repo_scopes ) > 1 : raise ValueError ( "{}: Too many repo_scopes: {}!" . format ( name , repo_scopes ) ) if repo_scopes : return repo_scopes [ 0 ] | Given a parent task return the repo scope for the task . | 106 | 12 |
27,879 | def is_github_task ( task ) : return any ( ( # XXX Cron tasks don't usually define 'taskcluster-github' as their schedulerId as they # are scheduled within another Taskcluster task. task . get ( 'schedulerId' ) == 'taskcluster-github' , # XXX Same here, cron tasks don't start with github task . get ( 'extra' , { } ) . get ( 'tasks_for' , '' ) . startswith ( 'github-' ) , is_github_url ( task . get ( 'metadata' , { } ) . get ( 'source' , '' ) ) , ) ) | Determine if a task is related to GitHub . | 142 | 11 |
27,880 | def is_action ( task ) : result = False if _extract_from_env_in_payload ( task , 'ACTION_CALLBACK' ) : result = True if task . get ( 'extra' , { } ) . get ( 'action' ) is not None : result = True return result | Determine if a task is an action task . | 67 | 11 |
27,881 | def prepare_to_run_task ( context , claim_task ) : current_task_info = { } context . claim_task = claim_task current_task_info [ 'taskId' ] = get_task_id ( claim_task ) current_task_info [ 'runId' ] = get_run_id ( claim_task ) log . info ( "Going to run taskId {taskId} runId {runId}!" . format ( * * current_task_info ) ) context . write_json ( os . path . join ( context . config [ 'work_dir' ] , 'current_task_info.json' ) , current_task_info , "Writing current task info to {path}..." ) return current_task_info | Given a claim_task json dict prepare the context and work_dir . | 167 | 15 |
27,882 | async def run_task ( context , to_cancellable_process ) : kwargs = { # pragma: no branch 'stdout' : PIPE , 'stderr' : PIPE , 'stdin' : None , 'close_fds' : True , 'preexec_fn' : lambda : os . setsid ( ) , } subprocess = await asyncio . create_subprocess_exec ( * context . config [ 'task_script' ] , * * kwargs ) context . proc = await to_cancellable_process ( TaskProcess ( subprocess ) ) timeout = context . config [ 'task_max_timeout' ] with get_log_filehandle ( context ) as log_filehandle : stderr_future = asyncio . ensure_future ( pipe_to_log ( context . proc . process . stderr , filehandles = [ log_filehandle ] ) ) stdout_future = asyncio . ensure_future ( pipe_to_log ( context . proc . process . stdout , filehandles = [ log_filehandle ] ) ) try : _ , pending = await asyncio . wait ( [ stderr_future , stdout_future ] , timeout = timeout ) if pending : message = "Exceeded task_max_timeout of {} seconds" . format ( timeout ) log . warning ( message ) await context . proc . stop ( ) raise ScriptWorkerTaskException ( message , exit_code = context . config [ 'task_max_timeout_status' ] ) finally : # in the case of a timeout, this will be -15. # this code is in the finally: block so we still get the final # log lines. exitcode = await context . proc . process . wait ( ) # make sure we haven't lost any of the logs await asyncio . wait ( [ stdout_future , stderr_future ] ) # add an exit code line at the end of the log status_line = "exit code: {}" . format ( exitcode ) if exitcode < 0 : status_line = "Automation Error: python exited with signal {}" . format ( exitcode ) log . info ( status_line ) print ( status_line , file = log_filehandle ) stopped_due_to_worker_shutdown = context . proc . stopped_due_to_worker_shutdown context . proc = None if stopped_due_to_worker_shutdown : raise WorkerShutdownDuringTask return exitcode | Run the task sending stdout + stderr to files . | 546 | 13 |
27,883 | async def reclaim_task ( context , task ) : while True : log . debug ( "waiting %s seconds before reclaiming..." % context . config [ 'reclaim_interval' ] ) await asyncio . sleep ( context . config [ 'reclaim_interval' ] ) if task != context . task : return log . debug ( "Reclaiming task..." ) try : context . reclaim_task = await context . temp_queue . reclaimTask ( get_task_id ( context . claim_task ) , get_run_id ( context . claim_task ) , ) clean_response = deepcopy ( context . reclaim_task ) clean_response [ 'credentials' ] = "{********}" log . debug ( "Reclaim task response:\n{}" . format ( pprint . pformat ( clean_response ) ) ) except taskcluster . exceptions . TaskclusterRestFailure as exc : if exc . status_code == 409 : log . debug ( "409: not reclaiming task." ) if context . proc and task == context . task : message = "Killing task after receiving 409 status in reclaim_task" log . warning ( message ) await context . proc . stop ( ) raise ScriptWorkerTaskException ( message , exit_code = context . config [ 'invalid_reclaim_status' ] ) break else : raise | Try to reclaim a task from the queue . | 290 | 9 |
27,884 | async def complete_task ( context , result ) : args = [ get_task_id ( context . claim_task ) , get_run_id ( context . claim_task ) ] reversed_statuses = get_reversed_statuses ( context ) try : if result == 0 : log . info ( "Reporting task complete..." ) response = await context . temp_queue . reportCompleted ( * args ) elif result != 1 and result in reversed_statuses : reason = reversed_statuses [ result ] log . info ( "Reporting task exception {}..." . format ( reason ) ) payload = { "reason" : reason } response = await context . temp_queue . reportException ( * args , payload ) else : log . info ( "Reporting task failed..." ) response = await context . temp_queue . reportFailed ( * args ) log . debug ( "Task status response:\n{}" . format ( pprint . pformat ( response ) ) ) except taskcluster . exceptions . TaskclusterRestFailure as exc : if exc . status_code == 409 : log . info ( "409: not reporting complete/failed." ) else : raise | Mark the task as completed in the queue . | 247 | 9 |
27,885 | async def claim_work ( context ) : log . debug ( "Calling claimWork..." ) payload = { 'workerGroup' : context . config [ 'worker_group' ] , 'workerId' : context . config [ 'worker_id' ] , # Hardcode one task at a time. Make this a pref if we allow for # parallel tasks in multiple `work_dir`s. 'tasks' : 1 , } try : return await context . queue . claimWork ( context . config [ 'provisioner_id' ] , context . config [ 'worker_type' ] , payload ) except ( taskcluster . exceptions . TaskclusterFailure , aiohttp . ClientError ) as exc : log . warning ( "{} {}" . format ( exc . __class__ , exc ) ) | Find and claim the next pending task in the queue if any . | 172 | 13 |
27,886 | def raise_on_errors ( errors , level = logging . CRITICAL ) : if errors : log . log ( level , "\n" . join ( errors ) ) raise CoTError ( "\n" . join ( errors ) ) | Raise a CoTError if errors . | 50 | 9 |
27,887 | def guess_task_type ( name , task_defn ) : parts = name . split ( ':' ) task_type = parts [ - 1 ] if task_type == 'parent' : if is_action ( task_defn ) : task_type = 'action' else : task_type = 'decision' if task_type not in get_valid_task_types ( ) : raise CoTError ( "Invalid task type for {}!" . format ( name ) ) return task_type | Guess the task type of the task . | 108 | 9 |
27,888 | def check_interactive_docker_worker ( link ) : errors = [ ] log . info ( "Checking for {} {} interactive docker-worker" . format ( link . name , link . task_id ) ) try : if link . task [ 'payload' ] [ 'features' ] . get ( 'interactive' ) : errors . append ( "{} is interactive: task.payload.features.interactive!" . format ( link . name ) ) if link . task [ 'payload' ] [ 'env' ] . get ( 'TASKCLUSTER_INTERACTIVE' ) : errors . append ( "{} is interactive: task.payload.env.TASKCLUSTER_INTERACTIVE!" . format ( link . name ) ) except KeyError : errors . append ( "check_interactive_docker_worker: {} task definition is malformed!" . format ( link . name ) ) return errors | Given a task make sure the task was not defined as interactive . | 201 | 13 |
27,889 | def verify_docker_image_sha ( chain , link ) : cot = link . cot task = link . task errors = [ ] if isinstance ( task [ 'payload' ] . get ( 'image' ) , dict ) : # Using pre-built image from docker-image task docker_image_task_id = task [ 'extra' ] [ 'chainOfTrust' ] [ 'inputs' ] [ 'docker-image' ] log . debug ( "Verifying {} {} against docker-image {}" . format ( link . name , link . task_id , docker_image_task_id ) ) if docker_image_task_id != task [ 'payload' ] [ 'image' ] [ 'taskId' ] : errors . append ( "{} {} docker-image taskId isn't consistent!: {} vs {}" . format ( link . name , link . task_id , docker_image_task_id , task [ 'payload' ] [ 'image' ] [ 'taskId' ] ) ) else : path = task [ 'payload' ] [ 'image' ] [ 'path' ] # we need change the hash alg everywhere if we change, and recreate # the docker images... image_hash = cot [ 'environment' ] [ 'imageArtifactHash' ] alg , sha = image_hash . split ( ':' ) docker_image_link = chain . get_link ( docker_image_task_id ) upstream_sha = docker_image_link . cot [ 'artifacts' ] . get ( path , { } ) . get ( alg ) if upstream_sha is None : errors . append ( "{} {} docker-image docker sha {} is missing! {}" . format ( link . name , link . task_id , alg , docker_image_link . cot [ 'artifacts' ] [ path ] ) ) elif upstream_sha != sha : errors . append ( "{} {} docker-image docker sha doesn't match! {} {} vs {}" . format ( link . name , link . task_id , alg , sha , upstream_sha ) ) else : log . debug ( "Found matching docker-image sha {}" . format ( upstream_sha ) ) else : prebuilt_task_types = chain . context . config [ 'prebuilt_docker_image_task_types' ] if prebuilt_task_types != "any" and link . task_type not in prebuilt_task_types : errors . append ( "Task type {} not allowed to use a prebuilt docker image!" . format ( link . task_type ) ) raise_on_errors ( errors ) | Verify that built docker shas match the artifact . | 578 | 11 |
27,890 | def find_sorted_task_dependencies ( task , task_name , task_id ) : log . info ( "find_sorted_task_dependencies {} {}" . format ( task_name , task_id ) ) cot_input_dependencies = [ _craft_dependency_tuple ( task_name , task_type , task_id ) for task_type , task_id in task [ 'extra' ] . get ( 'chainOfTrust' , { } ) . get ( 'inputs' , { } ) . items ( ) ] upstream_artifacts_dependencies = [ _craft_dependency_tuple ( task_name , artifact_dict [ 'taskType' ] , artifact_dict [ 'taskId' ] ) for artifact_dict in task . get ( 'payload' , { } ) . get ( 'upstreamArtifacts' , [ ] ) ] dependencies = [ * cot_input_dependencies , * upstream_artifacts_dependencies ] dependencies = _sort_dependencies_by_name_then_task_id ( dependencies ) parent_task_id = get_parent_task_id ( task ) or get_decision_task_id ( task ) parent_task_type = 'parent' # make sure we deal with the decision task first, or we may populate # signing:build0:decision before signing:decision parent_tuple = _craft_dependency_tuple ( task_name , parent_task_type , parent_task_id ) dependencies . insert ( 0 , parent_tuple ) log . info ( 'found dependencies: {}' . format ( dependencies ) ) return dependencies | Find the taskIds of the chain of trust dependencies of a given task . | 360 | 16 |
27,891 | async def build_task_dependencies ( chain , task , name , my_task_id ) : log . info ( "build_task_dependencies {} {}" . format ( name , my_task_id ) ) if name . count ( ':' ) > chain . context . config [ 'max_chain_length' ] : raise CoTError ( "Too deep recursion!\n{}" . format ( name ) ) sorted_dependencies = find_sorted_task_dependencies ( task , name , my_task_id ) for task_name , task_id in sorted_dependencies : if task_id not in chain . dependent_task_ids ( ) : link = LinkOfTrust ( chain . context , task_name , task_id ) json_path = link . get_artifact_full_path ( 'task.json' ) try : task_defn = await chain . context . queue . task ( task_id ) link . task = task_defn chain . links . append ( link ) # write task json to disk makedirs ( os . path . dirname ( json_path ) ) with open ( json_path , 'w' ) as fh : fh . write ( format_json ( task_defn ) ) await build_task_dependencies ( chain , task_defn , task_name , task_id ) except TaskclusterFailure as exc : raise CoTError ( str ( exc ) ) | Recursively build the task dependencies of a task . | 317 | 11 |
27,892 | async def download_cot ( chain ) : artifact_tasks = [ ] # only deal with chain.links, which are previously finished tasks with # signed chain of trust artifacts. ``chain.task`` is the current running # task, and will not have a signed chain of trust artifact yet. for link in chain . links : task_id = link . task_id parent_dir = link . cot_dir urls = [ ] unsigned_url = get_artifact_url ( chain . context , task_id , 'public/chain-of-trust.json' ) urls . append ( unsigned_url ) if chain . context . config [ 'verify_cot_signature' ] : urls . append ( get_artifact_url ( chain . context , task_id , 'public/chain-of-trust.json.sig' ) ) artifact_tasks . append ( asyncio . ensure_future ( download_artifacts ( chain . context , urls , parent_dir = parent_dir , valid_artifact_task_ids = [ task_id ] ) ) ) artifacts_paths = await raise_future_exceptions ( artifact_tasks ) for path in artifacts_paths : sha = get_hash ( path [ 0 ] ) log . debug ( "{} downloaded; hash is {}" . format ( path [ 0 ] , sha ) ) | Download the signed chain of trust artifacts . | 299 | 8 |
27,893 | async def download_cot_artifact ( chain , task_id , path ) : link = chain . get_link ( task_id ) log . debug ( "Verifying {} is in {} cot artifacts..." . format ( path , task_id ) ) if not link . cot : log . warning ( 'Chain of Trust for "{}" in {} does not exist. See above log for more details. \ Skipping download of this artifact' . format ( path , task_id ) ) return if path not in link . cot [ 'artifacts' ] : raise CoTError ( "path {} not in {} {} chain of trust artifacts!" . format ( path , link . name , link . task_id ) ) url = get_artifact_url ( chain . context , task_id , path ) loggable_url = get_loggable_url ( url ) log . info ( "Downloading Chain of Trust artifact:\n{}" . format ( loggable_url ) ) await download_artifacts ( chain . context , [ url ] , parent_dir = link . cot_dir , valid_artifact_task_ids = [ task_id ] ) full_path = link . get_artifact_full_path ( path ) for alg , expected_sha in link . cot [ 'artifacts' ] [ path ] . items ( ) : if alg not in chain . context . config [ 'valid_hash_algorithms' ] : raise CoTError ( "BAD HASH ALGORITHM: {}: {} {}!" . format ( link . name , alg , full_path ) ) real_sha = get_hash ( full_path , hash_alg = alg ) if expected_sha != real_sha : raise CoTError ( "BAD HASH on file {}: {}: Expected {} {}; got {}!" . format ( full_path , link . name , alg , expected_sha , real_sha ) ) log . debug ( "{} matches the expected {} {}" . format ( full_path , alg , expected_sha ) ) return full_path | Download an artifact and verify its SHA against the chain of trust . | 458 | 13 |
27,894 | async def download_cot_artifacts ( chain ) : upstream_artifacts = chain . task [ 'payload' ] . get ( 'upstreamArtifacts' , [ ] ) all_artifacts_per_task_id = get_all_artifacts_per_task_id ( chain , upstream_artifacts ) mandatory_artifact_tasks = [ ] optional_artifact_tasks = [ ] for task_id , paths in all_artifacts_per_task_id . items ( ) : for path in paths : coroutine = asyncio . ensure_future ( download_cot_artifact ( chain , task_id , path ) ) if is_artifact_optional ( chain , task_id , path ) : optional_artifact_tasks . append ( coroutine ) else : mandatory_artifact_tasks . append ( coroutine ) mandatory_artifacts_paths = await raise_future_exceptions ( mandatory_artifact_tasks ) succeeded_optional_artifacts_paths , failed_optional_artifacts = await get_results_and_future_exceptions ( optional_artifact_tasks ) if failed_optional_artifacts : log . warning ( 'Could not download {} artifacts: {}' . format ( len ( failed_optional_artifacts ) , failed_optional_artifacts ) ) return mandatory_artifacts_paths + succeeded_optional_artifacts_paths | Call download_cot_artifact in parallel for each upstreamArtifacts . | 296 | 15 |
27,895 | def is_artifact_optional ( chain , task_id , path ) : upstream_artifacts = chain . task [ 'payload' ] . get ( 'upstreamArtifacts' , [ ] ) optional_artifacts_per_task_id = get_optional_artifacts_per_task_id ( upstream_artifacts ) return path in optional_artifacts_per_task_id . get ( task_id , [ ] ) | Tells whether an artifact is flagged as optional or not . | 91 | 12 |
27,896 | def get_all_artifacts_per_task_id ( chain , upstream_artifacts ) : all_artifacts_per_task_id = { } for link in chain . links : # Download task-graph.json for decision+action task cot verification if link . task_type in PARENT_TASK_TYPES : add_enumerable_item_to_dict ( dict_ = all_artifacts_per_task_id , key = link . task_id , item = 'public/task-graph.json' ) # Download actions.json for decision+action task cot verification if link . task_type in DECISION_TASK_TYPES : add_enumerable_item_to_dict ( dict_ = all_artifacts_per_task_id , key = link . task_id , item = 'public/actions.json' ) add_enumerable_item_to_dict ( dict_ = all_artifacts_per_task_id , key = link . task_id , item = 'public/parameters.yml' ) if upstream_artifacts : for upstream_dict in upstream_artifacts : add_enumerable_item_to_dict ( dict_ = all_artifacts_per_task_id , key = upstream_dict [ 'taskId' ] , item = upstream_dict [ 'paths' ] ) # Avoid duplicate paths per task_id for task_id , paths in all_artifacts_per_task_id . items ( ) : all_artifacts_per_task_id [ task_id ] = sorted ( set ( paths ) ) return all_artifacts_per_task_id | Return every artifact to download including the Chain Of Trust Artifacts . | 356 | 13 |
27,897 | def verify_link_ed25519_cot_signature ( chain , link , unsigned_path , signature_path ) : if chain . context . config [ 'verify_cot_signature' ] : log . debug ( "Verifying the {} {} {} ed25519 chain of trust signature" . format ( link . name , link . task_id , link . worker_impl ) ) signature = read_from_file ( signature_path , file_type = 'binary' , exception = CoTError ) binary_contents = read_from_file ( unsigned_path , file_type = 'binary' , exception = CoTError ) errors = [ ] verify_key_seeds = chain . context . config [ 'ed25519_public_keys' ] . get ( link . worker_impl , [ ] ) for seed in verify_key_seeds : try : verify_key = ed25519_public_key_from_string ( seed ) verify_ed25519_signature ( verify_key , binary_contents , signature , "{} {}: {} ed25519 cot signature doesn't verify against {}: %(exc)s" . format ( link . name , link . task_id , link . worker_impl , seed ) ) log . debug ( "{} {}: ed25519 cot signature verified." . format ( link . name , link . task_id ) ) break except ScriptWorkerEd25519Error as exc : errors . append ( str ( exc ) ) else : errors = errors or [ "{} {}: Unknown error verifying ed25519 cot signature. worker_impl {} verify_keys {}" . format ( link . name , link . task_id , link . worker_impl , verify_key_seeds ) ] message = "\n" . join ( errors ) raise CoTError ( message ) link . cot = load_json_or_yaml ( unsigned_path , is_path = True , exception = CoTError , message = "{} {}: Invalid unsigned cot json body! %(exc)s" . format ( link . name , link . task_id ) ) | Verify the ed25519 signatures of the chain of trust artifacts populated in download_cot . | 461 | 19 |
27,898 | def verify_cot_signatures ( chain ) : for link in chain . links : unsigned_path = link . get_artifact_full_path ( 'public/chain-of-trust.json' ) ed25519_signature_path = link . get_artifact_full_path ( 'public/chain-of-trust.json.sig' ) verify_link_ed25519_cot_signature ( chain , link , unsigned_path , ed25519_signature_path ) | Verify the signatures of the chain of trust artifacts populated in download_cot . | 110 | 16 |
27,899 | def verify_task_in_task_graph ( task_link , graph_defn , level = logging . CRITICAL ) : ignore_keys = ( "created" , "deadline" , "expires" , "dependencies" , "schedulerId" ) errors = [ ] runtime_defn = deepcopy ( task_link . task ) # dependencies # Allow for the decision task ID in the dependencies; otherwise the runtime # dependencies must be a subset of the graph dependencies. bad_deps = set ( runtime_defn [ 'dependencies' ] ) - set ( graph_defn [ 'task' ] [ 'dependencies' ] ) # it's OK if a task depends on the decision task bad_deps = bad_deps - { task_link . decision_task_id } if bad_deps : errors . append ( "{} {} dependencies don't line up!\n{}" . format ( task_link . name , task_link . task_id , bad_deps ) ) # payload - eliminate the 'expires' key from artifacts because the datestring # will change runtime_defn [ 'payload' ] = _take_expires_out_from_artifacts_in_payload ( runtime_defn [ 'payload' ] ) graph_defn [ 'task' ] [ 'payload' ] = _take_expires_out_from_artifacts_in_payload ( graph_defn [ 'task' ] [ 'payload' ] ) # test all non-ignored key/value pairs in the task defn for key , value in graph_defn [ 'task' ] . items ( ) : if key in ignore_keys : continue if value != runtime_defn [ key ] : errors . append ( "{} {} {} differs!\n graph: {}\n task: {}" . format ( task_link . name , task_link . task_id , key , format_json ( value ) , format_json ( runtime_defn [ key ] ) ) ) raise_on_errors ( errors , level = level ) | Verify a given task_link s task against a given graph task definition . | 456 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.