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 + appen...
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" ) ; r...
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 ( counter...
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 ( ) ) { updateC...
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 , ...
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...
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 ( )...
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 . startsWi...
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 . ...
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 ( ) ; operat...
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 ( firstNonNu...
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 ( "# ---------------------------------------------------------------" ...
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 nod...
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 ) { ...
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 ) {...
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 : ...
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 ( "addJo...
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 ...
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 ( ) ...
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 . ensur...
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 (...
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...
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 ) ...
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"...
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 por...
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 . ...
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 ...
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 = Confi...
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 ) . p...
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 ) ) { ...
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 ( firstI...
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...
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 = ( ( Exec...
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 ( "contai...
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 ) ; i...
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 ) ; } fin...
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 ( Docke...
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 whi...
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 (...
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 ....
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 regis...
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 servic...
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...
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 ...
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 ( ) ) ; buil...
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 ...
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 ( ) ) ; retu...
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 . Endpoint...
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 ( ) + "." + defaultReg...
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 ...
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 envL...
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 = mapp...
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 Stri...
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 ....
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 . isNullOrEmpt...
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 HostD...
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 ; ...
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 ) { fi...
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 ( ) . eq...
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 J...
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 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 ...
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 ] = m...
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 |...
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