idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
31,500 | public PactDslJsonArray maxArrayLike ( Integer size , PactDslJsonRootValue value , int numberExamples ) { if ( numberExamples > size ) { throw new IllegalArgumentException ( String . format ( "Number of example %d is more than the maximum size of %d" , numberExamples , size ) ) ; } matchers . addRule ( rootPath + appendArrayIndex ( 1 ) , matchMax ( size ) ) ; PactDslJsonArray parent = new PactDslJsonArray ( rootPath , "" , this , true ) ; parent . setNumberExamples ( numberExamples ) ; parent . putObject ( value ) ; return ( PactDslJsonArray ) parent . closeArray ( ) ; } | Array of values with a maximum size that are not objects where each item must match the provided example |
31,501 | public PactDslJsonArray includesStr ( String value ) { body . put ( value ) ; matchers . addRule ( rootPath + appendArrayIndex ( 0 ) , includesMatcher ( value ) ) ; return this ; } | List item that must include the provided string |
31,502 | public PactDslJsonArray equalsTo ( Object value ) { body . put ( value ) ; matchers . addRule ( rootPath + appendArrayIndex ( 0 ) , EqualsMatcher . INSTANCE ) ; return this ; } | Attribute that must be equal to the provided value . |
31,503 | public PactDslJsonArray valueFromProviderState ( String expression , Object example ) { generators . addGenerator ( Category . BODY , rootPath + appendArrayIndex ( 0 ) , new ProviderStateGenerator ( expression ) ) ; body . put ( example ) ; return this ; } | Adds an element that will have it s value injected from the provider state |
31,504 | public PactDslRequestWithoutPath withFileUpload ( String partName , String fileName , String fileContentType , byte [ ] data ) throws IOException { setupFileUpload ( partName , fileName , fileContentType , data ) ; return this ; } | Sets up a file upload request . This will add the correct content type header to the request |
31,505 | public PactDslRequestWithoutPath headerFromProviderState ( String name , String expression , String example ) { requestGenerators . addGenerator ( Category . HEADER , name , new ProviderStateGenerator ( expression ) ) ; requestHeaders . put ( name , Collections . singletonList ( example ) ) ; return this ; } | Adds a header that will have it s value injected from the provider state |
31,506 | public PactDslRequestWithoutPath queryParameterFromProviderState ( String name , String expression , String example ) { requestGenerators . addGenerator ( Category . QUERY , name , new ProviderStateGenerator ( expression ) ) ; query . put ( name , Collections . singletonList ( example ) ) ; return this ; } | Adds a query parameter that will have it s value injected from the provider state |
31,507 | public static < T > Optional < T > get ( Config config , Function < String , T > getter , String path ) { if ( ! config . hasPath ( path ) ) { return Optional . empty ( ) ; } return Optional . of ( getter . apply ( path ) ) ; } | Optionally get a configuration value . |
31,508 | GoogleIdToken authenticate ( String token ) { final GoogleIdToken googleIdToken ; try { googleIdToken = verifyIdToken ( token ) ; } catch ( IOException e ) { logger . warn ( "Failed to verify token" ) ; return null ; } if ( googleIdToken == null ) { logger . debug ( "Invalid id token: verifyIdToken returned null" ) ; return null ; } final String email = googleIdToken . getPayload ( ) . getEmail ( ) ; if ( email == null ) { logger . debug ( "No email in id token" ) ; return null ; } final String domain = getDomain ( email ) ; if ( domain == null ) { logger . warn ( "Invalid email address {}" , email ) ; return null ; } else if ( domainWhitelist . contains ( domain ) ) { logger . debug ( "Domain {} in whitelist" , domain ) ; return googleIdToken ; } if ( validatedEmailCache . getIfPresent ( email ) != null ) { logger . debug ( "Cache hit for {}" , email ) ; return googleIdToken ; } if ( ! SERVICE_ACCOUNT_PATTERN . matcher ( email ) . matches ( ) ) { logger . debug ( "Not a service account: {}" , email ) ; return null ; } if ( ! allowedAudiences . isEmpty ( ) && googleIdToken . getPayload ( ) . getAudience ( ) != null ) { if ( ! googleIdToken . verifyAudience ( allowedAudiences ) ) { logger . warn ( "ID token wasn't intended for Styx" ) ; return null ; } } final String projectId ; try { projectId = checkServiceAccountProject ( email ) ; } catch ( IOException e ) { logger . info ( "Cannot authenticate {}" , email ) ; return null ; } if ( projectId != null ) { validatedEmailCache . put ( email , projectId ) ; return googleIdToken ; } return null ; } | Authenticate and authorize a Google ID token string from an incoming Styx API request . |
31,509 | public CounterSnapshot getCounterSnapshot ( String counterId ) throws IOException { final CounterSnapshot snapshot = inMemSnapshot . getIfPresent ( counterId ) ; if ( snapshot != null ) { stats . recordCounterCacheHit ( ) ; return snapshot ; } stats . recordCounterCacheMiss ( ) ; return refreshCounterSnapshot ( counterId ) ; } | Returns a recent snapshot possibly read from inMemSnapshot . |
31,510 | private CounterSnapshot refreshCounterSnapshot ( String counterId ) throws IOException { final CounterSnapshot newSnapshot = counterSnapshotFactory . create ( counterId ) ; inMemSnapshot . put ( counterId , newSnapshot ) ; return newSnapshot ; } | Update cached snapshot with most recent state of counter in Datastore . |
31,511 | public void updateCounter ( StorageTransaction transaction , String counterId , long delta ) throws IOException { CounterSnapshot snapshot = getCounterSnapshot ( counterId ) ; if ( delta < 0 ) { Optional < Integer > shardIndex = snapshot . pickShardWithExcessUsage ( delta ) ; if ( shardIndex . isPresent ( ) ) { updateCounterShard ( transaction , counterId , delta , shardIndex . get ( ) , snapshot . shardCapacity ( shardIndex . get ( ) ) ) ; return ; } } int shardIndex = snapshot . pickShardWithSpareCapacity ( delta ) ; updateCounterShard ( transaction , counterId , delta , shardIndex , snapshot . shardCapacity ( shardIndex ) ) ; } | Must be called within a TransactionCallable . Augments the transaction with certain operations that strongly consistently increment resp . decrement the counter referred to by counterId and cause the transaction to fail to commit if the counter s associated limit is exceeded . Also spurious failures are possible . |
31,512 | private static void initialize ( Storage storage , String counterId ) { LOG . debug ( "Initializing counter shards for resource {}" , counterId ) ; for ( int startIndex = 0 ; startIndex < NUM_SHARDS ; startIndex += TRANSACTION_GROUP_SIZE ) { initShardRange ( storage , counterId , startIndex , Math . min ( NUM_SHARDS , startIndex + TRANSACTION_GROUP_SIZE ) ) ; } } | Idempotent initialization so that we don t reset an existing shard to zero - counterId may have already been initialized and incremented by another process . |
31,513 | Map < WorkflowInstance , RunState > readActiveStates ( ) throws IOException { var timeout = CompletableFuture . runAsync ( ( ) -> { } , delayedExecutor ( 30 , SECONDS ) ) ; var instances = listActiveInstances0 ( timeout ) ; var states = gatherIO ( Lists . partition ( List . copyOf ( instances ) , MAX_NUMBER_OF_ENTITIES_IN_ONE_BATCH_READ ) . stream ( ) . map ( batch -> asyncIO ( ( ) -> readRunStateBatch ( batch ) ) ) . collect ( toList ( ) ) , timeout ) . stream ( ) . flatMap ( Collection :: stream ) . collect ( toMap ( RunState :: workflowInstance , Function . identity ( ) ) ) ; timeout . cancel ( true ) ; return states ; } | Strongly consistently read all active states |
31,514 | void deleteResource ( String id ) throws IOException { storeWithRetries ( ( ) -> { datastore . delete ( datastore . newKeyFactory ( ) . setKind ( KIND_COUNTER_LIMIT ) . newKey ( id ) ) ; return null ; } ) ; deleteShardsForCounter ( id ) ; } | Delete resource by id . Deletes both counter shards and counter limit if it exists . |
31,515 | public static < T > List < T > gatherIO ( List < ? extends CompletableFuture < ? extends T > > futures , CompletionStage < Void > timeout ) throws IOException { timeout . thenRun ( ( ) -> futures . forEach ( f -> f . completeExceptionally ( new TimeoutException ( ) ) ) ) ; var values = ImmutableList . < T > builder ( ) ; for ( var future : futures ) { try { values . add ( future . get ( ) ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new IOException ( e ) ; } catch ( ExecutionException e ) { final Throwable cause = e . getCause ( ) ; Throwables . propagateIfPossible ( cause , IOException . class ) ; if ( cause instanceof TimeoutException ) { throw new IOException ( cause ) ; } else { throw new RuntimeException ( cause ) ; } } } return values . build ( ) ; } | Gathers results from futures that may fail with IOExceptions . |
31,516 | public AuthContext authenticate ( Request request ) { final boolean hasAuthHeader = request . header ( HttpHeaders . AUTHORIZATION ) . isPresent ( ) ; if ( ! hasAuthHeader ) { return Optional :: empty ; } final String authHeader = request . header ( HttpHeaders . AUTHORIZATION ) . get ( ) ; if ( ! authHeader . startsWith ( BEARER_PREFIX ) ) { throw new ResponseException ( Response . forStatus ( Status . BAD_REQUEST . withReasonPhrase ( "Authorization token must be of type Bearer" ) ) ) ; } final GoogleIdToken googleIdToken ; try { googleIdToken = authenticator . authenticate ( authHeader . substring ( BEARER_PREFIX . length ( ) ) ) ; } catch ( IllegalArgumentException e ) { throw new ResponseException ( Response . forStatus ( Status . BAD_REQUEST . withReasonPhrase ( "Failed to parse Authorization token" ) ) , e ) ; } if ( googleIdToken == null ) { throw new ResponseException ( Response . forStatus ( Status . UNAUTHORIZED . withReasonPhrase ( "Authorization token is invalid" ) ) ) ; } return ( ) -> Optional . of ( googleIdToken ) ; } | Authentication an incoming Styx API request . |
31,517 | private Map < String , String > defaultMetadata ( ) { final Builder < String , String > builder = ImmutableMap . builder ( ) ; final Map < String , String > envVars = envVarSupplier . get ( ) ; for ( final Map . Entry < String , String > entry : DEFAULT_METADATA_ENVVARS . entrySet ( ) ) { final String envKey = entry . getKey ( ) ; final String metadataKey = entry . getValue ( ) ; final String envValue = envVars . get ( envKey ) ; if ( envValue != null ) { builder . put ( metadataKey , envValue ) ; } } return builder . build ( ) ; } | Metadata to associate with jobs by default . Currently sets some metadata based upon environment variables set when the CLI command is run . |
31,518 | public static void reRegisterHost ( final ZooKeeperClient client , final String host , final String hostId ) throws HostNotFoundException , KeeperException { log . info ( "re-registering host: {}, new host id: {}" , host , hostId ) ; try { final List < ZooKeeperOperation > operations = Lists . newArrayList ( ) ; operations . add ( check ( Paths . configHost ( host ) ) ) ; final List < String > nodes = safeListRecursive ( client , Paths . statusHost ( host ) ) ; for ( final String node : reverse ( nodes ) ) { operations . add ( delete ( node ) ) ; } operations . add ( create ( Paths . statusHost ( host ) ) ) ; operations . add ( create ( Paths . statusHostJobs ( host ) ) ) ; operations . add ( delete ( Paths . configHostId ( host ) ) ) ; operations . add ( create ( Paths . configHostId ( host ) , hostId . getBytes ( UTF_8 ) ) ) ; client . transaction ( operations ) ; } catch ( NoNodeException e ) { throw new HostNotFoundException ( host ) ; } catch ( KeeperException e ) { throw new HeliosRuntimeException ( e ) ; } } | Re - register an agent with a different host id . Will remove the existing status of the agent but preserve any jobs deployed to the host and their history . |
31,519 | @ Produces ( APPLICATION_JSON ) public List < String > list ( ) { return model . getRunningMasters ( ) ; } | Returns a list of names of running Helios masters . |
31,520 | public void addListener ( final AgentModel . Listener listener ) { listeners . add ( listener ) ; listener . tasksChanged ( this ) ; } | Add a listener that will be notified when tasks are changed . |
31,521 | public RolloutOptions withFallback ( final RolloutOptions that ) { return RolloutOptions . newBuilder ( ) . setTimeout ( firstNonNull ( timeout , that . timeout ) ) . setParallelism ( firstNonNull ( parallelism , that . parallelism ) ) . setMigrate ( firstNonNull ( migrate , that . migrate ) ) . setOverlap ( firstNonNull ( overlap , that . overlap ) ) . setToken ( firstNonNull ( token , that . token ) ) . setIgnoreFailures ( firstNonNull ( ignoreFailures , that . ignoreFailures ) ) . build ( ) ; } | Return a new RolloutOptions instance by merging this instance with another one . |
31,522 | @ SuppressWarnings ( "UseOfSystemOutOrSystemErr" ) private void handleError ( ArgumentParser parser , ArgumentParserException ex ) { System . err . println ( "# " + HELP_ISSUES ) ; System . err . println ( "# " + HELP_WIKI ) ; System . err . println ( "# ---------------------------------------------------------------" ) ; parser . handleError ( ex ) ; } | Use this instead of calling parser . handle error directly . This will print a header with links to jira and documentation before the standard error message is printed . |
31,523 | private Map < String , T > sync ( ) throws KeeperException { log . debug ( "syncing: {}" , path ) ; final Map < String , T > newSnapshot = Maps . newHashMap ( ) ; try { final List < String > children = getChildren ( ) ; log . debug ( "children: {}" , children ) ; for ( final String child : children ) { final String node = ZKPaths . makePath ( path , child ) ; final byte [ ] bytes = curator . getData ( ) . usingWatcher ( dataWatcher ) . forPath ( node ) ; final String json = new String ( bytes , UTF_8 ) ; log . debug ( "child: {}={}" , node , json ) ; final T value ; try { value = Json . read ( bytes , valueType ) ; } catch ( IOException e ) { log . warn ( "failed to parse node: {}: {}" , node , json , e ) ; continue ; } newSnapshot . put ( node , value ) ; } } catch ( KeeperException e ) { throw e ; } catch ( Exception e ) { Throwables . throwIfUnchecked ( e ) ; throw new RuntimeException ( e ) ; } return newSnapshot ; } | Fetch new snapshot and register watchers . |
31,524 | public static String getDomainFromResolverConf ( final String file ) { try ( final InputStream in = new FileInputStream ( file ) ) { final InputStreamReader isr = new InputStreamReader ( in ) ; try ( final BufferedReader br = new BufferedReader ( isr ) ) { String line ; while ( ( line = br . readLine ( ) ) != null ) { if ( line . startsWith ( "domain" ) ) { final StringTokenizer st = new StringTokenizer ( line ) ; st . nextToken ( ) ; if ( ! st . hasMoreTokens ( ) ) { continue ; } return st . nextToken ( ) ; } } } } catch ( FileNotFoundException e ) { log . warn ( "Resolver config file not found" , e ) ; } catch ( IOException e ) { log . warn ( "Error reading config file" , e ) ; } return "" ; } | Looks in file to find the domain setting . |
31,525 | public static List < Target > from ( final String srvName , final Iterable < String > domains ) { final ImmutableList . Builder < Target > builder = ImmutableList . builder ( ) ; for ( final String domain : domains ) { builder . add ( new SrvTarget ( srvName , domain ) ) ; } return builder . build ( ) ; } | Create targets for a list of domains . |
31,526 | private boolean run ( final Namespace options , final Target target , final PrintStream out , final PrintStream err , final String username , final boolean json , final BufferedReader stdin ) throws Exception { final HeliosClient client = Utils . getClient ( target , err , username , options ) ; if ( client == null ) { return false ; } try { final int result = run ( options , client , out , json , stdin ) ; return result == 0 ; } catch ( ExecutionException e ) { final Throwable cause = e . getCause ( ) ; if ( cause instanceof TimeoutException ) { err . println ( "Request timed out to master in " + target ) ; } else { throw new RuntimeException ( cause ) ; } return false ; } finally { client . close ( ) ; } } | Execute against a cluster at a specific endpoint . |
31,527 | public List < String > getRunningMasters ( ) { final ZooKeeperClient client = provider . get ( "getRunningMasters" ) ; try { final List < String > masters = client . getChildren ( Paths . statusMaster ( ) ) ; final ImmutableList . Builder < String > upMasters = ImmutableList . builder ( ) ; for ( final String master : masters ) { if ( client . exists ( Paths . statusMasterUp ( master ) ) != null ) { upMasters . add ( master ) ; } } return upMasters . build ( ) ; } catch ( KeeperException e ) { throw new HeliosRuntimeException ( "listing masters failed" , e ) ; } } | Returns a list of the host names of the currently running masters . |
31,528 | public void addJob ( final Job job ) throws JobExistsException { log . info ( "adding job: {}" , job ) ; final JobId id = job . getId ( ) ; final UUID operationId = UUID . randomUUID ( ) ; final String creationPath = Paths . configJobCreation ( id , operationId ) ; final ZooKeeperClient client = provider . get ( "addJob" ) ; try { try { client . ensurePath ( Paths . historyJob ( id ) ) ; client . transaction ( create ( Paths . configJob ( id ) , job ) , create ( Paths . configJobRefShort ( id ) , id ) , create ( Paths . configJobHosts ( id ) ) , create ( creationPath ) , set ( Paths . configJobs ( ) , UUID . randomUUID ( ) . toString ( ) . getBytes ( ) ) ) ; } catch ( final NodeExistsException e ) { if ( client . exists ( creationPath ) != null ) { return ; } throw new JobExistsException ( id . toString ( ) ) ; } } catch ( NoNodeException e ) { throw new HeliosRuntimeException ( "adding job " + job + " failed due to missing ZK path: " + e . getPath ( ) , e ) ; } catch ( final KeeperException e ) { throw new HeliosRuntimeException ( "adding job " + job + " failed" , e ) ; } } | Adds a job into the configuration . |
31,529 | public List < TaskStatusEvent > getJobHistory ( final JobId jobId ) throws JobDoesNotExistException { return getJobHistory ( jobId , null ) ; } | Given a jobId returns the N most recent events in its history in the cluster . |
31,530 | public List < TaskStatusEvent > getJobHistory ( final JobId jobId , final String host ) throws JobDoesNotExistException { final Job descriptor = getJob ( jobId ) ; if ( descriptor == null ) { throw new JobDoesNotExistException ( jobId ) ; } final ZooKeeperClient client = provider . get ( "getJobHistory" ) ; final List < String > hosts ; try { hosts = ( ! isNullOrEmpty ( host ) ) ? singletonList ( host ) : client . getChildren ( Paths . historyJobHosts ( jobId ) ) ; } catch ( NoNodeException e ) { return emptyList ( ) ; } catch ( KeeperException e ) { throw new RuntimeException ( e ) ; } final List < TaskStatusEvent > jsEvents = Lists . newArrayList ( ) ; for ( final String h : hosts ) { final List < String > events ; try { events = client . getChildren ( Paths . historyJobHostEvents ( jobId , h ) ) ; } catch ( NoNodeException e ) { continue ; } catch ( KeeperException e ) { throw new RuntimeException ( e ) ; } for ( final String event : events ) { try { final byte [ ] data = client . getData ( Paths . historyJobHostEventsTimestamp ( jobId , h , Long . valueOf ( event ) ) ) ; final TaskStatus status = Json . read ( data , TaskStatus . class ) ; jsEvents . add ( new TaskStatusEvent ( status , Long . valueOf ( event ) , h ) ) ; } catch ( NoNodeException e ) { } catch ( KeeperException | IOException e ) { throw new RuntimeException ( e ) ; } } } return Ordering . from ( EVENT_COMPARATOR ) . sortedCopy ( jsEvents ) ; } | Given a jobId and host returns the N most recent events in its history on that host in the cluster . |
31,531 | public void addDeploymentGroup ( final DeploymentGroup deploymentGroup ) throws DeploymentGroupExistsException { log . info ( "adding deployment-group: {}" , deploymentGroup ) ; final ZooKeeperClient client = provider . get ( "addDeploymentGroup" ) ; try { try { client . ensurePath ( Paths . configDeploymentGroups ( ) ) ; client . ensurePath ( Paths . statusDeploymentGroups ( ) ) ; client . transaction ( create ( Paths . configDeploymentGroup ( deploymentGroup . getName ( ) ) , deploymentGroup ) , create ( Paths . statusDeploymentGroup ( deploymentGroup . getName ( ) ) ) , create ( Paths . statusDeploymentGroupHosts ( deploymentGroup . getName ( ) ) , Json . asBytesUnchecked ( emptyList ( ) ) ) , create ( Paths . statusDeploymentGroupRemovedHosts ( deploymentGroup . getName ( ) ) , Json . asBytesUnchecked ( emptyList ( ) ) ) ) ; } catch ( final NodeExistsException e ) { throw new DeploymentGroupExistsException ( deploymentGroup . getName ( ) ) ; } } catch ( final KeeperException e ) { throw new HeliosRuntimeException ( "adding deployment-group " + deploymentGroup + " failed" , e ) ; } } | Create a deployment group . |
31,532 | public void removeDeploymentGroup ( final String name ) throws DeploymentGroupDoesNotExistException { log . info ( "removing deployment-group: name={}" , name ) ; final ZooKeeperClient client = provider . get ( "removeDeploymentGroup" ) ; try { client . ensurePath ( Paths . configDeploymentGroups ( ) ) ; client . ensurePath ( Paths . statusDeploymentGroups ( ) ) ; client . ensurePath ( Paths . statusDeploymentGroupTasks ( ) ) ; final List < ZooKeeperOperation > operations = Lists . newArrayList ( ) ; final List < String > paths = ImmutableList . of ( Paths . configDeploymentGroup ( name ) , Paths . statusDeploymentGroup ( name ) , Paths . statusDeploymentGroupHosts ( name ) , Paths . statusDeploymentGroupRemovedHosts ( name ) , Paths . statusDeploymentGroupTasks ( name ) ) ; for ( final String path : paths ) { if ( client . exists ( path ) == null ) { operations . add ( create ( path ) ) ; } } for ( final String path : Lists . reverse ( paths ) ) { operations . add ( delete ( path ) ) ; } client . transaction ( operations ) ; } catch ( final NoNodeException e ) { throw new DeploymentGroupDoesNotExistException ( name ) ; } catch ( final KeeperException e ) { throw new HeliosRuntimeException ( "removing deployment-group " + name + " failed" , e ) ; } } | Remove a deployment group . |
31,533 | private boolean updateOnHostChange ( final DeploymentGroup group , final DeploymentGroupStatus status ) { if ( status == null ) { return true ; } if ( group . getRollingUpdateReason ( ) == null ) { return status . getState ( ) != FAILED ; } if ( group . getRollingUpdateReason ( ) == HOSTS_CHANGED && status . getState ( ) == FAILED ) { return true ; } return status . getState ( ) != FAILED ; } | Determines whether we should trigger a rolling update when deployment group hosts change . |
31,534 | private boolean redundantUndeployment ( final Deployment deployment , final DeploymentGroup deploymentGroup ) { if ( ! Objects . equals ( deployment . getDeploymentGroupName ( ) , deploymentGroup . getName ( ) ) ) { return false ; } if ( ! deployment . getJobId ( ) . equals ( deploymentGroup . getJobId ( ) ) ) { return false ; } if ( ! Goal . START . equals ( deployment . getGoal ( ) ) ) { return false ; } return true ; } | redundantDeployment determines whether or not rollingUpdateUndeploy should actually emit RollingUpdateOps to undeploy a job . |
31,535 | public Job removeJob ( final JobId id , final String token ) throws JobDoesNotExistException , JobStillDeployedException , TokenVerificationException { log . info ( "removing job: id={}" , id ) ; final ZooKeeperClient client = provider . get ( "removeJob" ) ; final Job job = getJob ( client , id ) ; if ( job == null ) { throw new JobDoesNotExistException ( id ) ; } verifyToken ( token , job ) ; try { final ImmutableList . Builder < ZooKeeperOperation > operations = ImmutableList . builder ( ) ; final UUID jobCreationOperationId = getJobCreation ( client , id ) ; if ( jobCreationOperationId != null ) { operations . add ( delete ( Paths . configJobCreation ( id , jobCreationOperationId ) ) ) ; } operations . add ( delete ( Paths . configJobHosts ( id ) ) , delete ( Paths . configJobRefShort ( id ) ) , delete ( Paths . configJob ( id ) ) , set ( Paths . configJobs ( ) , UUID . randomUUID ( ) . toString ( ) . getBytes ( ) ) ) ; client . transaction ( operations . build ( ) ) ; } catch ( final NoNodeException e ) { throw new JobDoesNotExistException ( id ) ; } catch ( final NotEmptyException e ) { throw new JobStillDeployedException ( id , listJobHosts ( client , id ) ) ; } catch ( final KeeperException e ) { throw new HeliosRuntimeException ( "removing job " + id + " failed" , e ) ; } try { client . deleteRecursive ( Paths . historyJob ( id ) ) ; } catch ( NoNodeException ignored ) { } catch ( KeeperException e ) { log . warn ( "error removing job history for job {}" , id , e ) ; } return job ; } | Deletes a job from ZooKeeper . Ensures that job is not currently running anywhere . |
31,536 | public void updateDeployment ( final String host , final Deployment deployment , final String token ) throws HostNotFoundException , JobNotDeployedException , TokenVerificationException { log . info ( "updating deployment {}: {}" , deployment , host ) ; final ZooKeeperClient client = provider . get ( "updateDeployment" ) ; final JobId jobId = deployment . getJobId ( ) ; final Job job = getJob ( client , jobId ) ; final Deployment existingDeployment = getDeployment ( host , jobId ) ; if ( job == null ) { throw new JobNotDeployedException ( host , jobId ) ; } verifyToken ( token , job ) ; assertHostExists ( client , host ) ; assertTaskExists ( client , host , deployment . getJobId ( ) ) ; final String path = Paths . configHostJob ( host , jobId ) ; final Task task = new Task ( job , deployment . getGoal ( ) , existingDeployment . getDeployerUser ( ) , existingDeployment . getDeployerMaster ( ) , existingDeployment . getDeploymentGroupName ( ) ) ; try { client . setData ( path , task . toJsonBytes ( ) ) ; } catch ( Exception e ) { throw new HeliosRuntimeException ( "updating deployment " + deployment + " on host " + host + " failed" , e ) ; } } | Used to update the existing deployment of a job . |
31,537 | public void close ( ) { reactor . stopAsync ( ) ; if ( runner != null ) { runner . stopAsync ( ) ; } metrics . supervisorClosed ( ) ; monitor . close ( ) ; } | Close this supervisor . The actual container is left as - is . |
31,538 | public Map < String , Integer > allocate ( final Map < String , PortMapping > ports , final Set < Integer > used ) { return allocate0 ( ports , Sets . newHashSet ( used ) ) ; } | Allocate ports for port mappings with no external ports configured . |
31,539 | private boolean portAvailable ( final int port ) { ServerSocket socket = null ; try { socket = new ServerSocket ( port ) ; return true ; } catch ( IOException ignored ) { return false ; } finally { if ( socket != null ) { try { socket . close ( ) ; } catch ( IOException e ) { log . error ( "Couldn't close socket on port {} when checking availability: {}" , port , e ) ; } } } } | Check if the port is available on the host . This is racy but it s better than nothing . |
31,540 | private List < String > findMatchesWithLowestScore ( final List < ScoredHost > scored ) { final int minScore = scored . get ( 0 ) . score ; final ImmutableList . Builder < String > minScoreHosts = ImmutableList . builder ( ) ; for ( final ScoredHost score : scored ) { if ( score . score == minScore ) { minScoreHosts . add ( score . host ) ; } } return minScoreHosts . build ( ) ; } | Assumes sorted input in scored |
31,541 | private List < ScoredHost > scoreMatches ( final List < String > results ) { final ImmutableList . Builder < ScoredHost > scored = ImmutableList . builder ( ) ; for ( final String name : results ) { int score = Integer . MAX_VALUE ; for ( int i = 0 ; i < searchPath . length ; i ++ ) { if ( name . endsWith ( searchPath [ i ] . toString ( ) ) ) { if ( i < score ) { score = i ; } } } scored . add ( new ScoredHost ( name , score ) ) ; } return scored . build ( ) ; } | Score matches based upon the position in the dns search domain that matches the result |
31,542 | public static CliConfig fromFile ( final File defaultsFile , final Map < String , String > environmentVariables ) throws IOException , URISyntaxException { final Config config ; if ( defaultsFile . exists ( ) && defaultsFile . canRead ( ) ) { config = ConfigFactory . parseFile ( defaultsFile ) ; } else { config = ConfigFactory . empty ( ) ; } return fromEnvVar ( config , environmentVariables ) ; } | Returns a CliConfig instance with values parsed from the specified file . |
31,543 | public Supervisor create ( final Job job , final String existingContainerId , final Map < String , Integer > ports , final Supervisor . Listener listener ) { final RestartPolicy policy = RestartPolicy . newBuilder ( ) . build ( ) ; final TaskConfig taskConfig = TaskConfig . builder ( ) . host ( host ) . job ( job ) . ports ( ports ) . envVars ( envVars ) . containerDecorators ( containerDecorators ) . namespace ( namespace ) . defaultRegistrationDomain ( defaultRegistrationDomain ) . dns ( dns ) . build ( ) ; final TaskStatus . Builder taskStatus = TaskStatus . newBuilder ( ) . setJob ( job ) . setEnv ( taskConfig . containerEnv ( ) ) . setPorts ( taskConfig . ports ( ) ) ; final StatusUpdater statusUpdater = new DefaultStatusUpdater ( model , taskStatus ) ; final FlapController flapController = FlapController . create ( ) ; final TaskMonitor taskMonitor = new TaskMonitor ( job . getId ( ) , flapController , statusUpdater ) ; final HealthChecker healthChecker = HealthCheckerFactory . create ( taskConfig , dockerClient , dockerHost , agentRunningInContainer ) ; final TaskRunnerFactory runnerFactory = TaskRunnerFactory . builder ( ) . config ( taskConfig ) . registrar ( registrar ) . dockerClient ( dockerClient ) . healthChecker ( healthChecker ) . listener ( taskMonitor ) . build ( ) ; return Supervisor . newBuilder ( ) . setJob ( job ) . setExistingContainerId ( existingContainerId ) . setDockerClient ( dockerClient ) . setRestartPolicy ( policy ) . setMetrics ( metrics ) . setListener ( listener ) . setRunnerFactory ( runnerFactory ) . setStatusUpdater ( statusUpdater ) . setMonitor ( taskMonitor ) . build ( ) ; } | Create a new application container . |
31,544 | private boolean updateThrottle ( ) { final ThrottleState newThrottle ; final boolean flapping = flapController . isFlapping ( ) ; if ( imageFailure != null ) { newThrottle = imageFailure ; } else { newThrottle = flapping ? FLAPPING : NO ; } final boolean updated ; if ( ! Objects . equals ( throttle , newThrottle ) ) { log . info ( "throttle state change: {}: {} -> {}" , jobId , throttle , newThrottle ) ; throttle = newThrottle ; statusUpdater . setThrottleState ( throttle ) ; updated = true ; } else { updated = false ; } if ( flapping ) { if ( flapTimeout != null ) { flapTimeout . cancel ( false ) ; } flapTimeout = scheduler . schedule ( new UpdateThrottle ( ) , flapController . millisLeftToUnflap ( ) , MILLISECONDS ) ; } return updated ; } | Derive a new throttle state and propagate it if needed . If flapping schedule a future check to see if we re still flapping and potentially reset the flapping state . |
31,545 | private void updateState ( final TaskStatus . State state ) { statusUpdater . setState ( state ) ; try { statusUpdater . update ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } | Propagate a new task state by setting it and committing the status update . |
31,546 | protected static < T > List < T > validateArgument ( List < T > list , Predicate < T > predicate , Function < T , String > msgFn ) { final Optional < T > firstInvalid = list . stream ( ) . filter ( predicate . negate ( ) ) . findAny ( ) ; if ( firstInvalid . isPresent ( ) ) { throw new IllegalArgumentException ( firstInvalid . map ( msgFn ) . get ( ) ) ; } return list ; } | Verifies that all entries in the Collection satisfy the predicate . If any do not throw an IllegalArgumentException with the specified message for the first invalid entry . |
31,547 | private Set < String > validateJobImage ( final String image ) { final Set < String > errors = Sets . newHashSet ( ) ; if ( image == null ) { errors . add ( "Image was not specified." ) ; } else { validateImageReference ( image , errors ) ; } return errors ; } | Validate the Job s image by checking it s not null or empty and has the right format . |
31,548 | private Set < String > validateJobId ( final Job job ) { final Set < String > errors = Sets . newHashSet ( ) ; final JobId jobId = job . getId ( ) ; if ( jobId == null ) { errors . add ( "Job id was not specified." ) ; return errors ; } final String jobIdVersion = jobId . getVersion ( ) ; final String jobIdHash = jobId . getHash ( ) ; final JobId recomputedId = job . toBuilder ( ) . build ( ) . getId ( ) ; errors . addAll ( validateJobName ( jobId , recomputedId ) ) ; errors . addAll ( validateJobVersion ( jobIdVersion , recomputedId ) ) ; if ( this . shouldValidateJobHash ) { errors . addAll ( validateJobHash ( jobIdHash , recomputedId ) ) ; } return errors ; } | Validate the Job s JobId by checking name version and hash are not null or empty don t contain invalid characters . |
31,549 | private Set < String > validateJobHealthCheck ( final Job job ) { final HealthCheck healthCheck = job . getHealthCheck ( ) ; if ( healthCheck == null ) { return emptySet ( ) ; } final Set < String > errors = Sets . newHashSet ( ) ; if ( healthCheck instanceof ExecHealthCheck ) { final List < String > command = ( ( ExecHealthCheck ) healthCheck ) . getCommand ( ) ; if ( command == null || command . isEmpty ( ) ) { errors . add ( "A command must be defined for `docker exec`-based health checks." ) ; } } else if ( healthCheck instanceof HttpHealthCheck || healthCheck instanceof TcpHealthCheck ) { final String port ; if ( healthCheck instanceof HttpHealthCheck ) { port = ( ( HttpHealthCheck ) healthCheck ) . getPort ( ) ; } else { port = ( ( TcpHealthCheck ) healthCheck ) . getPort ( ) ; } final Map < String , PortMapping > ports = job . getPorts ( ) ; if ( isNullOrEmpty ( port ) ) { errors . add ( "A port must be defined for HTTP and TCP health checks." ) ; } else if ( ! ports . containsKey ( port ) ) { errors . add ( format ( "Health check port '%s' not defined in the job. Known ports are '%s'" , port , Joiner . on ( ", " ) . join ( ports . keySet ( ) ) ) ) ; } } return errors ; } | Validate the Job s health check . |
31,550 | private Set < String > validateJobNetworkMode ( final Job job ) { final String networkMode = job . getNetworkMode ( ) ; if ( networkMode == null ) { return emptySet ( ) ; } final Set < String > errors = Sets . newHashSet ( ) ; if ( ! VALID_NETWORK_MODES . contains ( networkMode ) && ! networkMode . startsWith ( "container:" ) ) { errors . add ( String . format ( "A Docker container's network mode must be %s, or container:<name|id>." , Joiner . on ( ", " ) . join ( VALID_NETWORK_MODES ) ) ) ; } return errors ; } | Validate the Job s network mode . |
31,551 | private Set < String > validateAddCapabilities ( final Job job ) { final Set < String > caps = job . getAddCapabilities ( ) ; if ( caps == null ) { return emptySet ( ) ; } final Set < String > errors = Sets . newHashSet ( ) ; final Set < String > disallowedCaps = Sets . difference ( caps , whitelistedCapabilities ) ; if ( ! disallowedCaps . isEmpty ( ) ) { errors . add ( String . format ( "The following Linux capabilities aren't allowed by the Helios master: '%s'. " + "The allowed capabilities are: '%s'." , Joiner . on ( ", " ) . join ( disallowedCaps ) , Joiner . on ( ", " ) . join ( whitelistedCapabilities ) ) ) ; } return errors ; } | Validate the Job s added Linux capabilities . |
31,552 | private static ClassLoader pluginClassLoader ( final Path plugin , final ClassLoader environment , final ClassLoader parent ) { final URL url ; try { url = plugin . toFile ( ) . toURI ( ) . toURL ( ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( "Failed to load plugin jar " + plugin , e ) ; } final ClassLoader providedClassLoader = new FilteringClassLoader ( PROVIDED , environment , parent ) ; return new URLClassLoader ( new URL [ ] { url } , providedClassLoader ) ; } | Create a class loader for a plugin jar . |
31,553 | public boolean unregister ( ) { if ( serviceRegistrationHandle . isPresent ( ) ) { registrar . unregister ( serviceRegistrationHandle . get ( ) ) ; serviceRegistrationHandle = Optional . absent ( ) ; return true ; } return false ; } | Unregister a set of service endpoints previously registered . |
31,554 | public void stop ( ) throws InterruptedException { final String container = containerId . or ( containerName ) ; stopAsync ( ) . awaitTerminated ( ) ; if ( System . getenv ( "CONTAINER_STATS" ) != null ) { try { log . info ( "container {} stats: {}" , containerName , docker . stats ( containerName ) ) ; } catch ( DockerException e ) { log . warn ( "Could not log container stats. Exception was {}" , e ) ; } } try { docker . stopContainer ( container , secondsToWaitBeforeKill ) ; } catch ( DockerException e ) { if ( ( e instanceof ContainerNotFoundException ) && ! containerId . isPresent ( ) ) { } else { log . warn ( "Stopping container {} failed" , container , e ) ; } } } | Stops this container . |
31,555 | private < T > T nullableWithFallback ( final T first , final T second ) { return first != null ? first : second ; } | Return first argument if not null . Otherwise return second argument . |
31,556 | public < K , V > Optional < KafkaProducer < K , V > > getProducer ( final Serializer < K > keySerializer , final Serializer < V > valueSerializer ) { try { return partialConfigs . map ( input -> new KafkaProducer < > ( input , keySerializer , valueSerializer ) ) ; } catch ( final Exception e ) { log . warn ( "error while generating KafkaProducer - {}" , e ) ; return Optional . empty ( ) ; } } | Returns a producer with customized serializers for keys and values . |
31,557 | private Supervisor createSupervisor ( final Job job , final Map < String , Integer > portAllocation ) { log . debug ( "creating job supervisor: {}" , job ) ; final TaskStatus taskStatus = model . getTaskStatus ( job . getId ( ) ) ; final String containerId = ( taskStatus == null ) ? null : taskStatus . getContainerId ( ) ; final Supervisor supervisor = supervisorFactory . create ( job , containerId , portAllocation , supervisorListener ) ; supervisors . put ( job . getId ( ) , supervisor ) ; return supervisor ; } | Create a job supervisor . |
31,558 | public static FastForwardReporter create ( MetricRegistry registry , Optional < HostAndPort > address , String metricKey , int intervalSeconds ) throws SocketException , UnknownHostException { return create ( registry , address , metricKey , intervalSeconds , Collections :: emptyMap ) ; } | Create a new FastForwardReporter instance . |
31,559 | public ListenableFuture < List < String > > listHosts ( final String namePattern ) { return listHosts ( ImmutableMultimap . of ( "namePattern" , namePattern ) ) ; } | Returns a list of all hosts registered in the Helios cluster whose name matches the given pattern . |
31,560 | public ListenableFuture < Map < JobId , Job > > jobs ( final String jobQuery ) { return jobs ( jobQuery , null ) ; } | Lists all jobs in the cluster whose name starts with the given string . |
31,561 | public ListenableFuture < Map < JobId , Job > > jobs ( final String jobQuery , final String hostNamePattern ) { final Map < String , String > params = new HashMap < > ( ) ; if ( ! Strings . isNullOrEmpty ( jobQuery ) ) { params . put ( "q" , jobQuery ) ; } if ( ! Strings . isNullOrEmpty ( hostNamePattern ) ) { params . put ( "hostPattern" , hostNamePattern ) ; } return get ( uri ( "/jobs" , params ) , jobIdMap ) ; } | Lists all jobs in the cluster whose name starts with the given string and that are deployed to hosts that match the given name pattern . |
31,562 | public static HeliosClient create ( final String domain , final String user ) { return HeliosClient . newBuilder ( ) . setDomain ( domain ) . setUser ( user ) . build ( ) ; } | Create a new helios client as a specific user connecting to a helios master cluster in a specific domain . |
31,563 | public static ServiceRegistrar createServiceRegistrar ( final Path path , final String address , final String domain ) { final ServiceRegistrarFactory factory ; if ( path == null ) { factory = createFactory ( ) ; } else { factory = createFactory ( path ) ; } if ( address != null ) { log . info ( "Creating service registrar with address: {}" , address ) ; return factory . create ( address ) ; } else if ( ! Strings . isNullOrEmpty ( domain ) ) { log . info ( "Creating service registrar for domain: {}" , domain ) ; return domain . equals ( "localhost" ) ? factory . create ( "tcp://localhost:4999" ) : factory . createForDomain ( domain ) ; } else { log . info ( "No address nor domain configured, not creating service registrar." ) ; return new NopServiceRegistrar ( ) ; } } | Create a registrar . Attempts to load it from a plugin if path is not null or using the app class loader otherwise . If no registrar plugin was found returns a nop registrar . |
31,564 | private static ServiceRegistrarFactory createFactory ( final Path path ) { final ServiceRegistrarFactory factory ; final Path absolutePath = path . toAbsolutePath ( ) ; try { factory = ServiceRegistrarLoader . load ( absolutePath ) ; final String name = factory . getClass ( ) . getName ( ) ; log . info ( "Loaded service registrar plugin: {} ({})" , name , absolutePath ) ; } catch ( ServiceRegistrarLoadingException e ) { throw new RuntimeException ( "Unable to load service registrar plugin: " + absolutePath , e ) ; } return factory ; } | Get a registrar factory from a plugin . |
31,565 | private static ServiceRegistrarFactory createFactory ( ) { final ServiceRegistrarFactory factory ; final ServiceRegistrarFactory installed ; try { installed = ServiceRegistrarLoader . load ( ) ; } catch ( ServiceRegistrarLoadingException e ) { throw new RuntimeException ( "Unable to load service registrar" , e ) ; } if ( installed == null ) { log . debug ( "No service registrar plugin configured" ) ; factory = new NopServiceRegistrarFactory ( ) ; } else { factory = installed ; final String name = factory . getClass ( ) . getName ( ) ; log . info ( "Loaded installed service registrar: {}" , name ) ; } return factory ; } | Get a registrar factory from the application class loader . |
31,566 | @ Produces ( TEXT_PLAIN ) public String version ( ) { return String . format ( "\"%s\"" , Version . POM_VERSION ) ; } | Returns the server version string . |
31,567 | @ Path ( "/check" ) @ Produces ( APPLICATION_JSON ) public VersionCheckResponse versionCheck ( @ QueryParam ( "client" ) @ DefaultValue ( "" ) final String client ) { final PomVersion serverVersion = PomVersion . parse ( Version . POM_VERSION ) ; final VersionCompatibility . Status status ; if ( isNullOrEmpty ( client ) ) { return new VersionCheckResponse ( VersionCompatibility . Status . MISSING , serverVersion , Version . RECOMMENDED_VERSION ) ; } final PomVersion clientVersion = PomVersion . parse ( client ) ; status = VersionCompatibility . getStatus ( serverVersion , clientVersion ) ; return new VersionCheckResponse ( status , serverVersion , Version . RECOMMENDED_VERSION ) ; } | Given the client version returns the version status i . e . whether or not they should be compatible or not . |
31,568 | public String containerName ( ) { final String shortId = job . getId ( ) . toShortString ( ) ; final String escaped = CONTAINER_NAME_FORBIDDEN . matcher ( shortId ) . replaceAll ( "_" ) ; final String random = Integer . toHexString ( new SecureRandom ( ) . nextInt ( ) ) ; return namespace + "-" + escaped + "_" + random ; } | Generate a random container name . |
31,569 | public ContainerConfig containerConfig ( final ImageInfo imageInfo , final Optional < String > dockerVersion ) { final ContainerConfig . Builder builder = ContainerConfig . builder ( ) ; builder . image ( job . getImage ( ) ) ; builder . cmd ( job . getCommand ( ) ) ; builder . hostname ( job . getHostname ( ) ) ; builder . env ( containerEnvStrings ( ) ) ; builder . exposedPorts ( containerExposedPorts ( ) ) ; builder . volumes ( volumes ( ) . keySet ( ) ) ; builder . labels ( job . getLabels ( ) ) ; for ( final ContainerDecorator decorator : containerDecorators ) { decorator . decorateContainerConfig ( job , imageInfo , dockerVersion , builder ) ; } return builder . build ( ) ; } | Create docker container configuration for a job . |
31,570 | public Map < String , PortMapping > ports ( ) { final ImmutableMap . Builder < String , PortMapping > builder = ImmutableMap . builder ( ) ; for ( final Map . Entry < String , PortMapping > e : job . getPorts ( ) . entrySet ( ) ) { final PortMapping mapping = e . getValue ( ) ; builder . put ( e . getKey ( ) , mapping . hasExternalPort ( ) ? mapping : mapping . withExternalPort ( checkNotNull ( ports . get ( e . getKey ( ) ) ) ) ) ; } return builder . build ( ) ; } | Get final port mappings using allocated ports . |
31,571 | public Map < String , String > containerEnv ( ) { final Map < String , String > env = Maps . newHashMap ( envVars ) ; for ( final Entry < String , Integer > entry : ports . entrySet ( ) ) { env . put ( "HELIOS_PORT_" + entry . getKey ( ) , host + ":" + entry . getValue ( ) ) ; } env . putAll ( job . getEnv ( ) ) ; return env ; } | Get environment variables for the container . |
31,572 | private ServiceRegistration . EndpointHealthCheck endpointHealthCheck ( String portName ) { if ( healthCheck ( ) instanceof HttpHealthCheck ) { final HttpHealthCheck httpHealthCheck = ( HttpHealthCheck ) healthCheck ( ) ; if ( portName . equals ( httpHealthCheck . getPort ( ) ) ) { return ServiceRegistration . EndpointHealthCheck . newHttpCheck ( httpHealthCheck . getPath ( ) ) ; } } else if ( healthCheck ( ) instanceof TcpHealthCheck ) { if ( portName . equals ( ( ( TcpHealthCheck ) healthCheck ( ) ) . getPort ( ) ) ) { return ServiceRegistration . EndpointHealthCheck . newTcpCheck ( ) ; } } return null ; } | Get endpoint health check for a given port . |
31,573 | private String fullyQualifiedRegistrationDomain ( ) { if ( job . getRegistrationDomain ( ) . endsWith ( "." ) ) { return job . getRegistrationDomain ( ) ; } else if ( "" . equals ( job . getRegistrationDomain ( ) ) ) { return defaultRegistrationDomain ; } else { return job . getRegistrationDomain ( ) + "." + defaultRegistrationDomain ; } } | Given the registration domain in the job and the default registration domain for the agent figure out what domain we should actually register the job in . |
31,574 | private Set < String > containerExposedPorts ( ) { final Set < String > ports = Sets . newHashSet ( ) ; for ( final Map . Entry < String , PortMapping > entry : job . getPorts ( ) . entrySet ( ) ) { final PortMapping mapping = entry . getValue ( ) ; ports . add ( containerPort ( mapping . getInternalPort ( ) , mapping . getProtocol ( ) ) ) ; } return ports ; } | Create container port exposure configuration for a job . |
31,575 | private List < String > containerEnvStrings ( ) { final Map < String , String > env = containerEnv ( ) ; final List < String > envList = Lists . newArrayList ( ) ; for ( final Map . Entry < String , String > entry : env . entrySet ( ) ) { envList . add ( entry . getKey ( ) + '=' + entry . getValue ( ) ) ; } return envList ; } | Compute docker container environment variables . |
31,576 | private Map < String , List < PortBinding > > portBindings ( ) { final Map < String , List < PortBinding > > bindings = Maps . newHashMap ( ) ; for ( final Map . Entry < String , PortMapping > e : job . getPorts ( ) . entrySet ( ) ) { final PortMapping mapping = e . getValue ( ) ; final Integer jobDefinedExtPort = mapping . getExternalPort ( ) ; final String externalPort = jobDefinedExtPort == null ? ports . get ( e . getKey ( ) ) . toString ( ) : jobDefinedExtPort . toString ( ) ; final PortBinding binding = PortBinding . of ( mapping . getIp ( ) , externalPort ) ; final String entry = containerPort ( mapping . getInternalPort ( ) , mapping . getProtocol ( ) ) ; bindings . put ( entry , Collections . singletonList ( binding ) ) ; } return bindings ; } | Create a port binding configuration for the job . |
31,577 | public HostConfig hostConfig ( final Optional < String > dockerVersion ) { final List < String > securityOpt = job . getSecurityOpt ( ) ; final HostConfig . Builder builder = HostConfig . builder ( ) . binds ( binds ( ) ) . portBindings ( portBindings ( ) ) . dns ( dns ) . securityOpt ( securityOpt . toArray ( new String [ securityOpt . size ( ) ] ) ) . runtime ( job . getRuntime ( ) ) . networkMode ( job . getNetworkMode ( ) ) ; if ( ! job . getRamdisks ( ) . isEmpty ( ) ) { builder . tmpfs ( job . getRamdisks ( ) ) ; } final Resources resources = job . getResources ( ) ; if ( resources != null ) { builder . memory ( resources . getMemory ( ) ) ; builder . memorySwap ( resources . getMemorySwap ( ) ) ; builder . cpusetCpus ( resources . getCpuset ( ) ) ; builder . cpuShares ( resources . getCpuShares ( ) ) ; } builder . capAdd ( ImmutableList . copyOf ( job . getAddCapabilities ( ) ) ) ; builder . capDrop ( ImmutableList . copyOf ( job . getDropCapabilities ( ) ) ) ; for ( final ContainerDecorator decorator : containerDecorators ) { decorator . decorateHostConfig ( job , dockerVersion , builder ) ; } return builder . build ( ) ; } | Create a container host configuration for the job . |
31,578 | private Map < String , Map > volumes ( ) { final ImmutableMap . Builder < String , Map > volumes = ImmutableMap . builder ( ) ; for ( final Map . Entry < String , String > entry : job . getVolumes ( ) . entrySet ( ) ) { final String path = entry . getKey ( ) ; final String source = entry . getValue ( ) ; if ( Strings . isNullOrEmpty ( source ) ) { volumes . put ( path , new HashMap ( ) ) ; } } return volumes . build ( ) ; } | Get container volumes . |
31,579 | private List < String > binds ( ) { final ImmutableList . Builder < String > binds = ImmutableList . builder ( ) ; for ( final Map . Entry < String , String > entry : job . getVolumes ( ) . entrySet ( ) ) { final String path = entry . getKey ( ) ; final String source = entry . getValue ( ) ; if ( Strings . isNullOrEmpty ( source ) ) { continue ; } binds . add ( source + ":" + path ) ; } return binds . build ( ) ; } | Get container bind mount volumes . |
31,580 | @ Path ( "{id}" ) @ Produces ( APPLICATION_JSON ) public HostDeregisterResponse delete ( @ PathParam ( "id" ) final String host ) { try { model . deregisterHost ( host ) ; return new HostDeregisterResponse ( HostDeregisterResponse . Status . OK , host ) ; } catch ( HostNotFoundException e ) { throw notFound ( new HostDeregisterResponse ( HostDeregisterResponse . Status . NOT_FOUND , host ) ) ; } catch ( HostStillInUseException e ) { throw badRequest ( new HostDeregisterResponse ( HostDeregisterResponse . Status . JOBS_STILL_DEPLOYED , host ) ) ; } } | Deregisters the host from the cluster . Will delete just about everything the cluster knows about it . |
31,581 | @ Path ( "{id}/status" ) @ Produces ( APPLICATION_JSON ) public Optional < HostStatus > hostStatus ( @ PathParam ( "id" ) final String host , @ QueryParam ( "status" ) @ DefaultValue ( "" ) final String statusFilter ) { final HostStatus status = model . getHostStatus ( host ) ; final Optional < HostStatus > response ; if ( status != null && ( isNullOrEmpty ( statusFilter ) || statusFilter . equals ( status . getStatus ( ) . toString ( ) ) ) ) { response = Optional . of ( status ) ; } else { response = Optional . absent ( ) ; } log . debug ( "hostStatus: host={}, statusFilter={}, returning: {}" , host , statusFilter , response ) ; return response ; } | Returns various status information about the host . |
31,582 | @ Path ( "/statuses" ) @ Produces ( APPLICATION_JSON ) public Map < String , HostStatus > hostStatuses ( final List < String > hosts , @ QueryParam ( "status" ) @ DefaultValue ( "" ) final String statusFilter ) { final Map < String , HostStatus > statuses = Maps . newHashMap ( ) ; for ( final String host : hosts ) { final HostStatus status = model . getHostStatus ( host ) ; if ( status != null ) { if ( isNullOrEmpty ( statusFilter ) || statusFilter . equals ( status . getStatus ( ) . toString ( ) ) ) { statuses . put ( host , status ) ; } } } return statuses ; } | Returns various status information about the hosts . |
31,583 | @ Path ( "/{host}/jobs/{job}" ) @ Produces ( APPLICATION_JSON ) public SetGoalResponse jobPatch ( @ PathParam ( "host" ) final String host , @ PathParam ( "job" ) final JobId jobId , final Deployment deployment , @ QueryParam ( "token" ) @ DefaultValue ( "" ) final String token ) { if ( ! deployment . getJobId ( ) . equals ( jobId ) ) { throw badRequest ( new SetGoalResponse ( SetGoalResponse . Status . ID_MISMATCH , host , jobId ) ) ; } try { model . updateDeployment ( host , deployment , token ) ; } catch ( HostNotFoundException e ) { throw notFound ( new SetGoalResponse ( SetGoalResponse . Status . HOST_NOT_FOUND , host , jobId ) ) ; } catch ( JobNotDeployedException e ) { throw notFound ( new SetGoalResponse ( SetGoalResponse . Status . JOB_NOT_DEPLOYED , host , jobId ) ) ; } catch ( TokenVerificationException e ) { throw forbidden ( new SetGoalResponse ( SetGoalResponse . Status . FORBIDDEN , host , jobId ) ) ; } log . info ( "patched job {} on host {}" , deployment , host ) ; return new SetGoalResponse ( SetGoalResponse . Status . OK , host , jobId ) ; } | Alters the current deployment of a deployed job identified by its job id on the specified host . |
31,584 | @ Path ( "{id}" ) @ Produces ( APPLICATION_JSON ) public JobDeleteResponse delete ( @ PathParam ( "id" ) final JobId id , @ QueryParam ( "token" ) @ DefaultValue ( "" ) final String token ) { if ( ! id . isFullyQualified ( ) ) { throw badRequest ( "Invalid id" ) ; } try { model . removeJob ( id , token ) ; return new JobDeleteResponse ( JobDeleteResponse . Status . OK ) ; } catch ( JobDoesNotExistException e ) { throw notFound ( new JobDeleteResponse ( JobDeleteResponse . Status . JOB_NOT_FOUND ) ) ; } catch ( JobStillDeployedException e ) { throw badRequest ( new JobDeleteResponse ( JobDeleteResponse . Status . STILL_IN_USE ) ) ; } catch ( TokenVerificationException e ) { throw forbidden ( new JobDeleteResponse ( JobDeleteResponse . Status . FORBIDDEN ) ) ; } } | Deletes the job specified by the given id . |
31,585 | @ Path ( "{id}/status" ) @ Produces ( APPLICATION_JSON ) public Optional < JobStatus > statusGet ( @ PathParam ( "id" ) final JobId id ) { if ( ! id . isFullyQualified ( ) ) { throw badRequest ( "Invalid id" ) ; } return Optional . fromNullable ( model . getJobStatus ( id ) ) ; } | Returns the job status for the given job id . The job status includes things like where it s deployed and the status of the jobs where it s deployed etc . |
31,586 | private static int parseTimeout ( final Namespace options , final String dest , final String envVarName , final int defaultValue ) { if ( options . getInt ( dest ) != null ) { return options . getInt ( dest ) ; } if ( System . getenv ( envVarName ) != null ) { return Integer . parseInt ( System . getenv ( envVarName ) ) ; } return defaultValue ; } | Return the timeout value to use first checking the argument provided to the CLI invocation then an environment variable then the default value . |
31,587 | public static int setGoalOnHosts ( final HeliosClient client , final PrintStream out , final boolean json , final List < String > hosts , final Deployment deployment , final String token ) throws InterruptedException , ExecutionException { int code = 0 ; for ( final String host : hosts ) { if ( ! json ) { out . printf ( "%s: " , host ) ; } final SetGoalResponse result = client . setGoal ( deployment , host , token ) . get ( ) ; if ( result . getStatus ( ) == SetGoalResponse . Status . OK ) { if ( json ) { out . print ( result . toJsonString ( ) ) ; } else { out . printf ( "done%n" ) ; } } else { if ( json ) { out . print ( result . toJsonString ( ) ) ; } else { out . printf ( "failed: %s%n" , result ) ; } code = 1 ; } } return code ; } | shared between JobStartCommand and JobStopCommand |
31,588 | public static byte [ ] asBytesUnchecked ( final Object value ) { try { return OBJECT_MAPPER . writeValueAsBytes ( value ) ; } catch ( JsonProcessingException e ) { throw new RuntimeException ( e ) ; } } | Serialize an object to json . Use when object is expected to be json serializable . |
31,589 | public static String asNormalizedStringUnchecked ( final Object value ) { try { return asNormalizedString ( value ) ; } catch ( JsonProcessingException e ) { throw new RuntimeException ( e ) ; } } | Serialize an object to a json string ordering fields and omitting null and empty fields . Use when object is expected to be json serializable . |
31,590 | public int [ ] asArray ( ) { int arr [ ] = new int [ size ( ) ] ; OrdinalIterator iter = iterator ( ) ; int ordinal = iter . nextOrdinal ( ) ; int i = 0 ; while ( ordinal != NO_MORE_ORDINALS ) { arr [ i ++ ] = ordinal ; ordinal = iter . nextOrdinal ( ) ; } return arr ; } | Returns an array containing all elements in the set . |
31,591 | private void ensureCapacity ( int segmentIndex ) { while ( segmentIndex >= segments . length ) { segments = Arrays . copyOf ( segments , segments . length * 3 / 2 ) ; } long numSegmentsPopulated = length >> log2OfSegmentSize ; for ( long i = numSegmentsPopulated ; i <= segmentIndex ; i ++ ) { segments [ ( int ) i ] = memoryPool . getSegment ( ) ; length += 1 << log2OfSegmentSize ; } } | Ensures that the segment at segmentIndex exists |
31,592 | public int getConnection ( String nodeType , int ordinal , String propertyName ) { return getConnection ( 0 , nodeType , ordinal , propertyName ) ; } | Retrieve a single connected ordinal given the type and ordinal of the originating node and the property by which this node is connected . |
31,593 | public int getConnection ( String connectionModel , String nodeType , int ordinal , String propertyName ) { int connectionModelIndex = modelHolder . getModelIndex ( connectionModel ) ; return getConnection ( connectionModelIndex , nodeType , ordinal , propertyName ) ; } | Retrieve a single connected ordinal in a given connection model given the type and ordinal of the originating node and the property by which this node is connected . |
31,594 | public void write ( ByteArrayBuffer buf ) { data . copy ( buf . data , 0 , pointer , buf . length ( ) ) ; pointer += buf . length ( ) ; } | Copies the contents of the specified buffer into this buffer at the current position . |
31,595 | public void writeVInt ( int value ) { if ( value < 0 ) { writeByte ( ( byte ) 0x80 ) ; return ; } if ( value > 0x0FFFFFFF ) writeByte ( ( byte ) ( 0x80 | ( ( value >>> 28 ) ) ) ) ; if ( value > 0x1FFFFF ) writeByte ( ( byte ) ( 0x80 | ( ( value >>> 21 ) & 0x7F ) ) ) ; if ( value > 0x3FFF ) writeByte ( ( byte ) ( 0x80 | ( ( value >>> 14 ) & 0x7F ) ) ) ; if ( value > 0x7F ) writeByte ( ( byte ) ( 0x80 | ( ( value >>> 7 ) & 0x7F ) ) ) ; writeByte ( ( byte ) ( value & 0x7F ) ) ; } | Writes a variable - byte encoded integer to the byte array . |
31,596 | public void write ( byte [ ] data ) { for ( int i = 0 ; i < data . length ; i ++ ) { writeByte ( data [ i ] ) ; } } | Writes each byte of data in order . |
31,597 | public < R > AnimaQuery < T > exclude ( TypeFunction < T , R > ... functions ) { String [ ] columnNames = Arrays . stream ( functions ) . map ( AnimaUtils :: getLambdaColumnName ) . collect ( toList ( ) ) . toArray ( new String [ functions . length ] ) ; return this . exclude ( columnNames ) ; } | Excluded columns by lambda |
31,598 | public AnimaQuery < T > select ( String columns ) { if ( null != this . selectColumns ) { throw new AnimaException ( "Select method can only be called once." ) ; } this . selectColumns = columns ; return this ; } | Sets the query to specify the column . |
31,599 | public < R > AnimaQuery < T > where ( TypeFunction < T , R > function ) { String columnName = AnimaUtils . getLambdaColumnName ( function ) ; conditionSQL . append ( " AND " ) . append ( columnName ) ; return this ; } | Set the column name using lambda |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.