idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
21,800
public OperationBuilder parameters ( final List < Parameter > parameters ) { List < Parameter > source = nullToEmptyList ( parameters ) ; List < Parameter > destination = new ArrayList < > ( this . parameters ) ; ParameterMerger merger = new ParameterMerger ( destination , source ) ; this . parameters = new ArrayList <...
Updates the input parameters this operation needs
21,801
public ApiDescriptionBuilder operations ( List < Operation > operations ) { if ( operations != null ) { this . operations = operations . stream ( ) . sorted ( operationOrdering ) . collect ( toList ( ) ) ; } return this ; }
Updates the operations to the api operation
21,802
public static Predicate < RequestHandler > withMethodAnnotation ( final Class < ? extends Annotation > annotation ) { return input -> input . isAnnotatedWith ( annotation ) ; }
Predicate that matches RequestHandler with handlers methods annotated with given annotation
21,803
public static Predicate < RequestHandler > withClassAnnotation ( final Class < ? extends Annotation > annotation ) { return input -> declaringClass ( input ) . map ( annotationPresent ( annotation ) ) . orElse ( false ) ; }
Predicate that matches RequestHandler with given annotation on the declaring class of the handler method
21,804
public static Predicate < RequestHandler > basePackage ( final String basePackage ) { return input -> declaringClass ( input ) . map ( handlerPackage ( basePackage ) ) . orElse ( true ) ; }
Predicate that matches RequestHandler with given base package name for the class of the handler method . This predicate includes all request handlers matching the provided basePackage
21,805
private static String [ ] prepareDefaultConf ( ) throws IOException { final File templateFolder = new File ( "test/local-conf-templates" ) ; final File localConfFolder = new File ( "local/conf" ) ; if ( ! localConfFolder . exists ( ) ) { FileUtils . copyDirectory ( templateFolder , localConfFolder . getParentFile ( ) )...
To enable run out of the box for testing .
21,806
public < T > T transaction ( final SQLTransaction < T > operations ) throws SQLException { Connection conn = null ; try { conn = this . queryRunner . getDataSource ( ) . getConnection ( ) ; conn . setAutoCommit ( false ) ; final DatabaseTransOperator transOperator = new DatabaseTransOperator ( this . queryRunner , conn...
Provide a way to allow users define custom SQL operations without relying on fixed SQL interface . The common use case is to group a sequence of SQL operations without commit every time .
21,807
private BasicTimeChecker getBasicTimeChecker ( final Map < String , ConditionChecker > checkers ) { for ( final ConditionChecker checker : checkers . values ( ) ) { if ( checker . getType ( ) . equals ( BasicTimeChecker . type ) ) { return ( BasicTimeChecker ) checker ; } } return null ; }
expirecheckers or triggerCheckers only have BasicTimeChecker today . This should be refactored in future .
21,808
public void setupHadoopJobProperties ( ) { if ( getJobProps ( ) . containsKey ( HADOOP_GLOBAL_OPTS ) ) { String hadoopGlobalOps = getJobProps ( ) . getString ( HADOOP_GLOBAL_OPTS ) ; if ( getJobProps ( ) . containsKey ( HADOOP_OPTS ) ) { String hadoopOps = getJobProps ( ) . getString ( HADOOP_OPTS ) ; getJobProps ( ) ....
Append HADOOP_GLOBAL_OPTS with HADOOP_OPTS in the given props
21,809
public static String formatDuration ( final long startTime , final long endTime ) { if ( startTime == - 1 ) { return "-" ; } final long durationMS ; if ( endTime == - 1 ) { durationMS = System . currentTimeMillis ( ) - startTime ; } else { durationMS = endTime - startTime ; } long seconds = durationMS / 1000 ; if ( sec...
Format time period pair to Duration String
21,810
public static ReadablePeriod parsePeriodString ( final String periodStr ) { final ReadablePeriod period ; final char periodUnit = periodStr . charAt ( periodStr . length ( ) - 1 ) ; if ( periodStr . equals ( "null" ) || periodUnit == 'n' ) { return null ; } final int periodInt = Integer . parseInt ( periodStr . substri...
Parse Period String to a ReadablePeriod Object
21,811
public static String createPeriodString ( final ReadablePeriod period ) { String periodStr = "null" ; if ( period == null ) { return periodStr ; } if ( period . get ( DurationFieldType . years ( ) ) > 0 ) { final int years = period . get ( DurationFieldType . years ( ) ) ; periodStr = years + "y" ; } else if ( period ....
Convert ReadablePeriod Object to string
21,812
private void loadPluginJobTypes ( final JobTypePluginSet plugins ) throws JobTypeManagerException { final File jobPluginsDir = new File ( this . jobTypePluginDir ) ; if ( ! jobPluginsDir . exists ( ) ) { logger . error ( "Job type plugin dir " + this . jobTypePluginDir + " doesn't exist. Will not load any external plug...
load Job Types from jobtype plugin dir
21,813
public List < ExecutableFlow > fetchRecentlyFinishedFlows ( final Duration maxAge ) throws ExecutorManagerException { return this . executionFlowDao . fetchRecentlyFinishedFlows ( maxAge ) ; }
maxAge indicates how long finished flows are shown in Recently Finished flow page .
21,814
private boolean isReady ( ) { if ( this . status != Status . READY ) { return false ; } for ( final Node parent : this . parents ) { if ( ! parent . status . isSuccessEffectively ( ) ) { return false ; } } return true ; }
Checks if the node is ready to run .
21,815
void markSuccess ( ) { assertRunningOrKilling ( ) ; changeStatus ( Status . SUCCESS ) ; for ( final Node child : this . children ) { child . runIfAllowed ( ) ; } this . dag . updateDagStatus ( ) ; }
Transitions the node to the success state .
21,816
void markFailed ( ) { assertRunningOrKilling ( ) ; changeStatus ( Status . FAILURE ) ; for ( final Node child : this . children ) { child . cancel ( ) ; } this . dag . updateDagStatus ( ) ; }
Transitions the node to the failure state .
21,817
void kill ( ) { assert ( this . dag . getStatus ( ) == Status . KILLING ) ; if ( this . status == Status . READY || this . status == Status . BLOCKED ) { changeStatus ( Status . CANCELED ) ; } else if ( this . status == Status . RUNNING ) { changeStatus ( Status . KILLING ) ; } }
Kills a node .
21,818
public static File getConfFile ( Props props , String workingDir , String fileName ) { File jobDir = new File ( workingDir , getDirName ( props ) ) ; if ( ! jobDir . exists ( ) ) { jobDir . mkdir ( ) ; } return new File ( jobDir , fileName ) ; }
Resolve the location of the file containing the configuration file .
21,819
public static String getDirName ( Props props ) { String dirSuffix = props . get ( CommonJobProperties . NESTED_FLOW_PATH ) ; if ( ( dirSuffix == null ) || ( dirSuffix . length ( ) == 0 ) ) { dirSuffix = props . get ( CommonJobProperties . JOB_ID ) ; if ( ( dirSuffix == null ) || ( dirSuffix . length ( ) == 0 ) ) { thr...
For classpath reasons we ll put each link file in a separate directory . This must be called only after the job id has been inserted by the job .
21,820
public static String getPath ( Props props , String workingDir ) { return new File ( workingDir , getDirName ( props ) ) . toString ( ) ; }
Gets the path to the directory in which the generated links and Hadoop conf properties files are written .
21,821
public static void loadProp ( Props props , Configuration conf , String name ) { String prop = props . get ( name ) ; if ( prop != null ) { conf . set ( name , prop ) ; } }
Loads an Azkaban property into the Hadoop configuration .
21,822
private void refreshExecutors ( ) { final List < Pair < Executor , Future < ExecutorInfo > > > futures = new ArrayList < > ( ) ; for ( final Executor executor : this . activeExecutors . getAll ( ) ) { final Future < ExecutorInfo > fetchExecutionInfo = this . executorInfoRefresherService . submit ( ( ) -> this . apiGate...
Refresh Executor stats for all the actie executors in this executorManager
21,823
public String getQueuedFlowIds ( ) { final List < Integer > allIds = new ArrayList < > ( ) ; getRunningFlowsIdsHelper ( allIds , this . queuedFlows . getAllEntries ( ) ) ; Collections . sort ( allIds ) ; return allIds . toString ( ) ; }
Get execution Ids of all non - dispatched flows
21,824
private void dispatch ( final ExecutionReference reference , final ExecutableFlow exflow , final Executor choosenExecutor ) throws ExecutorManagerException { exflow . setUpdateTime ( System . currentTimeMillis ( ) ) ; this . executorLoader . assignExecutor ( choosenExecutor . getId ( ) , exflow . getExecutionId ( ) ) ;...
Calls executor to dispatch the flow update db to assign the executor and in - memory state of executableFlow .
21,825
public void unsetExecutorIdForExecution ( final int executionId ) throws ExecutorManagerException { final String UNSET_EXECUTOR = "UPDATE execution_flows SET executor_id = null where exec_id = ?" ; final SQLTransaction < Integer > unsetExecutor = transOperator -> transOperator . update ( UNSET_EXECUTOR , executionId ) ...
set executor id to null for the execution id
21,826
public void run ( ) throws IOException { if ( this . isStarted ( ) || this . isComplete ( ) ) { throw new IllegalStateException ( "The process can only be used once." ) ; } final ProcessBuilder builder = new ProcessBuilder ( this . cmd ) ; builder . directory ( new File ( this . workingDir ) ) ; builder . environment (...
Execute this process blocking until it has completed .
21,827
public boolean softKill ( final long time , final TimeUnit unit ) throws InterruptedException { checkStarted ( ) ; if ( this . processId != 0 && isStarted ( ) ) { try { if ( this . isExecuteAsUser ) { final String cmd = String . format ( "%s %s %s %d" , this . executeAsUserBinary , this . effectiveUser , KILL_COMMAND ,...
Attempt to kill the process waiting up to the given time for it to die
21,828
public void hardKill ( ) { checkStarted ( ) ; if ( isRunning ( ) ) { if ( this . processId != 0 ) { try { if ( this . isExecuteAsUser ) { final String cmd = String . format ( "%s %s %s -9 %d" , this . executeAsUserBinary , this . effectiveUser , KILL_COMMAND , this . processId ) ; Runtime . getRuntime ( ) . exec ( cmd ...
Force kill this process
21,829
private int processId ( final java . lang . Process process ) { int processId = 0 ; try { final Field f = process . getClass ( ) . getDeclaredField ( "pid" ) ; f . setAccessible ( true ) ; processId = f . getInt ( process ) ; } catch ( final Throwable e ) { e . printStackTrace ( ) ; } return processId ; }
Attempt to get the process id for this process
21,830
public void render ( ) { try { this . response . setHeader ( "Content-type" , "text/html; charset=UTF-8" ) ; this . response . setCharacterEncoding ( "UTF-8" ) ; this . response . setContentType ( this . mimeType ) ; this . engine . mergeTemplate ( this . template , "UTF-8" , this . context , this . response . getWrite...
Renders the page in UTF - 8
21,831
private void validateDepNameUniqueness ( final List < TriggerDependencyBean > dependencies ) { final Set < String > seen = new HashSet < > ( ) ; for ( final TriggerDependencyBean dep : dependencies ) { Preconditions . checkArgument ( seen . add ( dep . getName ( ) ) , String . format ( "duplicate dependency" + ".name %...
check uniqueness of dependency . name
21,832
private void validateNameAndTypeArePresent ( final List < TriggerDependencyBean > dependencies ) { for ( final TriggerDependencyBean dep : dependencies ) { Preconditions . checkNotNull ( dep . getName ( ) , "dependency name is required" ) ; Preconditions . checkNotNull ( dep . getType ( ) , "dependency type is required...
validate name and type are present
21,833
public static void main ( final String [ ] args ) throws ParseException { final CommandLineParser parser = new DefaultParser ( ) ; if ( parser . parse ( createHelpOptions ( ) , args , true ) . hasOption ( HELP_KEY ) ) { new HelpFormatter ( ) . printHelp ( EncryptionCLI . class . getSimpleName ( ) , createOptions ( ) , ...
Outputs ciphered text to STDOUT .
21,834
protected void registerFactorFilter ( final FactorFilter < T , V > filter ) { if ( null == filter ) { throw new IllegalArgumentException ( "unable to register factor filter. " + "The passed comaractor is null or has an invalid weight value." ) ; } this . factorFilterList . put ( filter . getFactorName ( ) , filter ) ; ...
function to register a factorFilter to the internal Map for future reference .
21,835
public boolean filterTarget ( final T filteringTarget , final V referencingObject ) { logger . debug ( String . format ( "start filtering '%s' with factor filter for '%s'" , filteringTarget == null ? "(null)" : filteringTarget . toString ( ) , this . getName ( ) ) ) ; final Collection < FactorFilter < T , V > > filterL...
function to analyze the target item according to the reference object to decide whether the item should be filtered .
21,836
public static int getMaxConcurrentRunsForFlow ( String projectName , String flowName , int defaultMaxConcurrentRuns , Map < Pair < String , String > , Integer > maxConcurrentRunsFlowMap ) { return maxConcurrentRunsFlowMap . getOrDefault ( new Pair ( projectName , flowName ) , defaultMaxConcurrentRuns ) ; }
Get the maximum number of concurrent runs for the specified flow using the value in azkaban . concurrent . runs . oneflow . whitelist if explictly specified for the flow and otherwise azkaban . max . concurrent . runs . oneflow or the default .
21,837
public static String [ ] partitionCommandLine ( final String command ) { final ArrayList < String > commands = new ArrayList < > ( ) ; int index = 0 ; StringBuffer buffer = new StringBuffer ( command . length ( ) ) ; boolean isApos = false ; boolean isQuote = false ; while ( index < command . length ( ) ) { final char ...
Splits the command into a unix like command line structure . Quotes and single quotes are treated as nested strings .
21,838
public static void applyDisabledJobs ( final List < DisabledJob > disabledJobs , final ExecutableFlowBase exflow ) { for ( final DisabledJob disabled : disabledJobs ) { if ( disabled . isEmbeddedFlow ( ) ) { final ExecutableNode node = exflow . getExecutableNode ( disabled . getName ( ) ) ; if ( node != null && node in...
Change job status to disabled in exflow if the job is in disabledJobs
21,839
public void closeMBeans ( ) { try { for ( final ObjectName name : registeredMBeans ) { getMbeanServer ( ) . unregisterMBean ( name ) ; logger . info ( "Jmx MBean " + name . getCanonicalName ( ) + " unregistered." ) ; } } catch ( final Exception e ) { logger . error ( "Failed to cleanup MBeanServer" , e ) ; } }
Close all registered MBeans
21,840
public Object getMBeanAttribute ( final ObjectName name , final String attribute ) { try { return getMbeanServer ( ) . getAttribute ( name , attribute ) ; } catch ( final Exception e ) { logger . error ( "Retrieve MBeanServer attribute Failure. " + "ObjectName = " + name . toString ( ) + ", " + "attribute = " + attribu...
Get MBean Attribute
21,841
public Map < String , Object > getMBeanResult ( final String mbeanName ) { final Map < String , Object > ret = new HashMap < > ( ) ; try { final ObjectName name = new ObjectName ( mbeanName ) ; final MBeanInfo info = getMBeanInfo ( name ) ; final MBeanAttributeInfo [ ] mbeanAttrs = info . getAttributes ( ) ; final Map ...
Get MBean Result
21,842
public Object eval ( ) { logger . info ( "Checking sla for execution " + this . execId ) ; final ExecutableFlow flow ; try { flow = this . executorLoader . fetchExecutableFlow ( this . execId ) ; } catch ( final ExecutorManagerException e ) { logger . error ( "Can't get executable flow." , e ) ; e . printStackTrace ( )...
return true to trigger sla action
21,843
private void handleChangeManagerStatusRequest ( final HttpServletRequest req , final Map < String , Object > ret , final boolean enableMetricManager ) { try { logger . info ( "Updating metric manager status" ) ; if ( ( enableMetricManager && MetricReportManager . isInstantiated ( ) ) || MetricReportManager . isAvailabl...
enable or disable metric Manager A disable will also purge all data from all metric emitters
21,844
private void handleChangeCleaningInterval ( final HttpServletRequest req , final Map < String , Object > ret ) { try { final long newInterval = getLongParam ( req , STATS_MAP_CLEANINGINTERVAL ) ; if ( MetricReportManager . isAvailable ( ) ) { final MetricReportManager metricManager = MetricReportManager . getInstance (...
Update InMemoryMetricEmitter interval to maintain metric snapshots
21,845
private InMemoryMetricEmitter extractInMemoryMetricEmitter ( final MetricReportManager metricManager ) { InMemoryMetricEmitter memoryEmitter = null ; for ( final IMetricEmitter emitter : metricManager . getMetricEmitters ( ) ) { if ( emitter instanceof InMemoryMetricEmitter ) { memoryEmitter = ( InMemoryMetricEmitter )...
Get InMemoryMetricEmitter if available else null
21,846
private void handleGetAllMMetricsName ( final HttpServletRequest req , final Map < String , Object > ret ) { if ( MetricReportManager . isAvailable ( ) ) { final MetricReportManager metricManager = MetricReportManager . getInstance ( ) ; final List < IMetric < ? > > result = metricManager . getAllMetrics ( ) ; if ( res...
Get all the metrics tracked by metric manager
21,847
private void handleChangeMetricInterval ( final HttpServletRequest req , final Map < String , Object > ret ) throws ServletException { try { final String metricName = getParam ( req , STATS_MAP_METRICNAMEPARAM ) ; final long newInterval = getLongParam ( req , STATS_MAP_REPORTINGINTERVAL ) ; if ( MetricReportManager . i...
Update tracking interval for a given metrics
21,848
private static Props loadConfigurationFromAzkabanHome ( ) { final String azkabanHome = System . getenv ( "AZKABAN_HOME" ) ; if ( azkabanHome == null ) { logger . error ( "AZKABAN_HOME not set. Will try default." ) ; return null ; } if ( ! new File ( azkabanHome ) . isDirectory ( ) || ! new File ( azkabanHome ) . canRea...
Loads the Azkaban property file from the AZKABAN_HOME conf directory
21,849
public boolean closeClassLoader ( final ClassLoader cl ) throws ValidatorManagerException { boolean res = false ; if ( cl == null ) { return res ; } final Class classURLClassLoader = URLClassLoader . class ; Field f = null ; try { f = classURLClassLoader . getDeclaredField ( "ucp" ) ; } catch ( final NoSuchFieldExcepti...
close jar files of cl
21,850
public boolean finalizeNativeLibs ( final ClassLoader cl ) throws ValidatorManagerException { boolean res = false ; final Class classClassLoader = ClassLoader . class ; java . lang . reflect . Field nativeLibraries = null ; try { nativeLibraries = classClassLoader . getDeclaredField ( "nativeLibraries" ) ; } catch ( fi...
finalize native libraries
21,851
public void sendEmail ( final List < String > emailList , final String subject , final String body ) { if ( emailList != null && ! emailList . isEmpty ( ) ) { final EmailMessage message = super . createEmailMessage ( subject , "text/html" , emailList ) ; message . setBody ( body ) ; sendEmail ( message , true , "email ...
Send an email to the specified email list
21,852
private void sendFailedUpdateEmail ( final Executor executor , final ExecutorManagerException exception , final MailCreator mailCreator , final ImmutableList < ExecutableFlow > flows ) { final EmailMessage message = this . messageCreator . createMessage ( ) ; final boolean mailCreated = mailCreator . createFailedUpdate...
Sends a single email about failed updates .
21,853
private void waitUntilFlowPreparationFinish ( ) throws InterruptedException { final Duration SLEEP_INTERVAL = Duration . ofSeconds ( 5 ) ; while ( this . preparingFlowCount . intValue ( ) != 0 ) { logger . info ( this . preparingFlowCount + " flow(s) is/are still being setup before complete " + "deactivation." ) ; Thre...
Wait until ongoing flow preparation work finishes .
21,854
private void configureFlowLevelMetrics ( final FlowRunner flowRunner ) { logger . info ( "Configuring Azkaban metrics tracking for flow runner object" ) ; if ( MetricReportManager . isAvailable ( ) ) { final MetricReportManager metricManager = MetricReportManager . getInstance ( ) ; flowRunner . addListener ( ( NumFail...
Configure Azkaban metrics tracking for a new flowRunner instance
21,855
public void shutdown ( ) { logger . warn ( "Shutting down FlowRunnerManager..." ) ; if ( this . azkabanProps . getBoolean ( ConfigurationKeys . AZKABAN_POLL_MODEL , false ) ) { this . pollingService . shutdown ( ) ; } this . executorService . shutdown ( ) ; boolean result = false ; while ( ! result ) { logger . info ( ...
This shuts down the flow runner . The call is blocking and awaits execution of all jobs .
21,856
public void deleteExecutionDirectory ( ) { logger . warn ( "Deleting execution dir: " + this . executionDirectory . getAbsolutePath ( ) ) ; try { FileUtils . deleteDirectory ( this . executionDirectory ) ; } catch ( final IOException e ) { logger . error ( e ) ; } }
Deleting old execution directory to free disk space .
21,857
public static Props loadPluginProps ( final File pluginDir ) { if ( ! pluginDir . exists ( ) ) { logger . error ( "Error! Plugin path " + pluginDir . getPath ( ) + " doesn't exist." ) ; return null ; } if ( ! pluginDir . isDirectory ( ) ) { logger . error ( "The plugin path " + pluginDir + " is not a directory." ) ; re...
Load plugin properties
21,858
public static void loadPropsBySuffix ( final File jobPath , final Props props , final String ... suffixes ) { try { if ( jobPath . isDirectory ( ) ) { final File [ ] files = jobPath . listFiles ( ) ; if ( files != null ) { for ( final File file : files ) { loadPropsBySuffix ( file , props , suffixes ) ; } } } else if (...
Load properties from the given path
21,859
public static boolean isVariableReplacementPattern ( final String value ) { final Matcher matcher = VARIABLE_REPLACEMENT_PATTERN . matcher ( value ) ; return matcher . matches ( ) ; }
Check if the prop value is a variable replacement pattern
21,860
private static String resolveVariableExpression ( final String value , final int last , final JexlEngine jexl ) { final int lastIndex = value . lastIndexOf ( "$(" , last ) ; if ( lastIndex == - 1 ) { return value ; } int bracketCount = 0 ; int nextClosed = lastIndex + 2 ; for ( ; nextClosed < value . length ( ) ; ++ ne...
Function that looks for expressions to parse . It parses backwards to capture embedded expressions
21,861
public static String toJSONString ( final Props props , final boolean localOnly ) { final Map < String , String > map = toStringMap ( props , localOnly ) ; return JSONUtils . toJSON ( map ) ; }
Convert props to json string
21,862
public static Map < String , String > toStringMap ( final Props props , final boolean localOnly ) { final HashMap < String , String > map = new HashMap < > ( ) ; final Set < String > keyset = localOnly ? props . localKeySet ( ) : props . getKeySet ( ) ; for ( final String key : keyset ) { final String value = props . g...
Convert props to Map
21,863
public static Props fromJSONString ( final String json ) throws IOException { final Map < String , String > obj = ( Map < String , String > ) JSONUtils . parseJSONFromString ( json ) ; final Props props = new Props ( null , obj ) ; return props ; }
Convert json String to Prop Object
21,864
public static Props fromHierarchicalMap ( final Map < String , Object > propsMap ) { if ( propsMap == null ) { return null ; } final String source = ( String ) propsMap . get ( "source" ) ; final Map < String , String > propsParams = ( Map < String , String > ) propsMap . get ( "props" ) ; final Map < String , Object >...
Convert a hierarchical Map to Prop Object
21,865
public static Map < String , Object > toHierarchicalMap ( final Props props ) { final Map < String , Object > propsMap = new HashMap < > ( ) ; propsMap . put ( "source" , props . getSource ( ) ) ; propsMap . put ( "props" , toStringMap ( props , true ) ) ; if ( props . getParent ( ) != null ) { propsMap . put ( "parent...
Convert a Props object to a hierarchical Map
21,866
public static String getPropertyDiff ( Props oldProps , Props newProps ) { final StringBuilder builder = new StringBuilder ( "" ) ; if ( oldProps == null ) { oldProps = new Props ( ) ; } if ( newProps == null ) { newProps = new Props ( ) ; } final MapDifference < String , String > md = Maps . difference ( toStringMap (...
The difference between old and new Props
21,867
private static FactorComparator < Executor > getNumberOfAssignedFlowComparator ( final int weight ) { return FactorComparator . create ( NUMOFASSIGNEDFLOW_COMPARATOR_NAME , weight , new Comparator < Executor > ( ) { public int compare ( final Executor o1 , final Executor o2 ) { final ExecutorInfo stat1 = o1 . getExecut...
function defines the number of assigned flow comparator .
21,868
private static FactorComparator < Executor > getCpuUsageComparator ( final int weight ) { return FactorComparator . create ( CPUUSAGE_COMPARATOR_NAME , weight , new Comparator < Executor > ( ) { public int compare ( final Executor o1 , final Executor o2 ) { final ExecutorInfo stat1 = o1 . getExecutorInfo ( ) ; final Ex...
function defines the cpuUsage comparator .
21,869
private static FactorComparator < Executor > getLstDispatchedTimeComparator ( final int weight ) { return FactorComparator . create ( LSTDISPATCHED_COMPARATOR_NAME , weight , new Comparator < Executor > ( ) { public int compare ( final Executor o1 , final Executor o2 ) { final ExecutorInfo stat1 = o1 . getExecutorInfo ...
function defines the last dispatched time comparator .
21,870
protected String parseResponse ( final HttpResponse response ) throws HttpResponseException , IOException { final StatusLine statusLine = response . getStatusLine ( ) ; final String responseBody = response . getEntity ( ) != null ? EntityUtils . toString ( response . getEntity ( ) ) : "" ; if ( statusLine . getStatusCo...
Implementing the parseResponse function to return de - serialized Json object .
21,871
private void prepareTokenFile ( final String user , final Credentials credentials , final File tokenFile , final Logger logger ) throws IOException { writeCredentialsToFile ( credentials , tokenFile , logger ) ; try { assignPermissions ( user , tokenFile , logger ) ; } catch ( final IOException e ) { tokenFile . delete...
Prepare token file . Writes credentials to a token file and sets appropriate permissions to keep the file secure
21,872
private void assignPermissions ( final String user , final File tokenFile , final Logger logger ) throws IOException { final List < String > changePermissionsCommand = Arrays . asList ( CHMOD , TOKEN_FILE_PERMISSIONS , tokenFile . getAbsolutePath ( ) ) ; int result = this . executeAsUser . execute ( System . getPropert...
Uses execute - as - user binary to reassign file permissions to be readable only by that user .
21,873
private IMetaStoreClient createRetryingMetaStoreClient ( final HiveConf hiveConf ) throws MetaException { final HiveMetaHookLoader hookLoader = new HiveMetaHookLoader ( ) { public HiveMetaHook getHook ( final Table tbl ) throws MetaException { if ( tbl == null ) { return null ; } try { final HiveStorageHandler storageH...
Method to create a metastore client that retries on failures
21,874
Driver provideHiveDriver ( ) { HiveConf hiveConf = provideHiveConf ( ) ; SessionState . start ( hiveConf ) ; return new Driver ( hiveConf ) ; }
Return a Driver that s connected to the real honest - to - goodness Hive
21,875
private void shutdown ( final Map < String , Object > respMap ) { try { logger . warn ( "Shutting down executor..." ) ; setActiveInternal ( false ) ; this . application . shutdown ( ) ; respMap . put ( ConnectorParams . STATUS_PARAM , ConnectorParams . RESPONSE_SUCCESS ) ; } catch ( final Exception e ) { logger . error...
Prepare the executor for shutdown .
21,876
public long getLastInsertId ( ) throws SQLException { long num = - 1 ; try { num = ( ( Number ) this . queryRunner . query ( this . conn , "SELECT LAST_INSERT_ID();" , new ScalarHandler < > ( 1 ) ) ) . longValue ( ) ; } catch ( final SQLException ex ) { logger . error ( "can not get last insertion ID" ) ; throw ex ; } ...
returns the last id from a previous insert statement . Note that last insert and this operation should use the same connection .
21,877
protected void logJobProperties ( ) { if ( this . jobProps != null && this . jobProps . getBoolean ( JOB_DUMP_PROPERTIES_IN_LOG , false ) ) { try { final Map < String , String > flattenedProps = this . jobProps . getFlattened ( ) ; this . info ( "****** Job properties ******" ) ; this . info ( String . format ( "- ...
prints the current Job props to the Job log .
21,878
public File [ ] initPropsFiles ( ) { final File [ ] files = new File [ 2 ] ; files [ 0 ] = createFlattenedPropsFile ( this . cwd ) ; this . jobProps . put ( ENV_PREFIX + JOB_PROP_ENV , files [ 0 ] . getAbsolutePath ( ) ) ; this . jobProps . put ( ENV_PREFIX + JOB_NAME_ENV , getId ( ) ) ; files [ 1 ] = createOutputProps...
initialize temporary and final property file
21,879
public Map < String , String > getEnvironmentVariables ( ) { final Props props = getJobProps ( ) ; final Map < String , String > envMap = props . getMapByPrefix ( ENV_PREFIX ) ; return envMap ; }
Get Environment Variables from the Job Properties Table
21,880
public String getWorkingDirectory ( ) { final String workingDir = getJobProps ( ) . getString ( WORKING_DIR , this . jobPath ) ; return Utils . ifNull ( workingDir , "" ) ; }
Get Working Directory from Job Properties when it is presented . Otherwise the working directory is the jobPath
21,881
< T > T callForJsonType ( final String host , final int port , final String path , final List < Pair < String , String > > paramList , final Class < T > valueType ) throws IOException { final String responseString = callForJsonString ( host , port , path , paramList ) ; if ( null == responseString || responseString . l...
Call executor and parse the JSON response as an instance of the class given as an argument .
21,882
public static void hideUploadButtonWhenNeeded ( final Page page , final Session session , final UserManager userManager , final Boolean lockdownUploadProjects ) { final User user = session . getUser ( ) ; if ( lockdownUploadProjects && ! UserUtils . hasPermissionforAction ( userManager , user , Permission . Type . UPLO...
Method hides the upload button for regular users from relevant pages when the property lockdown . upload . projects is set . The button is displayed for admin users and users with upload permissions .
21,883
public String createSlaMessage ( final ExecutableFlow flow ) { final int execId = flow . getExecutionId ( ) ; final String durationStr = durationToString ( this . duration ) ; switch ( this . type . getComponent ( ) ) { case FLOW : final String basicinfo = "SLA Alert: Your flow " + this . flowName + " failed to " + thi...
Construct the message for the SLA .
21,884
public void cleanupProjectArtifacts ( final int projectId ) { if ( ! isCleanupPermitted ( ) ) { return ; } final Set < String > allResourceIds = findResourceIdsToDelete ( projectId ) ; if ( allResourceIds . size ( ) == 0 ) { return ; } log . warn ( String . format ( "Deleting project artifacts [id: %d]: %s" , projectId...
Remove all but last N artifacts as configured by AZKABAN_STORAGE_ARTIFACT_MAX_RETENTION
21,885
private boolean delete ( final String resourceId ) { final boolean isDeleted = this . storage . delete ( resourceId ) && removeDbEntry ( resourceId ) ; if ( ! isDeleted ) { log . info ( "Failed to delete resourceId: " + resourceId ) ; } return isDeleted ; }
Main Delete Utility .
21,886
protected boolean tieBreak ( final T object1 , final T object2 ) { if ( null == object2 ) { return true ; } if ( null == object1 ) { return false ; } return object1 . hashCode ( ) >= object2 . hashCode ( ) ; }
tieBreak method which will kick in when the comparator list generated an equality result for both sides . the tieBreak method will try best to make sure a stable result is returned .
21,887
protected void registerFactorComparator ( final FactorComparator < T > comparator ) { if ( null == comparator || Integer . MAX_VALUE - this . getTotalWeight ( ) < comparator . getWeight ( ) ) { throw new IllegalArgumentException ( "unable to register comparator." + " The passed comparator is null or has an invalid weig...
function to register a factorComparator to the internal Map for future reference .
21,888
public int getTotalWeight ( ) { int totalWeight = 0 ; final Collection < FactorComparator < T > > allValues = this . factorComparatorList . values ( ) ; for ( final FactorComparator < T > item : allValues ) { if ( item != null ) { totalWeight += item . getWeight ( ) ; } } return totalWeight ; }
function returns the total weight of the registered comparators .
21,889
private List < Object > getFilePreviews ( final String [ ] fileList , final String locationFull , final IStreamProvider streamProvider , final boolean renderResultsAsHtml ) { final List < Object > files = new ArrayList < > ( ) ; InputStream csvInputStream = null ; try { for ( final String fileName : fileList ) { final ...
Returns a list of file Objects that contain a name property with the file name a content property with the lines in the file and a hasMore property if the file contains more than NUM_PREVIEW_ROWS lines .
21,890
public synchronized boolean pauseJobIfPresent ( final String jobName , final String groupName ) throws SchedulerException { if ( ifJobExist ( jobName , groupName ) ) { this . scheduler . pauseJob ( new JobKey ( jobName , groupName ) ) ; return true ; } else { return false ; } }
Pause a job if it s present .
21,891
public synchronized boolean isJobPaused ( final String jobName , final String groupName ) throws SchedulerException { if ( ! ifJobExist ( jobName , groupName ) ) { throw new SchedulerException ( String . format ( "Job (job name %s, group name %s) doesn't " + "exist'" , jobName , groupName ) ) ; } final JobKey jobKey = ...
Check if job is paused .
21,892
public synchronized boolean unscheduleJob ( final String jobName , final String groupName ) throws SchedulerException { return this . scheduler . deleteJob ( new JobKey ( jobName , groupName ) ) ; }
Unschedule a job .
21,893
public synchronized boolean scheduleJobIfAbsent ( final String cronExpression , final QuartzJobDescription jobDescription ) throws SchedulerException { requireNonNull ( jobDescription , "jobDescription is null" ) ; if ( ifJobExist ( jobDescription . getJobName ( ) , jobDescription . getGroupName ( ) ) ) { logger . warn...
Only cron schedule register is supported . Since register might be called when concurrently uploading projects so synchronized is added to ensure thread safety .
21,894
private void getFlowsHelper ( final ArrayList < ExecutableFlow > flows , final Collection < Pair < ExecutionReference , ExecutableFlow > > collection ) { collection . stream ( ) . forEach ( ref -> flows . add ( ref . getSecond ( ) ) ) ; }
Helper method to get all flows from collection .
21,895
public List < Integer > getQueuedFlowIds ( ) { final List < Integer > allIds = new ArrayList < > ( ) ; try { getExecutionIdsHelper ( allIds , this . executorLoader . fetchQueuedFlows ( ) ) ; } catch ( final ExecutorManagerException e ) { this . logger . error ( "Failed to get queued flow ids." , e ) ; } return allIds ;...
Get execution ids of all non - dispatched flows from database .
21,896
public Collection < TriggerInstance > getRecentlyFinished ( final int limit ) { final String query = String . format ( SELECT_RECENTLY_FINISHED , limit ) ; try { return this . dbOperator . query ( query , new TriggerInstanceHandler ( SORT_MODE . SORT_ON_START_TIME_ASC ) ) ; } catch ( final SQLException ex ) { handleSQL...
Retrieve recently finished trigger instances but flow trigger properties are not populated into the returned trigger instances for efficiency . Flow trigger properties will be retrieved only on request time .
21,897
public TriggerInstance getTriggerInstanceByFlowExecId ( final int flowExecId ) { if ( flowExecId == Constants . FAILED_EXEC_ID || flowExecId == Constants . UNASSIGNED_EXEC_ID ) { return null ; } TriggerInstance triggerInstance = null ; try { final Collection < TriggerInstance > res = this . dbOperator . query ( SELECT_...
Retrieve a trigger instance given a flow execution id . Flow trigger properties will also be populated into the returned trigger instance . If flow exec id is - 1 or - 2 then null will be returned .
21,898
public TriggerInstance getTriggerInstanceById ( final String triggerInstanceId ) { TriggerInstance triggerInstance = null ; try { final Collection < TriggerInstance > res = this . dbOperator . query ( SELECT_EXECUTIONS_BY_INSTANCE_ID , new TriggerInstanceHandler ( SORT_MODE . SORT_ON_START_TIME_ASC ) , triggerInstanceI...
Retrieve a trigger instance given an instance id . Flow trigger properties will also be populated into the returned trigger instance .
21,899
private static IPropertiesValidator getValidator ( GobblinPresets preset ) { Objects . requireNonNull ( preset ) ; switch ( preset ) { case MYSQL_TO_HDFS : return new MySqlToHdfsValidator ( ) ; case HDFS_TO_MYSQL : return new HdfsToMySqlValidator ( ) ; default : throw new UnsupportedOperationException ( "Preset " + pre...
Factory method that provides IPropertiesValidator based on preset in runtime . Using factory method pattern as it is expected to grow .