comment stringlengths 1 45k | method_body stringlengths 23 281k | target_code stringlengths 0 5.16k | method_body_after stringlengths 12 281k | context_before stringlengths 8 543k | context_after stringlengths 8 543k |
|---|---|---|---|---|---|
We should make deployment fail on failed role creation. | public ActivateResult deploy2(JobId job, boolean deploySourceVersions) {
if (job.application().instance().isTester())
throw new IllegalArgumentException("'" + job.application() + "' is a tester application!");
TenantAndApplicationId applicationId = TenantAndApplicationId.from(job.application());
ZoneId zone = job.type().zone(controller.system());
try (Lock deploymentLock = lockForDeployment(job.application(), zone)) {
Set<ContainerEndpoint> endpoints;
Optional<EndpointCertificateMetadata> endpointCertificateMetadata;
Optional<ApplicationRoles> applicationRoles = Optional.empty();
Run run = controller.jobController().last(job)
.orElseThrow(() -> new IllegalStateException("No known run of '" + job + "'"));
if (run.hasEnded())
throw new IllegalStateException("No deployment expected for " + job + " now, as no job is running");
Version platform = run.versions().sourcePlatform().filter(__ -> deploySourceVersions).orElse(run.versions().targetPlatform());
ApplicationVersion revision = run.versions().sourceApplication().filter(__ -> deploySourceVersions).orElse(run.versions().targetApplication());
ApplicationPackage applicationPackage = getApplicationPackage(job.application(), zone, revision);
try (Lock lock = lock(applicationId)) {
LockedApplication application = new LockedApplication(requireApplication(applicationId), lock);
Instance instance = application.get().require(job.application().instance());
Deployment deployment = instance.deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platform.compareTo(deployment.version()) < 0 && ! instance.change().isPinned()
|| revision.compareTo(deployment.applicationVersion()) < 0 && ! (revision.isUnknown() && controller.system().isCd())))
throw new IllegalArgumentException(String.format("Rejecting deployment of application %s to %s, as the requested versions (platform: %s, application: %s)" +
" are older than the currently deployed (platform: %s, application: %s).",
job.application(), zone, platform, revision, deployment.version(), deployment.applicationVersion()));
if ( ! applicationPackage.trustedCertificates().isEmpty()
&& run.testerCertificate().isPresent())
applicationPackage = applicationPackage.withTrustedCertificate(run.testerCertificate().get());
endpointCertificateMetadata = endpointCertificateManager.getEndpointCertificateMetadata(instance, zone);
endpoints = controller.routing().registerEndpointsInDns(application.get(), job.application().instance(), zone);
if (provisionApplicationRoles.with(FetchVector.Dimension.ZONE_ID, zone.value()).value()) {
try {
applicationRoles = controller.serviceRegistry().applicationRoleService().createApplicationRoles(instance.id());
} catch (Exception e) {
log.log(Level.SEVERE, "Exception creating application roles for application: " + instance.id(), e);
}
}
}
ActivateResult result = deploy(job.application(), applicationPackage, zone, platform, endpoints, endpointCertificateMetadata, applicationRoles);
lockApplicationOrThrow(applicationId, application ->
store(application.with(job.application().instance(),
instance -> instance.withNewDeployment(zone, revision, platform,
clock.instant(), warningsFrom(result)))));
return result;
}
} | log.log(Level.SEVERE, "Exception creating application roles for application: " + instance.id(), e); | public ActivateResult deploy2(JobId job, boolean deploySourceVersions) {
if (job.application().instance().isTester())
throw new IllegalArgumentException("'" + job.application() + "' is a tester application!");
TenantAndApplicationId applicationId = TenantAndApplicationId.from(job.application());
ZoneId zone = job.type().zone(controller.system());
try (Lock deploymentLock = lockForDeployment(job.application(), zone)) {
Set<ContainerEndpoint> endpoints;
Optional<EndpointCertificateMetadata> endpointCertificateMetadata;
Optional<ApplicationRoles> applicationRoles = Optional.empty();
Run run = controller.jobController().last(job)
.orElseThrow(() -> new IllegalStateException("No known run of '" + job + "'"));
if (run.hasEnded())
throw new IllegalStateException("No deployment expected for " + job + " now, as no job is running");
Version platform = run.versions().sourcePlatform().filter(__ -> deploySourceVersions).orElse(run.versions().targetPlatform());
ApplicationVersion revision = run.versions().sourceApplication().filter(__ -> deploySourceVersions).orElse(run.versions().targetApplication());
ApplicationPackage applicationPackage = getApplicationPackage(job.application(), zone, revision);
try (Lock lock = lock(applicationId)) {
LockedApplication application = new LockedApplication(requireApplication(applicationId), lock);
Instance instance = application.get().require(job.application().instance());
Deployment deployment = instance.deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platform.compareTo(deployment.version()) < 0 && ! instance.change().isPinned()
|| revision.compareTo(deployment.applicationVersion()) < 0 && ! (revision.isUnknown() && controller.system().isCd())))
throw new IllegalArgumentException(String.format("Rejecting deployment of application %s to %s, as the requested versions (platform: %s, application: %s)" +
" are older than the currently deployed (platform: %s, application: %s).",
job.application(), zone, platform, revision, deployment.version(), deployment.applicationVersion()));
if ( ! applicationPackage.trustedCertificates().isEmpty()
&& run.testerCertificate().isPresent())
applicationPackage = applicationPackage.withTrustedCertificate(run.testerCertificate().get());
endpointCertificateMetadata = endpointCertificateManager.getEndpointCertificateMetadata(instance, zone);
endpoints = controller.routing().registerEndpointsInDns(application.get(), job.application().instance(), zone);
if (provisionApplicationRoles.with(FetchVector.Dimension.ZONE_ID, zone.value()).value()) {
try {
applicationRoles = controller.serviceRegistry().applicationRoleService().createApplicationRoles(instance.id());
} catch (Exception e) {
log.log(Level.SEVERE, "Exception creating application roles for application: " + instance.id(), e);
throw new RuntimeException("Unable to provision iam roles for application");
}
}
}
ActivateResult result = deploy(job.application(), applicationPackage, zone, platform, endpoints, endpointCertificateMetadata, applicationRoles);
lockApplicationOrThrow(applicationId, application ->
store(application.with(job.application().instance(),
instance -> instance.withNewDeployment(zone, revision, platform,
clock.instant(), warningsFrom(result)))));
return result;
}
} | class ApplicationController {
private static final Logger log = Logger.getLogger(ApplicationController.class.getName());
/** The controller owning this */
private final Controller controller;
/** For persistence */
private final CuratorDb curator;
private final ArtifactRepository artifactRepository;
private final ApplicationStore applicationStore;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final ApplicationPackageValidator applicationPackageValidator;
private final EndpointCertificateManager endpointCertificateManager;
private final StringFlag dockerImageRepoFlag;
private final BooleanFlag provisionApplicationRoles;
ApplicationController(Controller controller, CuratorDb curator, AccessControl accessControl, Clock clock,
SecretStore secretStore, FlagSource flagSource) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
this.dockerImageRepoFlag = Flags.DOCKER_IMAGE_REPO.bindTo(flagSource);
this.provisionApplicationRoles = Flags.PROVISION_APPLICATION_ROLES.bindTo(flagSource);
deploymentTrigger = new DeploymentTrigger(controller, clock);
applicationPackageValidator = new ApplicationPackageValidator(controller);
endpointCertificateManager = new EndpointCertificateManager(controller.zoneRegistry(), curator, secretStore,
controller.serviceRegistry().endpointCertificateProvider(), clock, flagSource);
Once.after(Duration.ofMinutes(1), () -> {
Instant start = clock.instant();
int count = 0;
for (TenantAndApplicationId id : curator.readApplicationIds()) {
lockApplicationIfPresent(id, application -> {
for (InstanceName instance : application.get().deploymentSpec().instanceNames())
if (!application.get().instances().containsKey(instance))
application = withNewInstance(application, id.instance(instance));
store(application);
});
count++;
}
log.log(Level.INFO, String.format("Wrote %d applications in %s", count,
Duration.between(start, clock.instant())));
});
}
/** Returns the application with the given id, or null if it is not present */
public Optional<Application> getApplication(TenantAndApplicationId id) {
return curator.readApplication(id);
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id)).flatMap(application -> application.get(id.instance()));
}
/**
* Returns the application with the given id
*
* @throws IllegalArgumentException if it does not exist
*/
public Application requireApplication(TenantAndApplicationId id) {
return getApplication(id).orElseThrow(() -> new IllegalArgumentException(id + " not found"));
}
/**
* Returns the instance with the given id
*
* @throws IllegalArgumentException if it does not exist
*/
public Instance requireInstance(ApplicationId id) {
return getInstance(id).orElseThrow(() -> new IllegalArgumentException(id + " not found"));
}
/** Returns a snapshot of all applications */
public List<Application> asList() {
return curator.readApplications(false);
}
/**
* Returns a snapshot of all readable applications. Unlike {@link ApplicationController
* applications that cannot currently be read (e.g. due to serialization issues) and may return an incomplete
* snapshot.
*
* This should only be used in cases where acting on a subset of applications is better than none.
*/
public List<Application> readable() {
return curator.readApplications(true);
}
/** Returns the ID of all known applications. */
public List<TenantAndApplicationId> idList() {
return curator.readApplicationIds();
}
/** Returns a snapshot of all applications of a tenant */
public List<Application> asList(TenantName tenant) {
return curator.readApplications(tenant);
}
public ArtifactRepository artifacts() { return artifactRepository; }
public ApplicationStore applicationStore() { return applicationStore; }
/** Returns all content clusters in all current deployments of the given application. */
public Map<ZoneId, List<String>> contentClustersByZone(Collection<DeploymentId> ids) {
Map<ZoneId, List<String>> clusters = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (DeploymentId id : ids)
clusters.put(id.zoneId(), List.copyOf(configServer.getContentClusters(id)));
return Collections.unmodifiableMap(clusters);
}
/** Returns the oldest Vespa version installed on any active or reserved production node for the given application. */
public Version oldestInstalledPlatform(TenantAndApplicationId id) {
return requireApplication(id).instances().values().stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream()
.flatMap(zone -> configServer.nodeRepository().list(zone,
id.instance(instance.name()),
EnumSet.of(active, reserved))
.stream())
.map(Node::currentVersion)
.filter(version -> ! version.isEmpty()))
.min(naturalOrder())
.orElse(controller.systemVersion());
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public Application createApplication(TenantAndApplicationId id, Credentials credentials) {
try (Lock lock = lock(id)) {
if (getApplication(id).isPresent())
throw new IllegalArgumentException("Could not create '" + id + "': Application already exists");
if (getApplication(dashToUnderscore(id)).isPresent())
throw new IllegalArgumentException("Could not create '" + id + "': Application " + dashToUnderscore(id) + " already exists");
com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId.validate(id.application().value());
if (controller.tenants().get(id.tenant()).isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
accessControl.createApplication(id, credentials);
LockedApplication locked = new LockedApplication(new Application(id, clock.instant()), lock);
store(locked);
log.info("Created " + locked);
return locked.get();
}
}
/**
* Creates a new instance for an existing application.
*
* @throws IllegalArgumentException if the instance already exists, or has an invalid instance name.
*/
public void createInstance(ApplicationId id) {
lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
store(withNewInstance(application, id));
});
}
public LockedApplication withNewInstance(LockedApplication application, ApplicationId id) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
InstanceId.validate(id.instance().value());
if (getInstance(id).isPresent())
throw new IllegalArgumentException("Could not create '" + id + "': Instance already exists");
if (getInstance(dashToUnderscore(id)).isPresent())
throw new IllegalArgumentException("Could not create '" + id + "': Instance " + dashToUnderscore(id) + " already exists");
log.info("Created " + id);
return application.withNewInstance(id.instance());
}
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options);
}
/** Deploys an application package for an existing application instance. */
private ApplicationPackage getApplicationPackage(ApplicationId application, ZoneId zone, ApplicationVersion revision) {
return new ApplicationPackage(revision.isUnknown() ? applicationStore.getDev(application, zone)
: applicationStore.get(application.tenant(), application.application(), revision));
}
public ActivateResult deploy(ApplicationId instanceId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
Optional<ApplicationVersion> applicationVersionFromDeployer,
DeployOptions options) {
if (instanceId.instance().isTester())
throw new IllegalArgumentException("'" + instanceId + "' is a tester application!");
TenantAndApplicationId applicationId = TenantAndApplicationId.from(instanceId);
if (getInstance(instanceId).isEmpty())
createInstance(instanceId);
try (Lock deploymentLock = lockForDeployment(instanceId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<EndpointCertificateMetadata> endpointCertificateMetadata;
try (Lock lock = lock(applicationId)) {
LockedApplication application = new LockedApplication(requireApplication(applicationId), lock);
InstanceName instance = instanceId.instance();
boolean manuallyDeployed = options.deployDirectly || zone.environment().isManuallyDeployed();
boolean preferOldestVersion = options.deployCurrentVersion;
if (manuallyDeployed) {
applicationVersion = applicationVersionFromDeployer.orElse(ApplicationVersion.unknown);
applicationPackage = applicationPackageFromDeployer.orElseThrow(
() -> new IllegalArgumentException("Application package must be given when deploying to " + zone));
platformVersion = options.vespaVersion.map(Version::new)
.orElse(applicationPackage.deploymentSpec().majorVersion()
.flatMap(this::lastCompatibleVersion)
.orElseGet(controller::systemVersion));
}
else {
JobType jobType = JobType.from(controller.system(), zone)
.orElseThrow(() -> new IllegalArgumentException("No job is known for " + zone + "."));
var run = controller.jobController().last(instanceId, jobType);
if (run.map(Run::hasEnded).orElse(true))
return unexpectedDeployment(instanceId, zone);
Versions versions = run.get().versions();
platformVersion = preferOldestVersion ? versions.sourcePlatform().orElse(versions.targetPlatform())
: versions.targetPlatform();
applicationVersion = preferOldestVersion ? versions.sourceApplication().orElse(versions.targetApplication())
: versions.targetApplication();
applicationPackage = getApplicationPackage(instanceId, applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, instanceId, jobType);
validateRun(application.get().require(instance), zone, platformVersion, applicationVersion);
}
endpointCertificateMetadata = endpointCertificateManager.getEndpointCertificateMetadata(application.get().require(instance), zone);
endpoints = controller.routing().registerEndpointsInDns(application.get(), instance, zone);
}
ActivateResult result = deploy(instanceId, applicationPackage, zone, platformVersion,
endpoints, endpointCertificateMetadata, Optional.empty());
lockApplicationOrThrow(applicationId, application ->
store(application.with(instanceId.instance(),
instance -> instance.withNewDeployment(zone, applicationVersion, platformVersion,
clock.instant(), warningsFrom(result)))));
return result;
}
}
private ApplicationPackage withTesterCertificate(ApplicationPackage applicationPackage, ApplicationId id, JobType type) {
if (applicationPackage.trustedCertificates().isEmpty())
return applicationPackage;
Run run = controller.jobController().last(id, type)
.orElseThrow(() -> new IllegalStateException("Last run of " + type + " for " + id + " not found"));
if (run.testerCertificate().isEmpty())
return applicationPackage;
return applicationPackage.withTrustedCertificate(run.testerCertificate().get());
}
/** Fetches the requested application package from the artifact store(s). */
public ApplicationPackage getApplicationPackage(ApplicationId id, ApplicationVersion version) {
return new ApplicationPackage(applicationStore.get(id.tenant(), id.application(), version));
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public LockedApplication storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
applicationPackageValidator.validate(application.get(), applicationPackage, clock.instant());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
var existingInstances = application.get().instances().keySet();
var declaredInstances = applicationPackage.deploymentSpec().instanceNames();
for (var name : declaredInstances)
if ( ! existingInstances.contains(name))
application = withNewInstance(application, application.get().id().instance(name));
for (InstanceName name : existingInstances) {
application = withoutDeletedDeployments(application, name);
}
for (InstanceName instance : declaredInstances)
if (applicationPackage.deploymentSpec().requireInstance(instance).concerns(Environment.prod))
application = controller.routing().assignRotations(application, instance);
store(application);
return application;
}
/** Deploy a system application to given zone */
public void deploy(SystemApplication application, ZoneId zone, Version version) {
if (application.hasApplicationPackage()) {
deploySystemApplicationPackage(application, zone, version);
} else {
configServer.nodeRepository().upgrade(zone, application.nodeType(), version);
}
}
/** Deploy a system application to given zone */
public ActivateResult deploySystemApplicationPackage(SystemApplication application, ZoneId zone, Version version) {
if (application.hasApplicationPackage()) {
ApplicationPackage applicationPackage = new ApplicationPackage(
artifactRepository.getSystemApplicationPackage(application.id(), zone, version)
);
return deploy(application.id(), applicationPackage, zone, version, Set.of(), /* No application cert */ Optional.empty(), Optional.empty());
} else {
throw new RuntimeException("This system application does not have an application package: " + application.id().toShortString());
}
}
/** Deploys the given tester application to the given zone. */
public ActivateResult deployTester(TesterId tester, ApplicationPackage applicationPackage, ZoneId zone, Version platform) {
return deploy(tester.id(), applicationPackage, zone, platform, Set.of(), /* No application cert for tester*/ Optional.empty(), Optional.empty());
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, Version platform, Set<ContainerEndpoint> endpoints,
Optional<EndpointCertificateMetadata> endpointCertificateMetadata,
Optional<ApplicationRoles> applicationRoles) {
try {
Optional<DockerImage> dockerImageRepo = Optional.ofNullable(
dockerImageRepoFlag
.with(FetchVector.Dimension.ZONE_ID, zone.value())
.with(FetchVector.Dimension.APPLICATION_ID, application.serializedForm())
.value())
.filter(s -> !s.isBlank())
.map(DockerImage::fromString);
Optional<AthenzDomain> domain = controller.tenants().get(application.tenant())
.filter(tenant-> tenant instanceof AthenzTenant)
.map(tenant -> ((AthenzTenant)tenant).domain());
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(new DeploymentData(application, zone, applicationPackage.zippedContent(), platform,
endpoints, endpointCertificateMetadata, dockerImageRepo, domain, applicationRoles));
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
controller.routing().policies().refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
private ActivateResult unexpectedDeployment(ApplicationId application, ZoneId zone) {
Log logEntry = new Log();
logEntry.level = "WARNING";
logEntry.time = clock.instant().toEpochMilli();
logEntry.message = "Ignoring deployment of application '" + application + "' to " + zone +
" as a deployment is not currently expected";
PrepareResponse prepareResponse = new PrepareResponse();
prepareResponse.log = List.of(logEntry);
prepareResponse.configChangeActions = new ConfigChangeActions(List.of(), List.of());
return new ActivateResult(new RevisionId("0"), prepareResponse, 0);
}
private LockedApplication withoutDeletedDeployments(LockedApplication application, InstanceName instance) {
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
List<ZoneId> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.map(Deployment::zone)
.filter(zone -> deploymentSpec.instance(instance).isEmpty()
|| ! deploymentSpec.requireInstance(instance).deploysTo(zone.environment(),
zone.region()))
.collect(toList());
if (deploymentsToRemove.isEmpty())
return application;
if ( ! application.get().validationOverrides().allows(ValidationId.deploymentRemoval, clock.instant()))
throw new IllegalArgumentException(ValidationId.deploymentRemoval.value() + ": " + application.get().require(instance) +
" is deployed in " +
deploymentsToRemove.stream()
.map(zone -> zone.region().value())
.collect(joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
boolean removeInstance = ! deploymentSpec.instanceNames().contains(instance)
&& application.get().require(instance).deployments().size() == deploymentsToRemove.size();
for (ZoneId zone : deploymentsToRemove)
application = deactivate(application, instance, zone);
if (removeInstance)
application = application.without(instance);
return application;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/**
* Deletes the the given application. All known instances of the applications will be deleted.
*
* @throws IllegalArgumentException if the application has deployments or the caller is not authorized
*/
public void deleteApplication(TenantAndApplicationId id, Credentials credentials) {
lockApplicationOrThrow(id, application -> {
var deployments = application.get().instances().values().stream()
.filter(instance -> ! instance.deployments().isEmpty())
.collect(toMap(instance -> instance.name(),
instance -> instance.deployments().keySet().stream()
.map(ZoneId::toString)
.collect(joining(", "))));
if ( ! deployments.isEmpty())
throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments: " + deployments);
for (Instance instance : application.get().instances().values()) {
controller.routing().removeEndpointsInDns(application.get(), instance.name());
application = application.without(instance.name());
}
applicationStore.removeAll(id.tenant(), id.application());
applicationStore.removeAllTesters(id.tenant(), id.application());
accessControl.deleteApplication(id, credentials);
curator.removeApplication(id);
controller.jobController().collectGarbage();
log.info("Deleted " + id);
});
}
/**
* Deletes the the given application instance.
*
* @throws IllegalArgumentException if the application has deployments or the caller is not authorized
* @throws NotExistsException if the instance does not exist
*/
public void deleteInstance(ApplicationId instanceId) {
if (getInstance(instanceId).isEmpty())
throw new NotExistsException("Could not delete instance '" + instanceId + "': Instance not found");
lockApplicationOrThrow(TenantAndApplicationId.from(instanceId), application -> {
if ( ! application.get().require(instanceId.instance()).deployments().isEmpty())
throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments in: " +
application.get().require(instanceId.instance()).deployments().keySet().stream().map(ZoneId::toString)
.sorted().collect(joining(", ")));
if ( ! application.get().deploymentSpec().equals(DeploymentSpec.empty)
&& application.get().deploymentSpec().instanceNames().contains(instanceId.instance()))
throw new IllegalArgumentException("Can not delete '" + instanceId + "', which is specified in 'deployment.xml'; remove it there first");
controller.routing().removeEndpointsInDns(application.get(), instanceId.instance());
curator.writeApplication(application.without(instanceId.instance()).get());
controller.jobController().collectGarbage();
log.info("Deleted " + instanceId);
});
}
/**
* Replace any previous version of this application by this instance
*
* @param application a locked application to store
*/
public void store(LockedApplication application) {
curator.writeApplication(application.get());
}
/**
* Acquire a locked application to modify and store, if there is an application with the given id.
*
* @param applicationId ID of the application to lock and get.
* @param action Function which acts on the locked application.
*/
public void lockApplicationIfPresent(TenantAndApplicationId applicationId, Consumer<LockedApplication> action) {
try (Lock lock = lock(applicationId)) {
getApplication(applicationId).map(application -> new LockedApplication(application, lock)).ifPresent(action);
}
}
/**
* Acquire a locked application to modify and store, or throw an exception if no application has the given id.
*
* @param applicationId ID of the application to lock and require.
* @param action Function which acts on the locked application.
* @throws IllegalArgumentException when application does not exist.
*/
public void lockApplicationOrThrow(TenantAndApplicationId applicationId, Consumer<LockedApplication> action) {
try (Lock lock = lock(applicationId)) {
action.accept(new LockedApplication(requireApplication(applicationId), lock));
}
}
/**
* Tells config server to schedule a restart of all nodes in this deployment
*
* @param hostname If non-empty, restart will only be scheduled for this host
*/
public void restart(DeploymentId deploymentId, Optional<Hostname> hostname) {
configServer.restart(deploymentId, hostname);
}
/**
* Asks the config server whether this deployment is currently <i>suspended</i>:
* Not in a state where it should receive traffic.
*/
public boolean isSuspended(DeploymentId deploymentId) {
try {
return configServer.isSuspended(deploymentId);
}
catch (ConfigServerException e) {
if (e.getErrorCode() == ConfigServerException.ErrorCode.NOT_FOUND)
return false;
throw e;
}
}
/** Deactivate application in the given zone */
public void deactivate(ApplicationId id, ZoneId zone) {
lockApplicationOrThrow(TenantAndApplicationId.from(id),
application -> store(deactivate(application, id.instance(), zone)));
}
/**
* Deactivates a locked application without storing it
*
* @return the application with the deployment in the given zone removed
*/
private LockedApplication deactivate(LockedApplication application, InstanceName instanceName, ZoneId zone) {
try {
configServer.deactivate(new DeploymentId(application.get().id().instance(instanceName), zone));
} catch (NotFoundException ignored) {
} finally {
controller.routing().policies().refresh(application.get().id().instance(instanceName), application.get().deploymentSpec(), zone);
}
return application.with(instanceName, instance -> instance.withoutDeploymentIn(zone));
}
public DeploymentTrigger deploymentTrigger() { return deploymentTrigger; }
private TenantAndApplicationId dashToUnderscore(TenantAndApplicationId id) {
return TenantAndApplicationId.from(id.tenant().value(), id.application().value().replaceAll("-", "_"));
}
private ApplicationId dashToUnderscore(ApplicationId id) {
return dashToUnderscore(TenantAndApplicationId.from(id)).instance(id.instance());
}
/**
* Returns a lock which provides exclusive rights to changing this application.
* Any operation which stores an application need to first acquire this lock, then read, modify
* and store the application, and finally release (close) the lock.
*/
Lock lock(TenantAndApplicationId application) {
return curator.lock(application);
}
/**
* Returns a lock which provides exclusive rights to deploying this application to the given zone.
*/
private Lock lockForDeployment(ApplicationId application, ZoneId zone) {
return curator.lockForDeployment(application, zone);
}
/** Verify that we don't downgrade an existing production deployment. */
private void validateRun(Instance instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = instance.deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! instance.change().isPinned()
|| applicationVersion.compareTo(deployment.applicationVersion()) < 0))
throw new IllegalArgumentException(String.format("Rejecting deployment of application %s to %s, as the requested versions (platform: %s, application: %s)" +
" are older than the currently deployed (platform: %s, application: %s).",
instance.id(), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/**
* Verifies that the application can be deployed to the tenant, following these rules:
*
* 1. Verify that the Athenz service can be launched by the config server
* 2. If the principal is given, verify that the principal is tenant admin or admin of the tenant domain
* 3. If the principal is not given, verify that the Athenz domain of the tenant equals Athenz domain given in deployment.xml
*
* @param tenantName tenant where application should be deployed
* @param applicationPackage application package
* @param deployer principal initiating the deployment, possibly empty
*/
public void verifyApplicationIdentityConfiguration(TenantName tenantName, Optional<InstanceName> instanceName, Optional<ZoneId> zoneId, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
Optional<AthenzDomain> identityDomain = applicationPackage.deploymentSpec().athenzDomain()
.map(domain -> new AthenzDomain(domain.value()));
if(identityDomain.isEmpty()) {
return;
}
if(! (accessControl instanceof AthenzFacade)) {
throw new IllegalArgumentException("Athenz domain and service specified in deployment.xml, but not supported by system.");
}
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
Optional<AthenzUser> athenzUser = getUser(deployer);
if (athenzUser.isPresent()) {
var zone = zoneId.orElseThrow(() -> new IllegalArgumentException("Unable to evaluate access, no zone provided in deployment"));
var serviceToLaunch = instanceName
.flatMap(instance -> applicationPackage.deploymentSpec().instance(instance))
.flatMap(instanceSpec -> instanceSpec.athenzService(zone.environment(), zone.region()))
.or(() -> applicationPackage.deploymentSpec().athenzService())
.map(service -> new AthenzService(identityDomain.get(), service.value()));
if(serviceToLaunch.isPresent()) {
if (
! ((AthenzFacade) accessControl).canLaunch(athenzUser.get(), serviceToLaunch.get()) &&
! ((AthenzFacade) accessControl).hasTenantAdminAccess(athenzUser.get(), identityDomain.get())
) {
throw new IllegalArgumentException("User " + athenzUser.get().getFullName() + " is not allowed to launch " +
"service " + serviceToLaunch.get().getFullName() + ". " +
"Please reach out to the domain admin.");
}
} else {
throw new IllegalArgumentException("Athenz domain configured, but no service defined for deployment to " + zone.value());
}
} else {
Tenant tenant = controller.tenants().require(tenantName);
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain, identityDomain.get()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.get().getName() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
}
}
/*
* Get the AthenzUser from this principal or Optional.empty if this does not represent a user.
*/
private Optional<AthenzUser> getUser(Optional<Principal> deployer) {
return deployer
.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.map(AthenzUser.class::cast);
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(domain -> {
controller.zoneRegistry().zones().reachable().ids().forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService().ifPresent(service -> {
verifyAthenzServiceCanBeLaunchedBy(configServerAthenzIdentity, new AthenzService(domain.value(), service.value()));
});
deploymentSpec.instances().forEach(spec -> {
spec.athenzService(zone.environment(), zone.region()).ifPresent(service -> {
verifyAthenzServiceCanBeLaunchedBy(configServerAthenzIdentity, new AthenzService(domain.value(), service.value()));
});
});
});
});
}
private void verifyAthenzServiceCanBeLaunchedBy(AthenzIdentity configServerAthenzIdentity, AthenzService athenzService) {
if ( ! ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, athenzService))
throw new IllegalArgumentException("Not allowed to launch Athenz service " + athenzService.getFullName());
}
/** Returns the latest known version within the given major. */
public Optional<Version> lastCompatibleVersion(int targetMajorVersion) {
return controller.versionStatus().versions().stream()
.map(VespaVersion::versionNumber)
.filter(version -> version.getMajor() == targetMajorVersion)
.max(naturalOrder());
}
/** Extract deployment warnings metric from deployment result */
private static Map<DeploymentMetrics.Warning, Integer> warningsFrom(ActivateResult result) {
if (result.prepareResponse().log == null) return Map.of();
Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>();
for (Log log : result.prepareResponse().log) {
if (!"warn".equalsIgnoreCase(log.level) && !"warning".equalsIgnoreCase(log.level)) continue;
warnings.merge(DeploymentMetrics.Warning.all, 1, Integer::sum);
}
return Map.copyOf(warnings);
}
} | class ApplicationController {
private static final Logger log = Logger.getLogger(ApplicationController.class.getName());
/** The controller owning this */
private final Controller controller;
/** For persistence */
private final CuratorDb curator;
private final ArtifactRepository artifactRepository;
private final ApplicationStore applicationStore;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final ApplicationPackageValidator applicationPackageValidator;
private final EndpointCertificateManager endpointCertificateManager;
private final StringFlag dockerImageRepoFlag;
private final BooleanFlag provisionApplicationRoles;
ApplicationController(Controller controller, CuratorDb curator, AccessControl accessControl, Clock clock,
SecretStore secretStore, FlagSource flagSource) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
this.dockerImageRepoFlag = Flags.DOCKER_IMAGE_REPO.bindTo(flagSource);
this.provisionApplicationRoles = Flags.PROVISION_APPLICATION_ROLES.bindTo(flagSource);
deploymentTrigger = new DeploymentTrigger(controller, clock);
applicationPackageValidator = new ApplicationPackageValidator(controller);
endpointCertificateManager = new EndpointCertificateManager(controller.zoneRegistry(), curator, secretStore,
controller.serviceRegistry().endpointCertificateProvider(), clock, flagSource);
Once.after(Duration.ofMinutes(1), () -> {
Instant start = clock.instant();
int count = 0;
for (TenantAndApplicationId id : curator.readApplicationIds()) {
lockApplicationIfPresent(id, application -> {
for (InstanceName instance : application.get().deploymentSpec().instanceNames())
if (!application.get().instances().containsKey(instance))
application = withNewInstance(application, id.instance(instance));
store(application);
});
count++;
}
log.log(Level.INFO, String.format("Wrote %d applications in %s", count,
Duration.between(start, clock.instant())));
});
}
/** Returns the application with the given id, or null if it is not present */
public Optional<Application> getApplication(TenantAndApplicationId id) {
return curator.readApplication(id);
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id)).flatMap(application -> application.get(id.instance()));
}
/**
* Returns the application with the given id
*
* @throws IllegalArgumentException if it does not exist
*/
public Application requireApplication(TenantAndApplicationId id) {
return getApplication(id).orElseThrow(() -> new IllegalArgumentException(id + " not found"));
}
/**
* Returns the instance with the given id
*
* @throws IllegalArgumentException if it does not exist
*/
public Instance requireInstance(ApplicationId id) {
return getInstance(id).orElseThrow(() -> new IllegalArgumentException(id + " not found"));
}
/** Returns a snapshot of all applications */
public List<Application> asList() {
return curator.readApplications(false);
}
/**
* Returns a snapshot of all readable applications. Unlike {@link ApplicationController
* applications that cannot currently be read (e.g. due to serialization issues) and may return an incomplete
* snapshot.
*
* This should only be used in cases where acting on a subset of applications is better than none.
*/
public List<Application> readable() {
return curator.readApplications(true);
}
/** Returns the ID of all known applications. */
public List<TenantAndApplicationId> idList() {
return curator.readApplicationIds();
}
/** Returns a snapshot of all applications of a tenant */
public List<Application> asList(TenantName tenant) {
return curator.readApplications(tenant);
}
public ArtifactRepository artifacts() { return artifactRepository; }
public ApplicationStore applicationStore() { return applicationStore; }
/** Returns all content clusters in all current deployments of the given application. */
public Map<ZoneId, List<String>> contentClustersByZone(Collection<DeploymentId> ids) {
Map<ZoneId, List<String>> clusters = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (DeploymentId id : ids)
clusters.put(id.zoneId(), List.copyOf(configServer.getContentClusters(id)));
return Collections.unmodifiableMap(clusters);
}
/** Returns the oldest Vespa version installed on any active or reserved production node for the given application. */
public Version oldestInstalledPlatform(TenantAndApplicationId id) {
return requireApplication(id).instances().values().stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream()
.flatMap(zone -> configServer.nodeRepository().list(zone,
id.instance(instance.name()),
EnumSet.of(active, reserved))
.stream())
.map(Node::currentVersion)
.filter(version -> ! version.isEmpty()))
.min(naturalOrder())
.orElse(controller.systemVersion());
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public Application createApplication(TenantAndApplicationId id, Credentials credentials) {
try (Lock lock = lock(id)) {
if (getApplication(id).isPresent())
throw new IllegalArgumentException("Could not create '" + id + "': Application already exists");
if (getApplication(dashToUnderscore(id)).isPresent())
throw new IllegalArgumentException("Could not create '" + id + "': Application " + dashToUnderscore(id) + " already exists");
com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId.validate(id.application().value());
if (controller.tenants().get(id.tenant()).isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
accessControl.createApplication(id, credentials);
LockedApplication locked = new LockedApplication(new Application(id, clock.instant()), lock);
store(locked);
log.info("Created " + locked);
return locked.get();
}
}
/**
* Creates a new instance for an existing application.
*
* @throws IllegalArgumentException if the instance already exists, or has an invalid instance name.
*/
public void createInstance(ApplicationId id) {
lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
store(withNewInstance(application, id));
});
}
public LockedApplication withNewInstance(LockedApplication application, ApplicationId id) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
InstanceId.validate(id.instance().value());
if (getInstance(id).isPresent())
throw new IllegalArgumentException("Could not create '" + id + "': Instance already exists");
if (getInstance(dashToUnderscore(id)).isPresent())
throw new IllegalArgumentException("Could not create '" + id + "': Instance " + dashToUnderscore(id) + " already exists");
log.info("Created " + id);
return application.withNewInstance(id.instance());
}
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options);
}
/** Deploys an application package for an existing application instance. */
private ApplicationPackage getApplicationPackage(ApplicationId application, ZoneId zone, ApplicationVersion revision) {
return new ApplicationPackage(revision.isUnknown() ? applicationStore.getDev(application, zone)
: applicationStore.get(application.tenant(), application.application(), revision));
}
public ActivateResult deploy(ApplicationId instanceId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
Optional<ApplicationVersion> applicationVersionFromDeployer,
DeployOptions options) {
if (instanceId.instance().isTester())
throw new IllegalArgumentException("'" + instanceId + "' is a tester application!");
TenantAndApplicationId applicationId = TenantAndApplicationId.from(instanceId);
if (getInstance(instanceId).isEmpty())
createInstance(instanceId);
try (Lock deploymentLock = lockForDeployment(instanceId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<EndpointCertificateMetadata> endpointCertificateMetadata;
try (Lock lock = lock(applicationId)) {
LockedApplication application = new LockedApplication(requireApplication(applicationId), lock);
InstanceName instance = instanceId.instance();
boolean manuallyDeployed = options.deployDirectly || zone.environment().isManuallyDeployed();
boolean preferOldestVersion = options.deployCurrentVersion;
if (manuallyDeployed) {
applicationVersion = applicationVersionFromDeployer.orElse(ApplicationVersion.unknown);
applicationPackage = applicationPackageFromDeployer.orElseThrow(
() -> new IllegalArgumentException("Application package must be given when deploying to " + zone));
platformVersion = options.vespaVersion.map(Version::new)
.orElse(applicationPackage.deploymentSpec().majorVersion()
.flatMap(this::lastCompatibleVersion)
.orElseGet(controller::systemVersion));
}
else {
JobType jobType = JobType.from(controller.system(), zone)
.orElseThrow(() -> new IllegalArgumentException("No job is known for " + zone + "."));
var run = controller.jobController().last(instanceId, jobType);
if (run.map(Run::hasEnded).orElse(true))
return unexpectedDeployment(instanceId, zone);
Versions versions = run.get().versions();
platformVersion = preferOldestVersion ? versions.sourcePlatform().orElse(versions.targetPlatform())
: versions.targetPlatform();
applicationVersion = preferOldestVersion ? versions.sourceApplication().orElse(versions.targetApplication())
: versions.targetApplication();
applicationPackage = getApplicationPackage(instanceId, applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, instanceId, jobType);
validateRun(application.get().require(instance), zone, platformVersion, applicationVersion);
}
endpointCertificateMetadata = endpointCertificateManager.getEndpointCertificateMetadata(application.get().require(instance), zone);
endpoints = controller.routing().registerEndpointsInDns(application.get(), instance, zone);
}
ActivateResult result = deploy(instanceId, applicationPackage, zone, platformVersion,
endpoints, endpointCertificateMetadata, Optional.empty());
lockApplicationOrThrow(applicationId, application ->
store(application.with(instanceId.instance(),
instance -> instance.withNewDeployment(zone, applicationVersion, platformVersion,
clock.instant(), warningsFrom(result)))));
return result;
}
}
private ApplicationPackage withTesterCertificate(ApplicationPackage applicationPackage, ApplicationId id, JobType type) {
if (applicationPackage.trustedCertificates().isEmpty())
return applicationPackage;
Run run = controller.jobController().last(id, type)
.orElseThrow(() -> new IllegalStateException("Last run of " + type + " for " + id + " not found"));
if (run.testerCertificate().isEmpty())
return applicationPackage;
return applicationPackage.withTrustedCertificate(run.testerCertificate().get());
}
/** Fetches the requested application package from the artifact store(s). */
public ApplicationPackage getApplicationPackage(ApplicationId id, ApplicationVersion version) {
return new ApplicationPackage(applicationStore.get(id.tenant(), id.application(), version));
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public LockedApplication storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
applicationPackageValidator.validate(application.get(), applicationPackage, clock.instant());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
var existingInstances = application.get().instances().keySet();
var declaredInstances = applicationPackage.deploymentSpec().instanceNames();
for (var name : declaredInstances)
if ( ! existingInstances.contains(name))
application = withNewInstance(application, application.get().id().instance(name));
for (InstanceName name : existingInstances) {
application = withoutDeletedDeployments(application, name);
}
for (InstanceName instance : declaredInstances)
if (applicationPackage.deploymentSpec().requireInstance(instance).concerns(Environment.prod))
application = controller.routing().assignRotations(application, instance);
store(application);
return application;
}
/** Deploy a system application to given zone */
public void deploy(SystemApplication application, ZoneId zone, Version version) {
if (application.hasApplicationPackage()) {
deploySystemApplicationPackage(application, zone, version);
} else {
configServer.nodeRepository().upgrade(zone, application.nodeType(), version);
}
}
/** Deploy a system application to given zone */
public ActivateResult deploySystemApplicationPackage(SystemApplication application, ZoneId zone, Version version) {
if (application.hasApplicationPackage()) {
ApplicationPackage applicationPackage = new ApplicationPackage(
artifactRepository.getSystemApplicationPackage(application.id(), zone, version)
);
return deploy(application.id(), applicationPackage, zone, version, Set.of(), /* No application cert */ Optional.empty(), Optional.empty());
} else {
throw new RuntimeException("This system application does not have an application package: " + application.id().toShortString());
}
}
/** Deploys the given tester application to the given zone. */
public ActivateResult deployTester(TesterId tester, ApplicationPackage applicationPackage, ZoneId zone, Version platform) {
return deploy(tester.id(), applicationPackage, zone, platform, Set.of(), /* No application cert for tester*/ Optional.empty(), Optional.empty());
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, Version platform, Set<ContainerEndpoint> endpoints,
Optional<EndpointCertificateMetadata> endpointCertificateMetadata,
Optional<ApplicationRoles> applicationRoles) {
try {
Optional<DockerImage> dockerImageRepo = Optional.ofNullable(
dockerImageRepoFlag
.with(FetchVector.Dimension.ZONE_ID, zone.value())
.with(FetchVector.Dimension.APPLICATION_ID, application.serializedForm())
.value())
.filter(s -> !s.isBlank())
.map(DockerImage::fromString);
Optional<AthenzDomain> domain = controller.tenants().get(application.tenant())
.filter(tenant-> tenant instanceof AthenzTenant)
.map(tenant -> ((AthenzTenant)tenant).domain());
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(new DeploymentData(application, zone, applicationPackage.zippedContent(), platform,
endpoints, endpointCertificateMetadata, dockerImageRepo, domain, applicationRoles));
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
controller.routing().policies().refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
private ActivateResult unexpectedDeployment(ApplicationId application, ZoneId zone) {
Log logEntry = new Log();
logEntry.level = "WARNING";
logEntry.time = clock.instant().toEpochMilli();
logEntry.message = "Ignoring deployment of application '" + application + "' to " + zone +
" as a deployment is not currently expected";
PrepareResponse prepareResponse = new PrepareResponse();
prepareResponse.log = List.of(logEntry);
prepareResponse.configChangeActions = new ConfigChangeActions(List.of(), List.of());
return new ActivateResult(new RevisionId("0"), prepareResponse, 0);
}
private LockedApplication withoutDeletedDeployments(LockedApplication application, InstanceName instance) {
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
List<ZoneId> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.map(Deployment::zone)
.filter(zone -> deploymentSpec.instance(instance).isEmpty()
|| ! deploymentSpec.requireInstance(instance).deploysTo(zone.environment(),
zone.region()))
.collect(toList());
if (deploymentsToRemove.isEmpty())
return application;
if ( ! application.get().validationOverrides().allows(ValidationId.deploymentRemoval, clock.instant()))
throw new IllegalArgumentException(ValidationId.deploymentRemoval.value() + ": " + application.get().require(instance) +
" is deployed in " +
deploymentsToRemove.stream()
.map(zone -> zone.region().value())
.collect(joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
boolean removeInstance = ! deploymentSpec.instanceNames().contains(instance)
&& application.get().require(instance).deployments().size() == deploymentsToRemove.size();
for (ZoneId zone : deploymentsToRemove)
application = deactivate(application, instance, zone);
if (removeInstance)
application = application.without(instance);
return application;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/**
* Deletes the the given application. All known instances of the applications will be deleted.
*
* @throws IllegalArgumentException if the application has deployments or the caller is not authorized
*/
public void deleteApplication(TenantAndApplicationId id, Credentials credentials) {
lockApplicationOrThrow(id, application -> {
var deployments = application.get().instances().values().stream()
.filter(instance -> ! instance.deployments().isEmpty())
.collect(toMap(instance -> instance.name(),
instance -> instance.deployments().keySet().stream()
.map(ZoneId::toString)
.collect(joining(", "))));
if ( ! deployments.isEmpty())
throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments: " + deployments);
for (Instance instance : application.get().instances().values()) {
controller.routing().removeEndpointsInDns(application.get(), instance.name());
application = application.without(instance.name());
}
applicationStore.removeAll(id.tenant(), id.application());
applicationStore.removeAllTesters(id.tenant(), id.application());
accessControl.deleteApplication(id, credentials);
curator.removeApplication(id);
controller.jobController().collectGarbage();
log.info("Deleted " + id);
});
}
/**
* Deletes the the given application instance.
*
* @throws IllegalArgumentException if the application has deployments or the caller is not authorized
* @throws NotExistsException if the instance does not exist
*/
public void deleteInstance(ApplicationId instanceId) {
if (getInstance(instanceId).isEmpty())
throw new NotExistsException("Could not delete instance '" + instanceId + "': Instance not found");
lockApplicationOrThrow(TenantAndApplicationId.from(instanceId), application -> {
if ( ! application.get().require(instanceId.instance()).deployments().isEmpty())
throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments in: " +
application.get().require(instanceId.instance()).deployments().keySet().stream().map(ZoneId::toString)
.sorted().collect(joining(", ")));
if ( ! application.get().deploymentSpec().equals(DeploymentSpec.empty)
&& application.get().deploymentSpec().instanceNames().contains(instanceId.instance()))
throw new IllegalArgumentException("Can not delete '" + instanceId + "', which is specified in 'deployment.xml'; remove it there first");
controller.routing().removeEndpointsInDns(application.get(), instanceId.instance());
curator.writeApplication(application.without(instanceId.instance()).get());
controller.jobController().collectGarbage();
log.info("Deleted " + instanceId);
});
}
/**
* Replace any previous version of this application by this instance
*
* @param application a locked application to store
*/
public void store(LockedApplication application) {
curator.writeApplication(application.get());
}
/**
* Acquire a locked application to modify and store, if there is an application with the given id.
*
* @param applicationId ID of the application to lock and get.
* @param action Function which acts on the locked application.
*/
public void lockApplicationIfPresent(TenantAndApplicationId applicationId, Consumer<LockedApplication> action) {
try (Lock lock = lock(applicationId)) {
getApplication(applicationId).map(application -> new LockedApplication(application, lock)).ifPresent(action);
}
}
/**
* Acquire a locked application to modify and store, or throw an exception if no application has the given id.
*
* @param applicationId ID of the application to lock and require.
* @param action Function which acts on the locked application.
* @throws IllegalArgumentException when application does not exist.
*/
public void lockApplicationOrThrow(TenantAndApplicationId applicationId, Consumer<LockedApplication> action) {
try (Lock lock = lock(applicationId)) {
action.accept(new LockedApplication(requireApplication(applicationId), lock));
}
}
/**
* Tells config server to schedule a restart of all nodes in this deployment
*
* @param hostname If non-empty, restart will only be scheduled for this host
*/
public void restart(DeploymentId deploymentId, Optional<Hostname> hostname) {
configServer.restart(deploymentId, hostname);
}
/**
* Asks the config server whether this deployment is currently <i>suspended</i>:
* Not in a state where it should receive traffic.
*/
public boolean isSuspended(DeploymentId deploymentId) {
try {
return configServer.isSuspended(deploymentId);
}
catch (ConfigServerException e) {
if (e.getErrorCode() == ConfigServerException.ErrorCode.NOT_FOUND)
return false;
throw e;
}
}
/** Deactivate application in the given zone */
public void deactivate(ApplicationId id, ZoneId zone) {
lockApplicationOrThrow(TenantAndApplicationId.from(id),
application -> store(deactivate(application, id.instance(), zone)));
}
/**
* Deactivates a locked application without storing it
*
* @return the application with the deployment in the given zone removed
*/
private LockedApplication deactivate(LockedApplication application, InstanceName instanceName, ZoneId zone) {
try {
configServer.deactivate(new DeploymentId(application.get().id().instance(instanceName), zone));
} catch (NotFoundException ignored) {
} finally {
controller.routing().policies().refresh(application.get().id().instance(instanceName), application.get().deploymentSpec(), zone);
}
return application.with(instanceName, instance -> instance.withoutDeploymentIn(zone));
}
public DeploymentTrigger deploymentTrigger() { return deploymentTrigger; }
private TenantAndApplicationId dashToUnderscore(TenantAndApplicationId id) {
return TenantAndApplicationId.from(id.tenant().value(), id.application().value().replaceAll("-", "_"));
}
private ApplicationId dashToUnderscore(ApplicationId id) {
return dashToUnderscore(TenantAndApplicationId.from(id)).instance(id.instance());
}
/**
* Returns a lock which provides exclusive rights to changing this application.
* Any operation which stores an application need to first acquire this lock, then read, modify
* and store the application, and finally release (close) the lock.
*/
Lock lock(TenantAndApplicationId application) {
return curator.lock(application);
}
/**
* Returns a lock which provides exclusive rights to deploying this application to the given zone.
*/
private Lock lockForDeployment(ApplicationId application, ZoneId zone) {
return curator.lockForDeployment(application, zone);
}
/** Verify that we don't downgrade an existing production deployment. */
private void validateRun(Instance instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = instance.deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! instance.change().isPinned()
|| applicationVersion.compareTo(deployment.applicationVersion()) < 0))
throw new IllegalArgumentException(String.format("Rejecting deployment of application %s to %s, as the requested versions (platform: %s, application: %s)" +
" are older than the currently deployed (platform: %s, application: %s).",
instance.id(), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/**
* Verifies that the application can be deployed to the tenant, following these rules:
*
* 1. Verify that the Athenz service can be launched by the config server
* 2. If the principal is given, verify that the principal is tenant admin or admin of the tenant domain
* 3. If the principal is not given, verify that the Athenz domain of the tenant equals Athenz domain given in deployment.xml
*
* @param tenantName tenant where application should be deployed
* @param applicationPackage application package
* @param deployer principal initiating the deployment, possibly empty
*/
public void verifyApplicationIdentityConfiguration(TenantName tenantName, Optional<InstanceName> instanceName, Optional<ZoneId> zoneId, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
Optional<AthenzDomain> identityDomain = applicationPackage.deploymentSpec().athenzDomain()
.map(domain -> new AthenzDomain(domain.value()));
if(identityDomain.isEmpty()) {
return;
}
if(! (accessControl instanceof AthenzFacade)) {
throw new IllegalArgumentException("Athenz domain and service specified in deployment.xml, but not supported by system.");
}
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
Optional<AthenzUser> athenzUser = getUser(deployer);
if (athenzUser.isPresent()) {
var zone = zoneId.orElseThrow(() -> new IllegalArgumentException("Unable to evaluate access, no zone provided in deployment"));
var serviceToLaunch = instanceName
.flatMap(instance -> applicationPackage.deploymentSpec().instance(instance))
.flatMap(instanceSpec -> instanceSpec.athenzService(zone.environment(), zone.region()))
.or(() -> applicationPackage.deploymentSpec().athenzService())
.map(service -> new AthenzService(identityDomain.get(), service.value()));
if(serviceToLaunch.isPresent()) {
if (
! ((AthenzFacade) accessControl).canLaunch(athenzUser.get(), serviceToLaunch.get()) &&
! ((AthenzFacade) accessControl).hasTenantAdminAccess(athenzUser.get(), identityDomain.get())
) {
throw new IllegalArgumentException("User " + athenzUser.get().getFullName() + " is not allowed to launch " +
"service " + serviceToLaunch.get().getFullName() + ". " +
"Please reach out to the domain admin.");
}
} else {
throw new IllegalArgumentException("Athenz domain configured, but no service defined for deployment to " + zone.value());
}
} else {
Tenant tenant = controller.tenants().require(tenantName);
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain, identityDomain.get()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.get().getName() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
}
}
/*
* Get the AthenzUser from this principal or Optional.empty if this does not represent a user.
*/
private Optional<AthenzUser> getUser(Optional<Principal> deployer) {
return deployer
.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.map(AthenzUser.class::cast);
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(domain -> {
controller.zoneRegistry().zones().reachable().ids().forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService().ifPresent(service -> {
verifyAthenzServiceCanBeLaunchedBy(configServerAthenzIdentity, new AthenzService(domain.value(), service.value()));
});
deploymentSpec.instances().forEach(spec -> {
spec.athenzService(zone.environment(), zone.region()).ifPresent(service -> {
verifyAthenzServiceCanBeLaunchedBy(configServerAthenzIdentity, new AthenzService(domain.value(), service.value()));
});
});
});
});
}
private void verifyAthenzServiceCanBeLaunchedBy(AthenzIdentity configServerAthenzIdentity, AthenzService athenzService) {
if ( ! ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, athenzService))
throw new IllegalArgumentException("Not allowed to launch Athenz service " + athenzService.getFullName());
}
/** Returns the latest known version within the given major. */
public Optional<Version> lastCompatibleVersion(int targetMajorVersion) {
return controller.versionStatus().versions().stream()
.map(VespaVersion::versionNumber)
.filter(version -> version.getMajor() == targetMajorVersion)
.max(naturalOrder());
}
/** Extract deployment warnings metric from deployment result */
private static Map<DeploymentMetrics.Warning, Integer> warningsFrom(ActivateResult result) {
if (result.prepareResponse().log == null) return Map.of();
Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>();
for (Log log : result.prepareResponse().log) {
if (!"warn".equalsIgnoreCase(log.level) && !"warning".equalsIgnoreCase(log.level)) continue;
warnings.merge(DeploymentMetrics.Warning.all, 1, Integer::sum);
}
return Map.copyOf(warnings);
}
} |
```suggestion if (owners.size() == 1 && owners.contains(owner)) { ``` | public void unregisterSession(String session, NetworkOwner owner, boolean broadcast) {
sessions.computeIfPresent(session, (name, owners) -> {
if (owners.equals(List.of(owner))) {
if (broadcast)
net.unregisterSession(session);
return null;
}
owners.remove(owner);
return owners;
});
} | if (owners.equals(List.of(owner))) { | public void unregisterSession(String session, NetworkOwner owner, boolean broadcast) {
sessions.computeIfPresent(session, (name, owners) -> {
if (owners.size() == 1 && owners.contains(owner)) {
if (broadcast)
net.unregisterSession(session);
return null;
}
owners.remove(owner);
return owners;
});
} | class NetworkMultiplexer implements NetworkOwner {
private static final Logger log = Logger.getLogger(NetworkMultiplexer.class.getName());
private final Network net;
private final Deque<NetworkOwner> owners = new ConcurrentLinkedDeque<>();
private final Map<String, Deque<NetworkOwner>> sessions = new ConcurrentHashMap<>();
private final AtomicBoolean disowned;
private NetworkMultiplexer(Network net, boolean shared) {
net.attach(this);
this.net = net;
this.disowned = new AtomicBoolean( ! shared);
}
/** Returns a network multiplexer which will be shared between several {@link NetworkOwner}s,
* and will shut down when all these have detached, and {@link
public static NetworkMultiplexer shared(Network net) {
return new NetworkMultiplexer(net, true);
}
/** Returns a network multiplexer with a single {@link NetworkOwner}, which shuts down when this owner detaches. */
public static NetworkMultiplexer dedicated(Network net) {
return new NetworkMultiplexer(net, false);
}
public void registerSession(String session, NetworkOwner owner, boolean broadcast) {
sessions.compute(session, (name, owners) -> {
if (owners == null) {
owners = new ConcurrentLinkedDeque<>();
if (broadcast)
net.registerSession(session);
}
else if (owners.contains(owner))
throw new IllegalArgumentException("Session '" + session + "' with owner '" + owner + "' already registered with " + this);
owners.push(owner);
return owners;
});
}
@Override
public Protocol getProtocol(Utf8Array name) {
Protocol protocol = null;
for (NetworkOwner owner : owners)
protocol = owner.getProtocol(name) == null ? protocol : owner.getProtocol(name);
return protocol;
}
@Override
public void deliverMessage(Message message, String session) {
NetworkOwner owner = sessions.getOrDefault(session, owners).peek();
if (owner == null) {
log.warning(this + " received message '" + message + "' with no owners attached");
message.discard();
}
else
owner.deliverMessage(message, session);
}
/** Attach the network owner to this, allowing this to forward messages to it. */
public void attach(NetworkOwner owner) {
if (owners.contains(owner))
throw new IllegalArgumentException(owner + " is already attached to " + this);
owners.add(owner);
}
/** Detach the network owner from this, no longer allowing messages to it, and shutting down this is ownerless. */
public void detach(NetworkOwner owner) {
if ( ! owners.remove(owner))
throw new IllegalArgumentException(owner + " not attached to " + this);
destroyIfOwnerless();
}
/** Signal that external ownership of this is relinquished, allowing destruction on last owner detachment. */
public void disown() {
if (disowned.getAndSet(true))
throw new IllegalStateException("Destroy called on a dedicated multiplexer--" +
"this automatically shuts down when detached from--or " +
"called multiple times on a shared multiplexer");
destroyIfOwnerless();
}
private void destroyIfOwnerless() {
if (disowned.get() && owners.isEmpty())
net.shutdown();
}
public Network net() {
return net;
}
@Override
public String toString() {
return "network multiplexer with owners: " + owners + ", sessions: " + sessions + " and destructible: " + disowned.get();
}
} | class NetworkMultiplexer implements NetworkOwner {
private static final Logger log = Logger.getLogger(NetworkMultiplexer.class.getName());
private final Network net;
private final Deque<NetworkOwner> owners = new ConcurrentLinkedDeque<>();
private final Map<String, Deque<NetworkOwner>> sessions = new ConcurrentHashMap<>();
private final AtomicBoolean disowned;
private NetworkMultiplexer(Network net, boolean shared) {
net.attach(this);
this.net = net;
this.disowned = new AtomicBoolean( ! shared);
}
/** Returns a network multiplexer which will be shared between several {@link NetworkOwner}s,
* and will shut down when all these have detached, and {@link
public static NetworkMultiplexer shared(Network net) {
return new NetworkMultiplexer(net, true);
}
/** Returns a network multiplexer with a single {@link NetworkOwner}, which shuts down when this owner detaches. */
public static NetworkMultiplexer dedicated(Network net) {
return new NetworkMultiplexer(net, false);
}
public void registerSession(String session, NetworkOwner owner, boolean broadcast) {
sessions.compute(session, (name, owners) -> {
if (owners == null) {
owners = new ConcurrentLinkedDeque<>();
if (broadcast)
net.registerSession(session);
}
else if (owners.contains(owner))
throw new IllegalArgumentException("Session '" + session + "' with owner '" + owner + "' already registered with " + this);
owners.push(owner);
return owners;
});
}
@Override
public Protocol getProtocol(Utf8Array name) {
Protocol protocol = null;
for (NetworkOwner owner : owners)
protocol = owner.getProtocol(name) == null ? protocol : owner.getProtocol(name);
return protocol;
}
@Override
public void deliverMessage(Message message, String session) {
NetworkOwner owner = sessions.getOrDefault(session, owners).peek();
if (owner == null) {
log.warning(this + " received message '" + message + "' with no owners attached");
message.discard();
}
else
owner.deliverMessage(message, session);
}
/** Attach the network owner to this, allowing this to forward messages to it. */
public void attach(NetworkOwner owner) {
if (owners.contains(owner))
throw new IllegalArgumentException(owner + " is already attached to " + this);
owners.add(owner);
}
/** Detach the network owner from this, no longer allowing messages to it, and shutting down this is ownerless. */
public void detach(NetworkOwner owner) {
if ( ! owners.remove(owner))
throw new IllegalArgumentException(owner + " not attached to " + this);
destroyIfOwnerless();
}
/** Signal that external ownership of this is relinquished, allowing destruction on last owner detachment. */
public void disown() {
if (disowned.getAndSet(true))
throw new IllegalStateException("Destroy called on a dedicated multiplexer--" +
"this automatically shuts down when detached from--or " +
"called multiple times on a shared multiplexer");
destroyIfOwnerless();
}
private void destroyIfOwnerless() {
if (disowned.get() && owners.isEmpty())
net.shutdown();
}
public Network net() {
return net;
}
@Override
public String toString() {
return "network multiplexer with owners: " + owners + ", sessions: " + sessions + " and destructible: " + disowned.get();
}
} |
Must be added in https://github.com/vespa-engine/vespa/blob/master/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/noderepository/NodeHistory.java as well | private Agent eventAgentFromSlime(Inspector eventAgentField) {
switch (eventAgentField.asString()) {
case "operator" : return Agent.operator;
case "application" : return Agent.application;
case "system" : return Agent.system;
case "NodeFailer" : return Agent.NodeFailer;
case "Rebalancer" : return Agent.Rebalancer;
case "DirtyExpirer" : return Agent.DirtyExpirer;
case "FailedExpirer" : return Agent.FailedExpirer;
case "InactiveExpirer" : return Agent.InactiveExpirer;
case "ProvisionedExpirer" : return Agent.ProvisionedExpirer;
case "ReservationExpirer" : return Agent.ReservationExpirer;
case "DynamicProvisioningMaintainer" : return Agent.DynamicProvisioningMaintainer;
case "RetiringUpgrader" : return Agent.RetiringUpgrader;
}
throw new IllegalArgumentException("Unknown node event agent '" + eventAgentField.asString() + "'");
} | case "RetiringUpgrader" : return Agent.RetiringUpgrader; | private Agent eventAgentFromSlime(Inspector eventAgentField) {
switch (eventAgentField.asString()) {
case "operator" : return Agent.operator;
case "application" : return Agent.application;
case "system" : return Agent.system;
case "NodeFailer" : return Agent.NodeFailer;
case "Rebalancer" : return Agent.Rebalancer;
case "DirtyExpirer" : return Agent.DirtyExpirer;
case "FailedExpirer" : return Agent.FailedExpirer;
case "InactiveExpirer" : return Agent.InactiveExpirer;
case "ProvisionedExpirer" : return Agent.ProvisionedExpirer;
case "ReservationExpirer" : return Agent.ReservationExpirer;
case "DynamicProvisioningMaintainer" : return Agent.DynamicProvisioningMaintainer;
case "RetiringUpgrader" : return Agent.RetiringUpgrader;
}
throw new IllegalArgumentException("Unknown node event agent '" + eventAgentField.asString() + "'");
} | class NodeSerializer {
/** The configured node flavors */
private final NodeFlavors flavors;
private static final String hostnameKey = "hostname";
private static final String ipAddressesKey = "ipAddresses";
private static final String ipAddressPoolKey = "additionalIpAddresses";
private static final String idKey = "openStackId";
private static final String parentHostnameKey = "parentHostname";
private static final String historyKey = "history";
private static final String instanceKey = "instance";
private static final String rebootGenerationKey = "rebootGeneration";
private static final String currentRebootGenerationKey = "currentRebootGeneration";
private static final String vespaVersionKey = "vespaVersion";
private static final String currentDockerImageKey = "currentDockerImage";
private static final String failCountKey = "failCount";
private static final String nodeTypeKey = "type";
private static final String wantToRetireKey = "wantToRetire";
private static final String wantToDeprovisionKey = "wantToDeprovision";
private static final String osVersionKey = "osVersion";
private static final String wantedOsVersionKey = "wantedOsVersion";
private static final String firmwareCheckKey = "firmwareCheck";
private static final String reportsKey = "reports";
private static final String modelNameKey = "modelName";
private static final String reservedToKey = "reservedTo";
private static final String flavorKey = "flavor";
private static final String resourcesKey = "resources";
private static final String diskKey = "disk";
private static final String tenantIdKey = "tenantId";
private static final String applicationIdKey = "applicationId";
private static final String instanceIdKey = "instanceId";
private static final String serviceIdKey = "serviceId";
private static final String requestedResourcesKey = "requestedResources";
private static final String restartGenerationKey = "restartGeneration";
private static final String currentRestartGenerationKey = "currentRestartGeneration";
private static final String removableKey = "removable";
private static final String wantedVespaVersionKey = "wantedVespaVersion";
private static final String wantedDockerImageRepoKey = "wantedDockerImageRepo";
private static final String historyEventTypeKey = "type";
private static final String atKey = "at";
private static final String agentKey = "agent";
private static final String networkPortsKey = "networkPorts";
public NodeSerializer(NodeFlavors flavors) {
this.flavors = flavors;
}
public byte[] toJson(Node node) {
try {
Slime slime = new Slime();
toSlime(node, slime.setObject());
return SlimeUtils.toJsonBytes(slime);
}
catch (IOException e) {
throw new RuntimeException("Serialization of " + node + " to json failed", e);
}
}
private void toSlime(Node node, Cursor object) {
object.setString(hostnameKey, node.hostname());
toSlime(node.ipConfig().primary(), object.setArray(ipAddressesKey), IP.Config::require);
toSlime(node.ipConfig().pool().asSet(), object.setArray(ipAddressPoolKey), UnaryOperator.identity() /* Pool already holds a validated address list */);
object.setString(idKey, node.id());
node.parentHostname().ifPresent(hostname -> object.setString(parentHostnameKey, hostname));
toSlime(node.flavor(), object);
object.setLong(rebootGenerationKey, node.status().reboot().wanted());
object.setLong(currentRebootGenerationKey, node.status().reboot().current());
node.status().vespaVersion().ifPresent(version -> object.setString(vespaVersionKey, version.toString()));
node.status().dockerImage().ifPresent(image -> object.setString(currentDockerImageKey, image.asString()));
object.setLong(failCountKey, node.status().failCount());
object.setBool(wantToRetireKey, node.status().wantToRetire());
object.setBool(wantToDeprovisionKey, node.status().wantToDeprovision());
node.allocation().ifPresent(allocation -> toSlime(allocation, object.setObject(instanceKey)));
toSlime(node.history(), object.setArray(historyKey));
object.setString(nodeTypeKey, toString(node.type()));
node.status().osVersion().current().ifPresent(version -> object.setString(osVersionKey, version.toString()));
node.status().osVersion().wanted().ifPresent(version -> object.setString(wantedOsVersionKey, version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong(firmwareCheckKey, instant.toEpochMilli()));
node.reports().toSlime(object, reportsKey);
node.modelName().ifPresent(modelName -> object.setString(modelNameKey, modelName));
node.reservedTo().ifPresent(tenant -> object.setString(reservedToKey, tenant.value()));
}
private void toSlime(Flavor flavor, Cursor object) {
if (flavor.isConfigured()) {
object.setString(flavorKey, flavor.name());
if (flavor.flavorOverrides().isPresent()) {
Cursor resourcesObject = object.setObject(resourcesKey);
flavor.flavorOverrides().get().diskGb().ifPresent(diskGb -> resourcesObject.setDouble(diskKey, diskGb));
}
}
else {
NodeResourcesSerializer.toSlime(flavor.resources(), object.setObject(resourcesKey));
}
}
private void toSlime(Allocation allocation, Cursor object) {
NodeResourcesSerializer.toSlime(allocation.requestedResources(), object.setObject(requestedResourcesKey));
object.setString(tenantIdKey, allocation.owner().tenant().value());
object.setString(applicationIdKey, allocation.owner().application().value());
object.setString(instanceIdKey, allocation.owner().instance().value());
object.setString(serviceIdKey, allocation.membership().stringValue());
object.setLong(restartGenerationKey, allocation.restartGeneration().wanted());
object.setLong(currentRestartGenerationKey, allocation.restartGeneration().current());
object.setBool(removableKey, allocation.isRemovable());
object.setString(wantedVespaVersionKey, allocation.membership().cluster().vespaVersion().toString());
allocation.membership().cluster().dockerImageRepo().ifPresent(repo -> object.setString(wantedDockerImageRepoKey, repo.repository()));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray(networkPortsKey)));
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events())
toSlime(event, array.addObject());
}
private void toSlime(History.Event event, Cursor object) {
object.setString(historyEventTypeKey, toString(event.type()));
object.setLong(atKey, event.at().toEpochMilli());
object.setString(agentKey, toString(event.agent()));
}
private void toSlime(Set<String> ipAddresses, Cursor array, UnaryOperator<Set<String>> validator) {
validator.apply(ipAddresses).stream().sorted(IP.NATURAL_ORDER).forEach(array::addString);
}
public Node fromJson(Node.State state, byte[] data) {
return nodeFromSlime(state, SlimeUtils.jsonToSlime(data).get());
}
private Node nodeFromSlime(Node.State state, Inspector object) {
Flavor flavor = flavorFromSlime(object);
return new Node(object.field(idKey).asString(),
new IP.Config(ipAddressesFromSlime(object, ipAddressesKey),
ipAddressesFromSlime(object, ipAddressPoolKey)),
object.field(hostnameKey).asString(),
parentHostnameFromSlime(object),
flavor,
statusFromSlime(object),
state,
allocationFromSlime(flavor.resources(), object.field(instanceKey)),
historyFromSlime(object.field(historyKey)),
nodeTypeFromString(object.field(nodeTypeKey).asString()),
Reports.fromSlime(object.field(reportsKey)),
modelNameFromSlime(object),
reservedToFromSlime(object.field(reservedToKey)));
}
private Status statusFromSlime(Inspector object) {
return new Status(generationFromSlime(object, rebootGenerationKey, currentRebootGenerationKey),
versionFromSlime(object.field(vespaVersionKey)),
dockerImageFromSlime(object.field(currentDockerImageKey)),
(int) object.field(failCountKey).asLong(),
object.field(wantToRetireKey).asBool(),
object.field(wantToDeprovisionKey).asBool(),
new OsVersion(versionFromSlime(object.field(osVersionKey)),
versionFromSlime(object.field(wantedOsVersionKey))),
instantFromSlime(object.field(firmwareCheckKey)));
}
private Flavor flavorFromSlime(Inspector object) {
Inspector resources = object.field(resourcesKey);
if (object.field(flavorKey).valid()) {
Flavor flavor = flavors.getFlavorOrThrow(object.field(flavorKey).asString());
if (!resources.valid()) return flavor;
return flavor.with(FlavorOverrides.ofDisk(resources.field(diskKey).asDouble()));
}
else {
return new Flavor(NodeResourcesSerializer.resourcesFromSlime(resources));
}
}
private Optional<Allocation> allocationFromSlime(NodeResources assignedResources, Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new Allocation(applicationIdFromSlime(object),
clusterMembershipFromSlime(object),
NodeResourcesSerializer.optionalResourcesFromSlime(object.field(requestedResourcesKey))
.orElse(assignedResources),
generationFromSlime(object, restartGenerationKey, currentRestartGenerationKey),
object.field(removableKey).asBool(),
NetworkPortsSerializer.fromSlime(object.field(networkPortsKey))));
}
private ApplicationId applicationIdFromSlime(Inspector object) {
return ApplicationId.from(TenantName.from(object.field(tenantIdKey).asString()),
ApplicationName.from(object.field(applicationIdKey).asString()),
InstanceName.from(object.field(instanceIdKey).asString()));
}
private History historyFromSlime(Inspector array) {
List<History.Event> events = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> {
History.Event event = eventFromSlime(item);
if (event != null)
events.add(event);
});
return new History(events);
}
private History.Event eventFromSlime(Inspector object) {
History.Event.Type type = eventTypeFromString(object.field(historyEventTypeKey).asString());
if (type == null) return null;
Instant at = Instant.ofEpochMilli(object.field(atKey).asLong());
Agent agent = eventAgentFromSlime(object.field(agentKey));
return new History.Event(type, agent, at);
}
private Generation generationFromSlime(Inspector object, String wantedField, String currentField) {
Inspector current = object.field(currentField);
return new Generation(object.field(wantedField).asLong(), current.asLong());
}
private ClusterMembership clusterMembershipFromSlime(Inspector object) {
return ClusterMembership.from(object.field(serviceIdKey).asString(),
versionFromSlime(object.field(wantedVespaVersionKey)).get(),
dockerImageRepoFromSlime(object.field(wantedDockerImageRepoKey)));
}
private Optional<Version> versionFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(Version.fromString(object.asString()));
}
private Optional<DockerImage> dockerImageRepoFromSlime(Inspector object) {
if ( ! object.valid() || object.asString().isEmpty()) return Optional.empty();
return Optional.of(DockerImage.fromString(object.asString()));
}
private Optional<DockerImage> dockerImageFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(DockerImage.fromString(object.asString()));
}
private Optional<Instant> instantFromSlime(Inspector object) {
if ( ! object.valid())
return Optional.empty();
return Optional.of(Instant.ofEpochMilli(object.asLong()));
}
private Optional<String> parentHostnameFromSlime(Inspector object) {
if (object.field(parentHostnameKey).valid())
return Optional.of(object.field(parentHostnameKey).asString());
else
return Optional.empty();
}
private Set<String> ipAddressesFromSlime(Inspector object, String key) {
ImmutableSet.Builder<String> ipAddresses = ImmutableSet.builder();
object.field(key).traverse((ArrayTraverser) (i, item) -> ipAddresses.add(item.asString()));
return ipAddresses.build();
}
private Optional<String> modelNameFromSlime(Inspector object) {
if (object.field(modelNameKey).valid()) {
return Optional.of(object.field(modelNameKey).asString());
}
return Optional.empty();
}
private Optional<TenantName> reservedToFromSlime(Inspector object) {
if (! object.valid()) return Optional.empty();
if (object.type() != Type.STRING)
throw new IllegalArgumentException("Expected 'reservedTo' to be a string but is " + object);
return Optional.of(TenantName.from(object.asString()));
}
/** Returns the event type, or null if this event type should be ignored */
private History.Event.Type eventTypeFromString(String eventTypeString) {
switch (eventTypeString) {
case "provisioned" : return History.Event.Type.provisioned;
case "deprovisioned" : return History.Event.Type.deprovisioned;
case "readied" : return History.Event.Type.readied;
case "reserved" : return History.Event.Type.reserved;
case "activated" : return History.Event.Type.activated;
case "wantToRetire": return History.Event.Type.wantToRetire;
case "retired" : return History.Event.Type.retired;
case "deactivated" : return History.Event.Type.deactivated;
case "parked" : return History.Event.Type.parked;
case "failed" : return History.Event.Type.failed;
case "deallocated" : return History.Event.Type.deallocated;
case "down" : return History.Event.Type.down;
case "requested" : return History.Event.Type.requested;
case "rebooted" : return History.Event.Type.rebooted;
case "osUpgraded" : return History.Event.Type.osUpgraded;
case "firmwareVerified" : return History.Event.Type.firmwareVerified;
}
throw new IllegalArgumentException("Unknown node event type '" + eventTypeString + "'");
}
private String toString(History.Event.Type nodeEventType) {
switch (nodeEventType) {
case provisioned : return "provisioned";
case deprovisioned : return "deprovisioned";
case readied : return "readied";
case reserved : return "reserved";
case activated : return "activated";
case wantToRetire: return "wantToRetire";
case retired : return "retired";
case deactivated : return "deactivated";
case parked : return "parked";
case failed : return "failed";
case deallocated : return "deallocated";
case down : return "down";
case requested: return "requested";
case rebooted: return "rebooted";
case osUpgraded: return "osUpgraded";
case firmwareVerified: return "firmwareVerified";
}
throw new IllegalArgumentException("Serialized form of '" + nodeEventType + "' not defined");
}
private String toString(Agent agent) {
switch (agent) {
case operator : return "operator";
case application : return "application";
case system : return "system";
case NodeFailer : return "NodeFailer";
case Rebalancer : return "Rebalancer";
case DirtyExpirer : return "DirtyExpirer";
case FailedExpirer : return "FailedExpirer";
case InactiveExpirer : return "InactiveExpirer";
case ProvisionedExpirer : return "ProvisionedExpirer";
case ReservationExpirer : return "ReservationExpirer";
case DynamicProvisioningMaintainer : return "DynamicProvisioningMaintainer";
case RetiringUpgrader: return "RetiringUpgrader";
}
throw new IllegalArgumentException("Serialized form of '" + agent + "' not defined");
}
static NodeType nodeTypeFromString(String typeString) {
switch (typeString) {
case "tenant": return NodeType.tenant;
case "host": return NodeType.host;
case "proxy": return NodeType.proxy;
case "proxyhost": return NodeType.proxyhost;
case "config": return NodeType.config;
case "confighost": return NodeType.confighost;
case "controller": return NodeType.controller;
case "controllerhost": return NodeType.controllerhost;
case "devhost": return NodeType.devhost;
default : throw new IllegalArgumentException("Unknown node type '" + typeString + "'");
}
}
static String toString(NodeType type) {
switch (type) {
case tenant: return "tenant";
case host: return "host";
case proxy: return "proxy";
case proxyhost: return "proxyhost";
case config: return "config";
case confighost: return "confighost";
case controller: return "controller";
case controllerhost: return "controllerhost";
case devhost: return "devhost";
}
throw new IllegalArgumentException("Serialized form of '" + type + "' not defined");
}
} | class NodeSerializer {
/** The configured node flavors */
private final NodeFlavors flavors;
private static final String hostnameKey = "hostname";
private static final String ipAddressesKey = "ipAddresses";
private static final String ipAddressPoolKey = "additionalIpAddresses";
private static final String idKey = "openStackId";
private static final String parentHostnameKey = "parentHostname";
private static final String historyKey = "history";
private static final String instanceKey = "instance";
private static final String rebootGenerationKey = "rebootGeneration";
private static final String currentRebootGenerationKey = "currentRebootGeneration";
private static final String vespaVersionKey = "vespaVersion";
private static final String currentDockerImageKey = "currentDockerImage";
private static final String failCountKey = "failCount";
private static final String nodeTypeKey = "type";
private static final String wantToRetireKey = "wantToRetire";
private static final String wantToDeprovisionKey = "wantToDeprovision";
private static final String osVersionKey = "osVersion";
private static final String wantedOsVersionKey = "wantedOsVersion";
private static final String firmwareCheckKey = "firmwareCheck";
private static final String reportsKey = "reports";
private static final String modelNameKey = "modelName";
private static final String reservedToKey = "reservedTo";
private static final String flavorKey = "flavor";
private static final String resourcesKey = "resources";
private static final String diskKey = "disk";
private static final String tenantIdKey = "tenantId";
private static final String applicationIdKey = "applicationId";
private static final String instanceIdKey = "instanceId";
private static final String serviceIdKey = "serviceId";
private static final String requestedResourcesKey = "requestedResources";
private static final String restartGenerationKey = "restartGeneration";
private static final String currentRestartGenerationKey = "currentRestartGeneration";
private static final String removableKey = "removable";
private static final String wantedVespaVersionKey = "wantedVespaVersion";
private static final String wantedDockerImageRepoKey = "wantedDockerImageRepo";
private static final String historyEventTypeKey = "type";
private static final String atKey = "at";
private static final String agentKey = "agent";
private static final String networkPortsKey = "networkPorts";
public NodeSerializer(NodeFlavors flavors) {
this.flavors = flavors;
}
public byte[] toJson(Node node) {
try {
Slime slime = new Slime();
toSlime(node, slime.setObject());
return SlimeUtils.toJsonBytes(slime);
}
catch (IOException e) {
throw new RuntimeException("Serialization of " + node + " to json failed", e);
}
}
private void toSlime(Node node, Cursor object) {
object.setString(hostnameKey, node.hostname());
toSlime(node.ipConfig().primary(), object.setArray(ipAddressesKey), IP.Config::require);
toSlime(node.ipConfig().pool().asSet(), object.setArray(ipAddressPoolKey), UnaryOperator.identity() /* Pool already holds a validated address list */);
object.setString(idKey, node.id());
node.parentHostname().ifPresent(hostname -> object.setString(parentHostnameKey, hostname));
toSlime(node.flavor(), object);
object.setLong(rebootGenerationKey, node.status().reboot().wanted());
object.setLong(currentRebootGenerationKey, node.status().reboot().current());
node.status().vespaVersion().ifPresent(version -> object.setString(vespaVersionKey, version.toString()));
node.status().dockerImage().ifPresent(image -> object.setString(currentDockerImageKey, image.asString()));
object.setLong(failCountKey, node.status().failCount());
object.setBool(wantToRetireKey, node.status().wantToRetire());
object.setBool(wantToDeprovisionKey, node.status().wantToDeprovision());
node.allocation().ifPresent(allocation -> toSlime(allocation, object.setObject(instanceKey)));
toSlime(node.history(), object.setArray(historyKey));
object.setString(nodeTypeKey, toString(node.type()));
node.status().osVersion().current().ifPresent(version -> object.setString(osVersionKey, version.toString()));
node.status().osVersion().wanted().ifPresent(version -> object.setString(wantedOsVersionKey, version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong(firmwareCheckKey, instant.toEpochMilli()));
node.reports().toSlime(object, reportsKey);
node.modelName().ifPresent(modelName -> object.setString(modelNameKey, modelName));
node.reservedTo().ifPresent(tenant -> object.setString(reservedToKey, tenant.value()));
}
private void toSlime(Flavor flavor, Cursor object) {
if (flavor.isConfigured()) {
object.setString(flavorKey, flavor.name());
if (flavor.flavorOverrides().isPresent()) {
Cursor resourcesObject = object.setObject(resourcesKey);
flavor.flavorOverrides().get().diskGb().ifPresent(diskGb -> resourcesObject.setDouble(diskKey, diskGb));
}
}
else {
NodeResourcesSerializer.toSlime(flavor.resources(), object.setObject(resourcesKey));
}
}
private void toSlime(Allocation allocation, Cursor object) {
NodeResourcesSerializer.toSlime(allocation.requestedResources(), object.setObject(requestedResourcesKey));
object.setString(tenantIdKey, allocation.owner().tenant().value());
object.setString(applicationIdKey, allocation.owner().application().value());
object.setString(instanceIdKey, allocation.owner().instance().value());
object.setString(serviceIdKey, allocation.membership().stringValue());
object.setLong(restartGenerationKey, allocation.restartGeneration().wanted());
object.setLong(currentRestartGenerationKey, allocation.restartGeneration().current());
object.setBool(removableKey, allocation.isRemovable());
object.setString(wantedVespaVersionKey, allocation.membership().cluster().vespaVersion().toString());
allocation.membership().cluster().dockerImageRepo().ifPresent(repo -> object.setString(wantedDockerImageRepoKey, repo.repository()));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray(networkPortsKey)));
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events())
toSlime(event, array.addObject());
}
private void toSlime(History.Event event, Cursor object) {
object.setString(historyEventTypeKey, toString(event.type()));
object.setLong(atKey, event.at().toEpochMilli());
object.setString(agentKey, toString(event.agent()));
}
private void toSlime(Set<String> ipAddresses, Cursor array, UnaryOperator<Set<String>> validator) {
validator.apply(ipAddresses).stream().sorted(IP.NATURAL_ORDER).forEach(array::addString);
}
public Node fromJson(Node.State state, byte[] data) {
return nodeFromSlime(state, SlimeUtils.jsonToSlime(data).get());
}
private Node nodeFromSlime(Node.State state, Inspector object) {
Flavor flavor = flavorFromSlime(object);
return new Node(object.field(idKey).asString(),
new IP.Config(ipAddressesFromSlime(object, ipAddressesKey),
ipAddressesFromSlime(object, ipAddressPoolKey)),
object.field(hostnameKey).asString(),
parentHostnameFromSlime(object),
flavor,
statusFromSlime(object),
state,
allocationFromSlime(flavor.resources(), object.field(instanceKey)),
historyFromSlime(object.field(historyKey)),
nodeTypeFromString(object.field(nodeTypeKey).asString()),
Reports.fromSlime(object.field(reportsKey)),
modelNameFromSlime(object),
reservedToFromSlime(object.field(reservedToKey)));
}
private Status statusFromSlime(Inspector object) {
return new Status(generationFromSlime(object, rebootGenerationKey, currentRebootGenerationKey),
versionFromSlime(object.field(vespaVersionKey)),
dockerImageFromSlime(object.field(currentDockerImageKey)),
(int) object.field(failCountKey).asLong(),
object.field(wantToRetireKey).asBool(),
object.field(wantToDeprovisionKey).asBool(),
new OsVersion(versionFromSlime(object.field(osVersionKey)),
versionFromSlime(object.field(wantedOsVersionKey))),
instantFromSlime(object.field(firmwareCheckKey)));
}
private Flavor flavorFromSlime(Inspector object) {
Inspector resources = object.field(resourcesKey);
if (object.field(flavorKey).valid()) {
Flavor flavor = flavors.getFlavorOrThrow(object.field(flavorKey).asString());
if (!resources.valid()) return flavor;
return flavor.with(FlavorOverrides.ofDisk(resources.field(diskKey).asDouble()));
}
else {
return new Flavor(NodeResourcesSerializer.resourcesFromSlime(resources));
}
}
private Optional<Allocation> allocationFromSlime(NodeResources assignedResources, Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new Allocation(applicationIdFromSlime(object),
clusterMembershipFromSlime(object),
NodeResourcesSerializer.optionalResourcesFromSlime(object.field(requestedResourcesKey))
.orElse(assignedResources),
generationFromSlime(object, restartGenerationKey, currentRestartGenerationKey),
object.field(removableKey).asBool(),
NetworkPortsSerializer.fromSlime(object.field(networkPortsKey))));
}
private ApplicationId applicationIdFromSlime(Inspector object) {
return ApplicationId.from(TenantName.from(object.field(tenantIdKey).asString()),
ApplicationName.from(object.field(applicationIdKey).asString()),
InstanceName.from(object.field(instanceIdKey).asString()));
}
private History historyFromSlime(Inspector array) {
List<History.Event> events = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> {
History.Event event = eventFromSlime(item);
if (event != null)
events.add(event);
});
return new History(events);
}
private History.Event eventFromSlime(Inspector object) {
History.Event.Type type = eventTypeFromString(object.field(historyEventTypeKey).asString());
if (type == null) return null;
Instant at = Instant.ofEpochMilli(object.field(atKey).asLong());
Agent agent = eventAgentFromSlime(object.field(agentKey));
return new History.Event(type, agent, at);
}
private Generation generationFromSlime(Inspector object, String wantedField, String currentField) {
Inspector current = object.field(currentField);
return new Generation(object.field(wantedField).asLong(), current.asLong());
}
private ClusterMembership clusterMembershipFromSlime(Inspector object) {
return ClusterMembership.from(object.field(serviceIdKey).asString(),
versionFromSlime(object.field(wantedVespaVersionKey)).get(),
dockerImageRepoFromSlime(object.field(wantedDockerImageRepoKey)));
}
private Optional<Version> versionFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(Version.fromString(object.asString()));
}
private Optional<DockerImage> dockerImageRepoFromSlime(Inspector object) {
if ( ! object.valid() || object.asString().isEmpty()) return Optional.empty();
return Optional.of(DockerImage.fromString(object.asString()));
}
private Optional<DockerImage> dockerImageFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(DockerImage.fromString(object.asString()));
}
private Optional<Instant> instantFromSlime(Inspector object) {
if ( ! object.valid())
return Optional.empty();
return Optional.of(Instant.ofEpochMilli(object.asLong()));
}
private Optional<String> parentHostnameFromSlime(Inspector object) {
if (object.field(parentHostnameKey).valid())
return Optional.of(object.field(parentHostnameKey).asString());
else
return Optional.empty();
}
private Set<String> ipAddressesFromSlime(Inspector object, String key) {
ImmutableSet.Builder<String> ipAddresses = ImmutableSet.builder();
object.field(key).traverse((ArrayTraverser) (i, item) -> ipAddresses.add(item.asString()));
return ipAddresses.build();
}
private Optional<String> modelNameFromSlime(Inspector object) {
if (object.field(modelNameKey).valid()) {
return Optional.of(object.field(modelNameKey).asString());
}
return Optional.empty();
}
private Optional<TenantName> reservedToFromSlime(Inspector object) {
if (! object.valid()) return Optional.empty();
if (object.type() != Type.STRING)
throw new IllegalArgumentException("Expected 'reservedTo' to be a string but is " + object);
return Optional.of(TenantName.from(object.asString()));
}
/** Returns the event type, or null if this event type should be ignored */
private History.Event.Type eventTypeFromString(String eventTypeString) {
switch (eventTypeString) {
case "provisioned" : return History.Event.Type.provisioned;
case "deprovisioned" : return History.Event.Type.deprovisioned;
case "readied" : return History.Event.Type.readied;
case "reserved" : return History.Event.Type.reserved;
case "activated" : return History.Event.Type.activated;
case "wantToRetire": return History.Event.Type.wantToRetire;
case "retired" : return History.Event.Type.retired;
case "deactivated" : return History.Event.Type.deactivated;
case "parked" : return History.Event.Type.parked;
case "failed" : return History.Event.Type.failed;
case "deallocated" : return History.Event.Type.deallocated;
case "down" : return History.Event.Type.down;
case "requested" : return History.Event.Type.requested;
case "rebooted" : return History.Event.Type.rebooted;
case "osUpgraded" : return History.Event.Type.osUpgraded;
case "firmwareVerified" : return History.Event.Type.firmwareVerified;
}
throw new IllegalArgumentException("Unknown node event type '" + eventTypeString + "'");
}
private String toString(History.Event.Type nodeEventType) {
switch (nodeEventType) {
case provisioned : return "provisioned";
case deprovisioned : return "deprovisioned";
case readied : return "readied";
case reserved : return "reserved";
case activated : return "activated";
case wantToRetire: return "wantToRetire";
case retired : return "retired";
case deactivated : return "deactivated";
case parked : return "parked";
case failed : return "failed";
case deallocated : return "deallocated";
case down : return "down";
case requested: return "requested";
case rebooted: return "rebooted";
case osUpgraded: return "osUpgraded";
case firmwareVerified: return "firmwareVerified";
}
throw new IllegalArgumentException("Serialized form of '" + nodeEventType + "' not defined");
}
private String toString(Agent agent) {
switch (agent) {
case operator : return "operator";
case application : return "application";
case system : return "system";
case NodeFailer : return "NodeFailer";
case Rebalancer : return "Rebalancer";
case DirtyExpirer : return "DirtyExpirer";
case FailedExpirer : return "FailedExpirer";
case InactiveExpirer : return "InactiveExpirer";
case ProvisionedExpirer : return "ProvisionedExpirer";
case ReservationExpirer : return "ReservationExpirer";
case DynamicProvisioningMaintainer : return "DynamicProvisioningMaintainer";
case RetiringUpgrader: return "RetiringUpgrader";
}
throw new IllegalArgumentException("Serialized form of '" + agent + "' not defined");
}
static NodeType nodeTypeFromString(String typeString) {
switch (typeString) {
case "tenant": return NodeType.tenant;
case "host": return NodeType.host;
case "proxy": return NodeType.proxy;
case "proxyhost": return NodeType.proxyhost;
case "config": return NodeType.config;
case "confighost": return NodeType.confighost;
case "controller": return NodeType.controller;
case "controllerhost": return NodeType.controllerhost;
case "devhost": return NodeType.devhost;
default : throw new IllegalArgumentException("Unknown node type '" + typeString + "'");
}
}
static String toString(NodeType type) {
switch (type) {
case tenant: return "tenant";
case host: return "host";
case proxy: return "proxy";
case proxyhost: return "proxyhost";
case config: return "config";
case confighost: return "confighost";
case controller: return "controller";
case controllerhost: return "controllerhost";
case devhost: return "devhost";
}
throw new IllegalArgumentException("Serialized form of '" + type + "' not defined");
}
} |
I would have thought the one create by this would suffice? | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct()); | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} |
I think that all are created by this one. | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct()); | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} |
Well, after sleeping on this one I am no longer certain about the life time about this one. I looked at the ComponentRegistry and saw that it was freezeable and assumed it would be frozen once component graph was set up, and hence not being possible to unregister anything. But that assumption might be wrong. No tests failed due to this, but that might be due that the 60s grace period. @gjoranv could you have a look at this one. | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct()); | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} |
This will deconstruct all DocprocServices, regardless of whether they survive the next reconfig or not. The injected registry contains _all_ of them, no matter which generation they were created in. | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct()); | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} |
That was the the creeping feeling I had. | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct()); | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} |
That was my objection yesterday, but it seems the registry is created in the constructor of this handler, not injected. | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct()); | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} |
The other registries are injected, but not the one used for the `DocprocService`es, which are the ones with the thread pools that weren't shut down. | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct()); | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} |
Since this is based on randomness, should we have a separate constructor overload for `AdaptiveLoadBalancer` taking in `Random` instance explicitly? This would allow us to use a deterministic seed for unit tests. | public void testAdaptiveLoadBalancer() {
LoadBalancer lb = new AdaptiveLoadBalancer("foo");
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
}
long sentSum = 0;
for (var metrics : weights) {
assertTrue(10 > Math.abs(metrics.sent() - 3333));
sentSum += metrics.sent();
}
assertEquals(9999, sentSum);
for (var metrics : weights) {
metrics.reset();
}
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
if (node.entry.getName().contains("1")) {
lb.received(node, false);
} else if (node.entry.getName().contains("2")) {
if ((i % 2) == 0) {
lb.received(node, false);
}
} else {
if ((i % 4) == 0) {
lb.received(node, false);
}
}
}
sentSum = 0;
long sumPending = 0;
for (var metrics : weights) {
System.out.println("m: s=" + metrics.sent() + " p=" + metrics.pending());
sentSum += metrics.sent();
sumPending += metrics.pending();
}
assertEquals(9999, sentSum);
assertTrue(200 > Math.abs(sumPending - 2700));
assertTrue( 100 > Math.abs(weights.get(0).sent() - 1780));
assertTrue( 200 > Math.abs(weights.get(1).sent() - 5500));
assertTrue( 100 > Math.abs(weights.get(2).sent() - 2650));
assertTrue( 100 > Math.abs(weights.get(0).pending() - 1340));
assertEquals( 0, weights.get(1).pending());
assertTrue( 100 > Math.abs(weights.get(2).pending() - 1340));
} | assertTrue(10 > Math.abs(metrics.sent() - 3333)); | public void testAdaptiveLoadBalancer() {
LoadBalancer lb = new AdaptiveLoadBalancer("foo", new Random(1));
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
}
long sentSum = 0;
for (var metrics : weights) {
assertTrue(10 > Math.abs(metrics.sent() - 3333));
sentSum += metrics.sent();
}
assertEquals(9999, sentSum);
for (var metrics : weights) {
metrics.reset();
}
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
if (node.entry.getName().contains("1")) {
lb.received(node, false);
} else if (node.entry.getName().contains("2")) {
if ((i % 2) == 0) {
lb.received(node, false);
}
} else {
if ((i % 4) == 0) {
lb.received(node, false);
}
}
}
sentSum = 0;
long sumPending = 0;
for (var metrics : weights) {
System.out.println("m: s=" + metrics.sent() + " p=" + metrics.pending());
sentSum += metrics.sent();
sumPending += metrics.pending();
}
assertEquals(9999, sentSum);
assertEquals(2039, sumPending);
assertEquals(1332, weights.get(0).sent());
assertEquals(6645, weights.get(1).sent());
assertEquals(2022, weights.get(2).sent());
assertEquals(1020, weights.get(0).pending());
assertEquals(0, weights.get(1).pending());
assertEquals(1019, weights.get(2).pending());
} | class LoadBalancerTestCase {
@Test
public void requireThatParseExceptionIsReadable() {
assertIllegalArgument("foo", "bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'bar'.");
assertIllegalArgument("foo", "foobar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foobar'.");
assertIllegalArgument("foo", "foo", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo'.");
assertIllegalArgument("foo", "foo/", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/'.");
assertIllegalArgument("foo", "foo/0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0'.");
assertIllegalArgument("foo", "foo/0.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.'.");
assertIllegalArgument("foo", "foo/0.bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.bar'.");
assertIllegalArgument("foo", "foo/bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar'.");
assertIllegalArgument("foo", "foo/bar.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.'.");
assertIllegalArgument("foo", "foo/bar.0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.0'.");
}
private static void assertIllegalArgument(String clusterName, String recipient, String expectedMessage) {
LegacyLoadBalancer policy = new LegacyLoadBalancer(clusterName);
try {
fail("Expected exception, got index " + policy.getIndex(recipient) + ".");
} catch (IllegalArgumentException e) {
assertEquals(expectedMessage, e.getMessage());
}
}
@Test
public void testLoadBalancerCreation() {
LoadBalancerPolicy lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=legacy");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=adaptive");
assertTrue(lbp.getLoadBalancer() instanceof AdaptiveLoadBalancer);
}
@Test
@Test
public void testLegacyLoadBalancer() {
LoadBalancer lb = new LegacyLoadBalancer("foo");
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
{
for (int i = 0; i < 99; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertEquals("foo/" + (i % 3) + "/default" , node.entry.getName());
}
assertEquals(33, weights.get(0).sent());
assertEquals(33, weights.get(1).sent());
assertEquals(33, weights.get(2).sent());
weights.get(0).reset();
weights.get(1).reset();
weights.get(2).reset();
}
{
for (int i = 0; i < 100; i++) {
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), false);
}
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(0)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(100, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(2)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
}
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/1/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
private void verifyLoadBalancerOneItemOnly(LoadBalancer lb) {
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1") );
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
@Test
public void testLoadBalancerOneItemOnly() {
verifyLoadBalancerOneItemOnly(new LegacyLoadBalancer("foo"));
verifyLoadBalancerOneItemOnly(new AdaptiveLoadBalancer("foo"));
}
} | class LoadBalancerTestCase {
@Test
public void requireThatParseExceptionIsReadable() {
assertIllegalArgument("foo", "bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'bar'.");
assertIllegalArgument("foo", "foobar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foobar'.");
assertIllegalArgument("foo", "foo", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo'.");
assertIllegalArgument("foo", "foo/", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/'.");
assertIllegalArgument("foo", "foo/0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0'.");
assertIllegalArgument("foo", "foo/0.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.'.");
assertIllegalArgument("foo", "foo/0.bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.bar'.");
assertIllegalArgument("foo", "foo/bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar'.");
assertIllegalArgument("foo", "foo/bar.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.'.");
assertIllegalArgument("foo", "foo/bar.0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.0'.");
}
private static void assertIllegalArgument(String clusterName, String recipient, String expectedMessage) {
LegacyLoadBalancer policy = new LegacyLoadBalancer(clusterName);
try {
fail("Expected exception, got index " + policy.getIndex(recipient) + ".");
} catch (IllegalArgumentException e) {
assertEquals(expectedMessage, e.getMessage());
}
}
@Test
public void testLoadBalancerCreation() {
LoadBalancerPolicy lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=legacy");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=adaptive");
assertTrue(lbp.getLoadBalancer() instanceof AdaptiveLoadBalancer);
}
@Test
@Test
public void testLegacyLoadBalancer() {
LoadBalancer lb = new LegacyLoadBalancer("foo");
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
{
for (int i = 0; i < 99; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertEquals("foo/" + (i % 3) + "/default" , node.entry.getName());
}
assertEquals(33, weights.get(0).sent());
assertEquals(33, weights.get(1).sent());
assertEquals(33, weights.get(2).sent());
weights.get(0).reset();
weights.get(1).reset();
weights.get(2).reset();
}
{
for (int i = 0; i < 100; i++) {
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), false);
}
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(0)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(100, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(2)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
}
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/1/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
private void verifyLoadBalancerOneItemOnly(LoadBalancer lb) {
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1") );
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
@Test
public void testLoadBalancerOneItemOnly() {
verifyLoadBalancerOneItemOnly(new LegacyLoadBalancer("foo"));
verifyLoadBalancerOneItemOnly(new AdaptiveLoadBalancer("foo"));
}
} |
Sorry, I looked at the wrong constructor. As @jonmv says, the registry is not injected. Without knowing the code in detail, it looks like all the DocprocServices are created by the handler instance. So this should be all good. | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct()); | protected void destroy() {
laterExecutor.shutdown();
docprocServiceRegistry.allComponents().forEach(docprocService -> docprocService.deconstruct());
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} | class DocumentProcessingHandler extends AbstractRequestHandler {
private static Logger log = Logger.getLogger(DocumentProcessingHandler.class.getName());
private final ComponentRegistry<DocprocService> docprocServiceRegistry;
private final ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry;
private final ChainRegistry<DocumentProcessor> chainRegistry = new ChainRegistry<>();
private final ScheduledThreadPoolExecutor laterExecutor =
new ScheduledThreadPoolExecutor(2, new DaemonThreadFactory("docproc-later-"));
private ContainerDocumentConfig containerDocConfig;
private final DocumentTypeManager documentTypeManager;
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
int numThreads,
DocumentTypeManager documentTypeManager,
ChainsModel chainsModel, SchemaMap schemaMap, Statistics statistics,
Metric metric,
ContainerDocumentConfig containerDocConfig) {
this.docprocServiceRegistry = docprocServiceRegistry;
this.docFactoryRegistry = docFactoryRegistry;
this.containerDocConfig = containerDocConfig;
this.documentTypeManager = documentTypeManager;
DocprocService.schemaMap = schemaMap;
laterExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
laterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
if (chainsModel != null) {
prepareChainRegistry(chainRegistry, chainsModel, documentProcessorComponentRegistry);
for (Chain<DocumentProcessor> chain : chainRegistry.allComponents()) {
log.config("Setting up call stack for chain " + chain.getId());
DocprocService service = new DocprocService(chain.getId(), convertToCallStack(chain, statistics, metric), documentTypeManager, computeNumThreads(numThreads));
service.setInService(true);
docprocServiceRegistry.register(service.getId(), service);
}
}
}
private static int computeNumThreads(int maxThreads) {
return (maxThreads > 0) ? maxThreads : Runtime.getRuntime().availableProcessors();
}
public DocumentProcessingHandler(ComponentRegistry<DocprocService> docprocServiceRegistry,
ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
DocumentProcessingHandlerParameters params) {
this(docprocServiceRegistry, documentProcessorComponentRegistry, docFactoryRegistry,
params.getMaxNumThreads(),
params.getDocumentTypeManager(), params.getChainsModel(), params.getSchemaMap(),
params.getStatisticsManager(),
params.getMetric(),
params.getContainerDocConfig());
}
@Inject
public DocumentProcessingHandler(ComponentRegistry<DocumentProcessor> documentProcessorComponentRegistry,
ComponentRegistry<AbstractConcreteDocumentFactory> docFactoryRegistry,
ChainsConfig chainsConfig,
SchemamappingConfig mappingConfig,
DocumentmanagerConfig docManConfig,
DocprocConfig docprocConfig,
ContainerMbusConfig containerMbusConfig,
ContainerDocumentConfig containerDocConfig,
Statistics manager,
Metric metric) {
this(new ComponentRegistry<>(),
documentProcessorComponentRegistry, docFactoryRegistry, new DocumentProcessingHandlerParameters().setMaxNumThreads
(docprocConfig.numthreads())
.setDocumentTypeManager(new DocumentTypeManager(docManConfig))
.setChainsModel(buildFromConfig(chainsConfig)).setSchemaMap(configureMapping(mappingConfig))
.setStatisticsManager(manager)
.setMetric(metric)
.setContainerDocumentConfig(containerDocConfig));
}
@Override
public ComponentRegistry<DocprocService> getDocprocServiceRegistry() {
return docprocServiceRegistry;
}
public ChainRegistry<DocumentProcessor> getChains() {
return chainRegistry;
}
private static SchemaMap configureMapping(SchemamappingConfig mappingConfig) {
SchemaMap map = new SchemaMap();
map.configure(mappingConfig);
return map;
}
private static CallStack convertToCallStack(Chain<DocumentProcessor> chain, Statistics statistics, Metric metric) {
CallStack stack = new CallStack(chain.getId().stringValue(), statistics, metric);
for (DocumentProcessor processor : chain.components()) {
processor.getFieldMap().putAll(DocprocService.schemaMap.chainMap(chain.getId().stringValue(), processor.getId().stringValue()));
stack.addLast(processor);
}
return stack;
}
@Override
public ContentChannel handleRequest(Request request, ResponseHandler handler) {
RequestContext requestContext;
if (request instanceof MbusRequest) {
requestContext = new MbusRequestContext((MbusRequest) request, handler, docprocServiceRegistry, docFactoryRegistry, containerDocConfig);
} else {
throw new IllegalArgumentException("Request type not supported: " + request);
}
if (!requestContext.isProcessable()) {
requestContext.skip();
return null;
}
String serviceName = requestContext.getServiceName();
DocprocService service = docprocServiceRegistry.getComponent(serviceName);
if (service == null) {
log.log(Level.SEVERE, "DocprocService for session '" + serviceName +
"' not found, returning request '" + requestContext + "'.");
requestContext.processingFailed(RequestContext.ErrorCode.ERROR_PROCESSING_FAILURE,
"DocprocService " + serviceName + " not found.");
return null;
} else if (service.getExecutor().getCallStack().size() == 0) {
requestContext.skip();
return null;
}
DocumentProcessingTask task = new DocumentProcessingTask(requestContext, this, service, service.getThreadPoolExecutor());
task.submit();
return null;
}
void submit(DocumentProcessingTask task, long delay) {
LaterTimerTask timerTask = new LaterTimerTask(task, delay);
laterExecutor.schedule(timerTask, delay, TimeUnit.MILLISECONDS);
}
private class LaterTimerTask extends TimerTask {
private DocumentProcessingTask processingTask;
private long delay;
private LaterTimerTask(DocumentProcessingTask processingTask, long delay) {
this.delay = delay;
log.log(Level.FINE, "Enqueueing in " + delay + " ms due to Progress.LATER: " + processingTask);
this.processingTask = processingTask;
}
@Override
public void run() {
log.log(Level.FINE, "Submitting after having waited " + delay + " ms in LATER queue: " + processingTask);
processingTask.submit();
}
}
public DocumentTypeManager getDocumentTypeManager() {
return documentTypeManager;
}
} |
Variable should be lowercase, and `final` can be removed (we typically don't use final for local variables). | private void reportAuditLog() {
final String OPERATOR = "operator";
AuditLog log = controller().auditLogger().readLog();
for (AuditLog.Entry entry : log.entries()) {
String[] resource = entry.resource().split("/");
String operationMetric;
if(resource[1] != null) {
String api = resource[1];
operationMetric = OPERATION_PREFIX + api;
Metric.Context context = metric.createContext(Map.of(OPERATOR, entry.principal()));
metric.add(operationMetric, 1, context);
}
}
} | final String OPERATOR = "operator"; | private void reportAuditLog() {
AuditLog log = controller().auditLogger().readLog();
HashMap<String, HashMap<String, Integer>> metricCounts = new HashMap<>();
for (AuditLog.Entry entry : log.entries()) {
String[] resource = entry.resource().split("/");
if((resource.length > 1) && (resource[1] != null)) {
String api = resource[1];
String operationMetric = OPERATION_PREFIX + api;
HashMap<String, Integer> dimension = metricCounts.get(operationMetric);
if (dimension != null) {
Integer count = dimension.get(entry.principal());
if (count != null) {
dimension.replace(entry.principal(), ++count);
} else {
dimension.put(entry.principal(), 1);
}
} else {
dimension = new HashMap<>();
dimension.put(entry.principal(),1);
metricCounts.put(operationMetric, dimension);
}
}
}
for (String operationMetric : metricCounts.keySet()) {
for (String userDimension : metricCounts.get(operationMetric).keySet()) {
metric.set(operationMetric, (metricCounts.get(operationMetric)).get(userDimension), metric.createContext(Map.of("operator", userDimension)));
}
}
} | class MetricsReporter extends ControllerMaintainer {
public static final String DEPLOYMENT_FAIL_METRIC = "deployment.failurePercentage";
public static final String DEPLOYMENT_AVERAGE_DURATION = "deployment.averageDuration";
public static final String DEPLOYMENT_FAILING_UPGRADES = "deployment.failingUpgrades";
public static final String DEPLOYMENT_BUILD_AGE_SECONDS = "deployment.buildAgeSeconds";
public static final String DEPLOYMENT_WARNINGS = "deployment.warnings";
public static final String OS_CHANGE_DURATION = "deployment.osChangeDuration";
public static final String PLATFORM_CHANGE_DURATION = "deployment.platformChangeDuration";
public static final String OS_NODE_COUNT = "deployment.nodeCountByOsVersion";
public static final String PLATFORM_NODE_COUNT = "deployment.nodeCountByPlatformVersion";
public static final String REMAINING_ROTATIONS = "remaining_rotations";
public static final String NAME_SERVICE_REQUESTS_QUEUED = "dns.queuedRequests";
public static final String OPERATION_PREFIX = "operation.";
private final Metric metric;
private final Clock clock;
private final ConcurrentHashMap<NodeCountKey, Long> nodeCounts = new ConcurrentHashMap<>();
public MetricsReporter(Controller controller, Metric metric) {
super(controller, Duration.ofMinutes(1));
this.metric = metric;
this.clock = controller.clock();
}
@Override
public void maintain() {
reportDeploymentMetrics();
reportRemainingRotations();
reportQueuedNameServiceRequests();
reportInfrastructureUpgradeMetrics();
reportAuditLog();
}
private void reportInfrastructureUpgradeMetrics() {
Map<NodeVersion, Duration> osChangeDurations = osChangeDurations();
Map<NodeVersion, Duration> platformChangeDurations = platformChangeDurations();
reportChangeDurations(osChangeDurations, OS_CHANGE_DURATION);
reportChangeDurations(platformChangeDurations, PLATFORM_CHANGE_DURATION);
reportNodeCount(osChangeDurations.keySet(), OS_NODE_COUNT);
reportNodeCount(platformChangeDurations.keySet(), PLATFORM_NODE_COUNT);
}
private void reportRemainingRotations() {
try (RotationLock lock = controller().routing().rotations().lock()) {
int availableRotations = controller().routing().rotations().availableRotations(lock).size();
metric.set(REMAINING_ROTATIONS, availableRotations, metric.createContext(Map.of()));
}
}
private void reportDeploymentMetrics() {
ApplicationList applications = ApplicationList.from(controller().applications().readable())
.withProductionDeployment();
DeploymentStatusList deployments = controller().jobController().deploymentStatuses(applications);
metric.set(DEPLOYMENT_FAIL_METRIC, deploymentFailRatio(deployments) * 100, metric.createContext(Map.of()));
averageDeploymentDurations(deployments, clock.instant()).forEach((instance, duration) -> {
metric.set(DEPLOYMENT_AVERAGE_DURATION, duration.getSeconds(), metric.createContext(dimensions(instance)));
});
deploymentsFailingUpgrade(deployments).forEach((instance, failingJobs) -> {
metric.set(DEPLOYMENT_FAILING_UPGRADES, failingJobs, metric.createContext(dimensions(instance)));
});
deploymentWarnings(deployments).forEach((application, warnings) -> {
metric.set(DEPLOYMENT_WARNINGS, warnings, metric.createContext(dimensions(application)));
});
for (Application application : applications.asList())
application.latestVersion()
.flatMap(ApplicationVersion::buildTime)
.ifPresent(buildTime -> metric.set(DEPLOYMENT_BUILD_AGE_SECONDS,
controller().clock().instant().getEpochSecond() - buildTime.getEpochSecond(),
metric.createContext(dimensions(application.id().defaultInstance()))));
}
private void reportQueuedNameServiceRequests() {
metric.set(NAME_SERVICE_REQUESTS_QUEUED, controller().curator().readNameServiceQueue().requests().size(),
metric.createContext(Map.of()));
}
private void reportNodeCount(Set<NodeVersion> nodeVersions, String metricName) {
Map<NodeCountKey, Long> newNodeCounts = nodeVersions.stream()
.collect(Collectors.groupingBy(nodeVersion -> {
return new NodeCountKey(metricName,
nodeVersion.currentVersion(),
nodeVersion.zone());
}, Collectors.counting()));
nodeCounts.putAll(newNodeCounts);
nodeCounts.forEach((key, count) -> {
if (newNodeCounts.containsKey(key)) {
metric.set(metricName, count, metric.createContext(dimensions(key.zone, key.version)));
} else if (key.metricName.equals(metricName)) {
metric.set(metricName, 0, metric.createContext(dimensions(key.zone, key.version)));
}
});
}
private void reportChangeDurations(Map<NodeVersion, Duration> changeDurations, String metricName) {
changeDurations.forEach((nodeVersion, duration) -> {
metric.set(metricName, duration.toSeconds(), metric.createContext(dimensions(nodeVersion.hostname(), nodeVersion.zone())));
});
}
private Map<NodeVersion, Duration> platformChangeDurations() {
return changeDurations(controller().versionStatus().versions(), VespaVersion::nodeVersions);
}
private Map<NodeVersion, Duration> osChangeDurations() {
return changeDurations(controller().osVersionStatus().versions().values(), Function.identity());
}
private <V> Map<NodeVersion, Duration> changeDurations(Collection<V> versions, Function<V, NodeVersions> versionsGetter) {
var now = clock.instant();
var durations = new HashMap<NodeVersion, Duration>();
for (var version : versions) {
for (var nodeVersion : versionsGetter.apply(version).asMap().values()) {
durations.put(nodeVersion, nodeVersion.changeDuration(now));
}
}
return durations;
}
private static double deploymentFailRatio(DeploymentStatusList statuses) {
return statuses.asList().stream()
.mapToInt(status -> status.hasFailures() ? 1 : 0)
.average().orElse(0);
}
private static Map<ApplicationId, Duration> averageDeploymentDurations(DeploymentStatusList statuses, Instant now) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> averageDeploymentDuration(entry.getValue(), now)));
}
private static Map<ApplicationId, Integer> deploymentsFailingUpgrade(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> deploymentsFailingUpgrade(entry.getValue())));
}
private static int deploymentsFailingUpgrade(JobList jobs) {
return jobs.failing().not().failingApplicationChange().size();
}
private static Duration averageDeploymentDuration(JobList jobs, Instant now) {
List<Duration> jobDurations = jobs.lastTriggered()
.mapToList(run -> Duration.between(run.start(), run.end().orElse(now)));
return jobDurations.stream()
.reduce(Duration::plus)
.map(totalDuration -> totalDuration.dividedBy(jobDurations.size()))
.orElse(Duration.ZERO);
}
private static Map<ApplicationId, Integer> deploymentWarnings(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.application().instances().values().stream())
.collect(Collectors.toMap(Instance::id, a -> maxWarningCountOf(a.deployments().values())));
}
private static int maxWarningCountOf(Collection<Deployment> deployments) {
return deployments.stream()
.map(Deployment::metrics)
.map(DeploymentMetrics::warnings)
.map(Map::values)
.flatMap(Collection::stream)
.max(Integer::compareTo)
.orElse(0);
}
private static Map<String, String> dimensions(ApplicationId application) {
return Map.of("tenant", application.tenant().value(),
"app",application.application().value() + "." + application.instance().value());
}
private static Map<String, String> dimensions(HostName hostname, ZoneId zone) {
return Map.of("host", hostname.value(),
"zone", zone.value());
}
private static Map<String, String> dimensions(ZoneId zone, Version currentVersion) {
return Map.of("zone", zone.value(),
"currentVersion", currentVersion.toFullString());
}
private static class NodeCountKey {
private final String metricName;
private final Version version;
private final ZoneId zone;
public NodeCountKey(String metricName, Version version, ZoneId zone) {
this.metricName = metricName;
this.version = version;
this.zone = zone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeCountKey that = (NodeCountKey) o;
return metricName.equals(that.metricName) &&
version.equals(that.version) &&
zone.equals(that.zone);
}
@Override
public int hashCode() {
return Objects.hash(metricName, version, zone);
}
}
} | class MetricsReporter extends ControllerMaintainer {
public static final String DEPLOYMENT_FAIL_METRIC = "deployment.failurePercentage";
public static final String DEPLOYMENT_AVERAGE_DURATION = "deployment.averageDuration";
public static final String DEPLOYMENT_FAILING_UPGRADES = "deployment.failingUpgrades";
public static final String DEPLOYMENT_BUILD_AGE_SECONDS = "deployment.buildAgeSeconds";
public static final String DEPLOYMENT_WARNINGS = "deployment.warnings";
public static final String OS_CHANGE_DURATION = "deployment.osChangeDuration";
public static final String PLATFORM_CHANGE_DURATION = "deployment.platformChangeDuration";
public static final String OS_NODE_COUNT = "deployment.nodeCountByOsVersion";
public static final String PLATFORM_NODE_COUNT = "deployment.nodeCountByPlatformVersion";
public static final String REMAINING_ROTATIONS = "remaining_rotations";
public static final String NAME_SERVICE_REQUESTS_QUEUED = "dns.queuedRequests";
public static final String OPERATION_PREFIX = "operation.";
private final Metric metric;
private final Clock clock;
private final ConcurrentHashMap<NodeCountKey, Long> nodeCounts = new ConcurrentHashMap<>();
public MetricsReporter(Controller controller, Metric metric) {
super(controller, Duration.ofMinutes(1));
this.metric = metric;
this.clock = controller.clock();
}
@Override
public void maintain() {
reportDeploymentMetrics();
reportRemainingRotations();
reportQueuedNameServiceRequests();
reportInfrastructureUpgradeMetrics();
reportAuditLog();
}
private void reportInfrastructureUpgradeMetrics() {
Map<NodeVersion, Duration> osChangeDurations = osChangeDurations();
Map<NodeVersion, Duration> platformChangeDurations = platformChangeDurations();
reportChangeDurations(osChangeDurations, OS_CHANGE_DURATION);
reportChangeDurations(platformChangeDurations, PLATFORM_CHANGE_DURATION);
reportNodeCount(osChangeDurations.keySet(), OS_NODE_COUNT);
reportNodeCount(platformChangeDurations.keySet(), PLATFORM_NODE_COUNT);
}
private void reportRemainingRotations() {
try (RotationLock lock = controller().routing().rotations().lock()) {
int availableRotations = controller().routing().rotations().availableRotations(lock).size();
metric.set(REMAINING_ROTATIONS, availableRotations, metric.createContext(Map.of()));
}
}
private void reportDeploymentMetrics() {
ApplicationList applications = ApplicationList.from(controller().applications().readable())
.withProductionDeployment();
DeploymentStatusList deployments = controller().jobController().deploymentStatuses(applications);
metric.set(DEPLOYMENT_FAIL_METRIC, deploymentFailRatio(deployments) * 100, metric.createContext(Map.of()));
averageDeploymentDurations(deployments, clock.instant()).forEach((instance, duration) -> {
metric.set(DEPLOYMENT_AVERAGE_DURATION, duration.getSeconds(), metric.createContext(dimensions(instance)));
});
deploymentsFailingUpgrade(deployments).forEach((instance, failingJobs) -> {
metric.set(DEPLOYMENT_FAILING_UPGRADES, failingJobs, metric.createContext(dimensions(instance)));
});
deploymentWarnings(deployments).forEach((application, warnings) -> {
metric.set(DEPLOYMENT_WARNINGS, warnings, metric.createContext(dimensions(application)));
});
for (Application application : applications.asList())
application.latestVersion()
.flatMap(ApplicationVersion::buildTime)
.ifPresent(buildTime -> metric.set(DEPLOYMENT_BUILD_AGE_SECONDS,
controller().clock().instant().getEpochSecond() - buildTime.getEpochSecond(),
metric.createContext(dimensions(application.id().defaultInstance()))));
}
private void reportQueuedNameServiceRequests() {
metric.set(NAME_SERVICE_REQUESTS_QUEUED, controller().curator().readNameServiceQueue().requests().size(),
metric.createContext(Map.of()));
}
private void reportNodeCount(Set<NodeVersion> nodeVersions, String metricName) {
Map<NodeCountKey, Long> newNodeCounts = nodeVersions.stream()
.collect(Collectors.groupingBy(nodeVersion -> {
return new NodeCountKey(metricName,
nodeVersion.currentVersion(),
nodeVersion.zone());
}, Collectors.counting()));
nodeCounts.putAll(newNodeCounts);
nodeCounts.forEach((key, count) -> {
if (newNodeCounts.containsKey(key)) {
metric.set(metricName, count, metric.createContext(dimensions(key.zone, key.version)));
} else if (key.metricName.equals(metricName)) {
metric.set(metricName, 0, metric.createContext(dimensions(key.zone, key.version)));
}
});
}
private void reportChangeDurations(Map<NodeVersion, Duration> changeDurations, String metricName) {
changeDurations.forEach((nodeVersion, duration) -> {
metric.set(metricName, duration.toSeconds(), metric.createContext(dimensions(nodeVersion.hostname(), nodeVersion.zone())));
});
}
private Map<NodeVersion, Duration> platformChangeDurations() {
return changeDurations(controller().versionStatus().versions(), VespaVersion::nodeVersions);
}
private Map<NodeVersion, Duration> osChangeDurations() {
return changeDurations(controller().osVersionStatus().versions().values(), Function.identity());
}
private <V> Map<NodeVersion, Duration> changeDurations(Collection<V> versions, Function<V, NodeVersions> versionsGetter) {
var now = clock.instant();
var durations = new HashMap<NodeVersion, Duration>();
for (var version : versions) {
for (var nodeVersion : versionsGetter.apply(version).asMap().values()) {
durations.put(nodeVersion, nodeVersion.changeDuration(now));
}
}
return durations;
}
private static double deploymentFailRatio(DeploymentStatusList statuses) {
return statuses.asList().stream()
.mapToInt(status -> status.hasFailures() ? 1 : 0)
.average().orElse(0);
}
private static Map<ApplicationId, Duration> averageDeploymentDurations(DeploymentStatusList statuses, Instant now) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> averageDeploymentDuration(entry.getValue(), now)));
}
private static Map<ApplicationId, Integer> deploymentsFailingUpgrade(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> deploymentsFailingUpgrade(entry.getValue())));
}
private static int deploymentsFailingUpgrade(JobList jobs) {
return jobs.failing().not().failingApplicationChange().size();
}
private static Duration averageDeploymentDuration(JobList jobs, Instant now) {
List<Duration> jobDurations = jobs.lastTriggered()
.mapToList(run -> Duration.between(run.start(), run.end().orElse(now)));
return jobDurations.stream()
.reduce(Duration::plus)
.map(totalDuration -> totalDuration.dividedBy(jobDurations.size()))
.orElse(Duration.ZERO);
}
private static Map<ApplicationId, Integer> deploymentWarnings(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.application().instances().values().stream())
.collect(Collectors.toMap(Instance::id, a -> maxWarningCountOf(a.deployments().values())));
}
private static int maxWarningCountOf(Collection<Deployment> deployments) {
return deployments.stream()
.map(Deployment::metrics)
.map(DeploymentMetrics::warnings)
.map(Map::values)
.flatMap(Collection::stream)
.max(Integer::compareTo)
.orElse(0);
}
private static Map<String, String> dimensions(ApplicationId application) {
return Map.of("tenant", application.tenant().value(),
"app",application.application().value() + "." + application.instance().value());
}
private static Map<String, String> dimensions(HostName hostname, ZoneId zone) {
return Map.of("host", hostname.value(),
"zone", zone.value());
}
private static Map<String, String> dimensions(ZoneId zone, Version currentVersion) {
return Map.of("zone", zone.value(),
"currentVersion", currentVersion.toFullString());
}
private static class NodeCountKey {
private final String metricName;
private final Version version;
private final ZoneId zone;
public NodeCountKey(String metricName, Version version, ZoneId zone) {
this.metricName = metricName;
this.version = version;
this.zone = zone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeCountKey that = (NodeCountKey) o;
return metricName.equals(that.metricName) &&
version.equals(that.version) &&
zone.equals(that.zone);
}
@Override
public int hashCode() {
return Objects.hash(metricName, version, zone);
}
}
} |
Array length should be checked. | private void reportAuditLog() {
final String OPERATOR = "operator";
AuditLog log = controller().auditLogger().readLog();
for (AuditLog.Entry entry : log.entries()) {
String[] resource = entry.resource().split("/");
String operationMetric;
if(resource[1] != null) {
String api = resource[1];
operationMetric = OPERATION_PREFIX + api;
Metric.Context context = metric.createContext(Map.of(OPERATOR, entry.principal()));
metric.add(operationMetric, 1, context);
}
}
} | if(resource[1] != null) { | private void reportAuditLog() {
AuditLog log = controller().auditLogger().readLog();
HashMap<String, HashMap<String, Integer>> metricCounts = new HashMap<>();
for (AuditLog.Entry entry : log.entries()) {
String[] resource = entry.resource().split("/");
if((resource.length > 1) && (resource[1] != null)) {
String api = resource[1];
String operationMetric = OPERATION_PREFIX + api;
HashMap<String, Integer> dimension = metricCounts.get(operationMetric);
if (dimension != null) {
Integer count = dimension.get(entry.principal());
if (count != null) {
dimension.replace(entry.principal(), ++count);
} else {
dimension.put(entry.principal(), 1);
}
} else {
dimension = new HashMap<>();
dimension.put(entry.principal(),1);
metricCounts.put(operationMetric, dimension);
}
}
}
for (String operationMetric : metricCounts.keySet()) {
for (String userDimension : metricCounts.get(operationMetric).keySet()) {
metric.set(operationMetric, (metricCounts.get(operationMetric)).get(userDimension), metric.createContext(Map.of("operator", userDimension)));
}
}
} | class MetricsReporter extends ControllerMaintainer {
public static final String DEPLOYMENT_FAIL_METRIC = "deployment.failurePercentage";
public static final String DEPLOYMENT_AVERAGE_DURATION = "deployment.averageDuration";
public static final String DEPLOYMENT_FAILING_UPGRADES = "deployment.failingUpgrades";
public static final String DEPLOYMENT_BUILD_AGE_SECONDS = "deployment.buildAgeSeconds";
public static final String DEPLOYMENT_WARNINGS = "deployment.warnings";
public static final String OS_CHANGE_DURATION = "deployment.osChangeDuration";
public static final String PLATFORM_CHANGE_DURATION = "deployment.platformChangeDuration";
public static final String OS_NODE_COUNT = "deployment.nodeCountByOsVersion";
public static final String PLATFORM_NODE_COUNT = "deployment.nodeCountByPlatformVersion";
public static final String REMAINING_ROTATIONS = "remaining_rotations";
public static final String NAME_SERVICE_REQUESTS_QUEUED = "dns.queuedRequests";
public static final String OPERATION_PREFIX = "operation.";
private final Metric metric;
private final Clock clock;
private final ConcurrentHashMap<NodeCountKey, Long> nodeCounts = new ConcurrentHashMap<>();
public MetricsReporter(Controller controller, Metric metric) {
super(controller, Duration.ofMinutes(1));
this.metric = metric;
this.clock = controller.clock();
}
@Override
public void maintain() {
reportDeploymentMetrics();
reportRemainingRotations();
reportQueuedNameServiceRequests();
reportInfrastructureUpgradeMetrics();
reportAuditLog();
}
private void reportInfrastructureUpgradeMetrics() {
Map<NodeVersion, Duration> osChangeDurations = osChangeDurations();
Map<NodeVersion, Duration> platformChangeDurations = platformChangeDurations();
reportChangeDurations(osChangeDurations, OS_CHANGE_DURATION);
reportChangeDurations(platformChangeDurations, PLATFORM_CHANGE_DURATION);
reportNodeCount(osChangeDurations.keySet(), OS_NODE_COUNT);
reportNodeCount(platformChangeDurations.keySet(), PLATFORM_NODE_COUNT);
}
private void reportRemainingRotations() {
try (RotationLock lock = controller().routing().rotations().lock()) {
int availableRotations = controller().routing().rotations().availableRotations(lock).size();
metric.set(REMAINING_ROTATIONS, availableRotations, metric.createContext(Map.of()));
}
}
private void reportDeploymentMetrics() {
ApplicationList applications = ApplicationList.from(controller().applications().readable())
.withProductionDeployment();
DeploymentStatusList deployments = controller().jobController().deploymentStatuses(applications);
metric.set(DEPLOYMENT_FAIL_METRIC, deploymentFailRatio(deployments) * 100, metric.createContext(Map.of()));
averageDeploymentDurations(deployments, clock.instant()).forEach((instance, duration) -> {
metric.set(DEPLOYMENT_AVERAGE_DURATION, duration.getSeconds(), metric.createContext(dimensions(instance)));
});
deploymentsFailingUpgrade(deployments).forEach((instance, failingJobs) -> {
metric.set(DEPLOYMENT_FAILING_UPGRADES, failingJobs, metric.createContext(dimensions(instance)));
});
deploymentWarnings(deployments).forEach((application, warnings) -> {
metric.set(DEPLOYMENT_WARNINGS, warnings, metric.createContext(dimensions(application)));
});
for (Application application : applications.asList())
application.latestVersion()
.flatMap(ApplicationVersion::buildTime)
.ifPresent(buildTime -> metric.set(DEPLOYMENT_BUILD_AGE_SECONDS,
controller().clock().instant().getEpochSecond() - buildTime.getEpochSecond(),
metric.createContext(dimensions(application.id().defaultInstance()))));
}
private void reportQueuedNameServiceRequests() {
metric.set(NAME_SERVICE_REQUESTS_QUEUED, controller().curator().readNameServiceQueue().requests().size(),
metric.createContext(Map.of()));
}
private void reportNodeCount(Set<NodeVersion> nodeVersions, String metricName) {
Map<NodeCountKey, Long> newNodeCounts = nodeVersions.stream()
.collect(Collectors.groupingBy(nodeVersion -> {
return new NodeCountKey(metricName,
nodeVersion.currentVersion(),
nodeVersion.zone());
}, Collectors.counting()));
nodeCounts.putAll(newNodeCounts);
nodeCounts.forEach((key, count) -> {
if (newNodeCounts.containsKey(key)) {
metric.set(metricName, count, metric.createContext(dimensions(key.zone, key.version)));
} else if (key.metricName.equals(metricName)) {
metric.set(metricName, 0, metric.createContext(dimensions(key.zone, key.version)));
}
});
}
private void reportChangeDurations(Map<NodeVersion, Duration> changeDurations, String metricName) {
changeDurations.forEach((nodeVersion, duration) -> {
metric.set(metricName, duration.toSeconds(), metric.createContext(dimensions(nodeVersion.hostname(), nodeVersion.zone())));
});
}
private Map<NodeVersion, Duration> platformChangeDurations() {
return changeDurations(controller().versionStatus().versions(), VespaVersion::nodeVersions);
}
private Map<NodeVersion, Duration> osChangeDurations() {
return changeDurations(controller().osVersionStatus().versions().values(), Function.identity());
}
private <V> Map<NodeVersion, Duration> changeDurations(Collection<V> versions, Function<V, NodeVersions> versionsGetter) {
var now = clock.instant();
var durations = new HashMap<NodeVersion, Duration>();
for (var version : versions) {
for (var nodeVersion : versionsGetter.apply(version).asMap().values()) {
durations.put(nodeVersion, nodeVersion.changeDuration(now));
}
}
return durations;
}
private static double deploymentFailRatio(DeploymentStatusList statuses) {
return statuses.asList().stream()
.mapToInt(status -> status.hasFailures() ? 1 : 0)
.average().orElse(0);
}
private static Map<ApplicationId, Duration> averageDeploymentDurations(DeploymentStatusList statuses, Instant now) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> averageDeploymentDuration(entry.getValue(), now)));
}
private static Map<ApplicationId, Integer> deploymentsFailingUpgrade(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> deploymentsFailingUpgrade(entry.getValue())));
}
private static int deploymentsFailingUpgrade(JobList jobs) {
return jobs.failing().not().failingApplicationChange().size();
}
private static Duration averageDeploymentDuration(JobList jobs, Instant now) {
List<Duration> jobDurations = jobs.lastTriggered()
.mapToList(run -> Duration.between(run.start(), run.end().orElse(now)));
return jobDurations.stream()
.reduce(Duration::plus)
.map(totalDuration -> totalDuration.dividedBy(jobDurations.size()))
.orElse(Duration.ZERO);
}
private static Map<ApplicationId, Integer> deploymentWarnings(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.application().instances().values().stream())
.collect(Collectors.toMap(Instance::id, a -> maxWarningCountOf(a.deployments().values())));
}
private static int maxWarningCountOf(Collection<Deployment> deployments) {
return deployments.stream()
.map(Deployment::metrics)
.map(DeploymentMetrics::warnings)
.map(Map::values)
.flatMap(Collection::stream)
.max(Integer::compareTo)
.orElse(0);
}
private static Map<String, String> dimensions(ApplicationId application) {
return Map.of("tenant", application.tenant().value(),
"app",application.application().value() + "." + application.instance().value());
}
private static Map<String, String> dimensions(HostName hostname, ZoneId zone) {
return Map.of("host", hostname.value(),
"zone", zone.value());
}
private static Map<String, String> dimensions(ZoneId zone, Version currentVersion) {
return Map.of("zone", zone.value(),
"currentVersion", currentVersion.toFullString());
}
private static class NodeCountKey {
private final String metricName;
private final Version version;
private final ZoneId zone;
public NodeCountKey(String metricName, Version version, ZoneId zone) {
this.metricName = metricName;
this.version = version;
this.zone = zone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeCountKey that = (NodeCountKey) o;
return metricName.equals(that.metricName) &&
version.equals(that.version) &&
zone.equals(that.zone);
}
@Override
public int hashCode() {
return Objects.hash(metricName, version, zone);
}
}
} | class MetricsReporter extends ControllerMaintainer {
public static final String DEPLOYMENT_FAIL_METRIC = "deployment.failurePercentage";
public static final String DEPLOYMENT_AVERAGE_DURATION = "deployment.averageDuration";
public static final String DEPLOYMENT_FAILING_UPGRADES = "deployment.failingUpgrades";
public static final String DEPLOYMENT_BUILD_AGE_SECONDS = "deployment.buildAgeSeconds";
public static final String DEPLOYMENT_WARNINGS = "deployment.warnings";
public static final String OS_CHANGE_DURATION = "deployment.osChangeDuration";
public static final String PLATFORM_CHANGE_DURATION = "deployment.platformChangeDuration";
public static final String OS_NODE_COUNT = "deployment.nodeCountByOsVersion";
public static final String PLATFORM_NODE_COUNT = "deployment.nodeCountByPlatformVersion";
public static final String REMAINING_ROTATIONS = "remaining_rotations";
public static final String NAME_SERVICE_REQUESTS_QUEUED = "dns.queuedRequests";
public static final String OPERATION_PREFIX = "operation.";
private final Metric metric;
private final Clock clock;
private final ConcurrentHashMap<NodeCountKey, Long> nodeCounts = new ConcurrentHashMap<>();
public MetricsReporter(Controller controller, Metric metric) {
super(controller, Duration.ofMinutes(1));
this.metric = metric;
this.clock = controller.clock();
}
@Override
public void maintain() {
reportDeploymentMetrics();
reportRemainingRotations();
reportQueuedNameServiceRequests();
reportInfrastructureUpgradeMetrics();
reportAuditLog();
}
private void reportInfrastructureUpgradeMetrics() {
Map<NodeVersion, Duration> osChangeDurations = osChangeDurations();
Map<NodeVersion, Duration> platformChangeDurations = platformChangeDurations();
reportChangeDurations(osChangeDurations, OS_CHANGE_DURATION);
reportChangeDurations(platformChangeDurations, PLATFORM_CHANGE_DURATION);
reportNodeCount(osChangeDurations.keySet(), OS_NODE_COUNT);
reportNodeCount(platformChangeDurations.keySet(), PLATFORM_NODE_COUNT);
}
private void reportRemainingRotations() {
try (RotationLock lock = controller().routing().rotations().lock()) {
int availableRotations = controller().routing().rotations().availableRotations(lock).size();
metric.set(REMAINING_ROTATIONS, availableRotations, metric.createContext(Map.of()));
}
}
private void reportDeploymentMetrics() {
ApplicationList applications = ApplicationList.from(controller().applications().readable())
.withProductionDeployment();
DeploymentStatusList deployments = controller().jobController().deploymentStatuses(applications);
metric.set(DEPLOYMENT_FAIL_METRIC, deploymentFailRatio(deployments) * 100, metric.createContext(Map.of()));
averageDeploymentDurations(deployments, clock.instant()).forEach((instance, duration) -> {
metric.set(DEPLOYMENT_AVERAGE_DURATION, duration.getSeconds(), metric.createContext(dimensions(instance)));
});
deploymentsFailingUpgrade(deployments).forEach((instance, failingJobs) -> {
metric.set(DEPLOYMENT_FAILING_UPGRADES, failingJobs, metric.createContext(dimensions(instance)));
});
deploymentWarnings(deployments).forEach((application, warnings) -> {
metric.set(DEPLOYMENT_WARNINGS, warnings, metric.createContext(dimensions(application)));
});
for (Application application : applications.asList())
application.latestVersion()
.flatMap(ApplicationVersion::buildTime)
.ifPresent(buildTime -> metric.set(DEPLOYMENT_BUILD_AGE_SECONDS,
controller().clock().instant().getEpochSecond() - buildTime.getEpochSecond(),
metric.createContext(dimensions(application.id().defaultInstance()))));
}
private void reportQueuedNameServiceRequests() {
metric.set(NAME_SERVICE_REQUESTS_QUEUED, controller().curator().readNameServiceQueue().requests().size(),
metric.createContext(Map.of()));
}
private void reportNodeCount(Set<NodeVersion> nodeVersions, String metricName) {
Map<NodeCountKey, Long> newNodeCounts = nodeVersions.stream()
.collect(Collectors.groupingBy(nodeVersion -> {
return new NodeCountKey(metricName,
nodeVersion.currentVersion(),
nodeVersion.zone());
}, Collectors.counting()));
nodeCounts.putAll(newNodeCounts);
nodeCounts.forEach((key, count) -> {
if (newNodeCounts.containsKey(key)) {
metric.set(metricName, count, metric.createContext(dimensions(key.zone, key.version)));
} else if (key.metricName.equals(metricName)) {
metric.set(metricName, 0, metric.createContext(dimensions(key.zone, key.version)));
}
});
}
private void reportChangeDurations(Map<NodeVersion, Duration> changeDurations, String metricName) {
changeDurations.forEach((nodeVersion, duration) -> {
metric.set(metricName, duration.toSeconds(), metric.createContext(dimensions(nodeVersion.hostname(), nodeVersion.zone())));
});
}
private Map<NodeVersion, Duration> platformChangeDurations() {
return changeDurations(controller().versionStatus().versions(), VespaVersion::nodeVersions);
}
private Map<NodeVersion, Duration> osChangeDurations() {
return changeDurations(controller().osVersionStatus().versions().values(), Function.identity());
}
private <V> Map<NodeVersion, Duration> changeDurations(Collection<V> versions, Function<V, NodeVersions> versionsGetter) {
var now = clock.instant();
var durations = new HashMap<NodeVersion, Duration>();
for (var version : versions) {
for (var nodeVersion : versionsGetter.apply(version).asMap().values()) {
durations.put(nodeVersion, nodeVersion.changeDuration(now));
}
}
return durations;
}
private static double deploymentFailRatio(DeploymentStatusList statuses) {
return statuses.asList().stream()
.mapToInt(status -> status.hasFailures() ? 1 : 0)
.average().orElse(0);
}
private static Map<ApplicationId, Duration> averageDeploymentDurations(DeploymentStatusList statuses, Instant now) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> averageDeploymentDuration(entry.getValue(), now)));
}
private static Map<ApplicationId, Integer> deploymentsFailingUpgrade(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> deploymentsFailingUpgrade(entry.getValue())));
}
private static int deploymentsFailingUpgrade(JobList jobs) {
return jobs.failing().not().failingApplicationChange().size();
}
private static Duration averageDeploymentDuration(JobList jobs, Instant now) {
List<Duration> jobDurations = jobs.lastTriggered()
.mapToList(run -> Duration.between(run.start(), run.end().orElse(now)));
return jobDurations.stream()
.reduce(Duration::plus)
.map(totalDuration -> totalDuration.dividedBy(jobDurations.size()))
.orElse(Duration.ZERO);
}
private static Map<ApplicationId, Integer> deploymentWarnings(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.application().instances().values().stream())
.collect(Collectors.toMap(Instance::id, a -> maxWarningCountOf(a.deployments().values())));
}
private static int maxWarningCountOf(Collection<Deployment> deployments) {
return deployments.stream()
.map(Deployment::metrics)
.map(DeploymentMetrics::warnings)
.map(Map::values)
.flatMap(Collection::stream)
.max(Integer::compareTo)
.orElse(0);
}
private static Map<String, String> dimensions(ApplicationId application) {
return Map.of("tenant", application.tenant().value(),
"app",application.application().value() + "." + application.instance().value());
}
private static Map<String, String> dimensions(HostName hostname, ZoneId zone) {
return Map.of("host", hostname.value(),
"zone", zone.value());
}
private static Map<String, String> dimensions(ZoneId zone, Version currentVersion) {
return Map.of("zone", zone.value(),
"currentVersion", currentVersion.toFullString());
}
private static class NodeCountKey {
private final String metricName;
private final Version version;
private final ZoneId zone;
public NodeCountKey(String metricName, Version version, ZoneId zone) {
this.metricName = metricName;
this.version = version;
this.zone = zone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeCountKey that = (NodeCountKey) o;
return metricName.equals(that.metricName) &&
version.equals(that.version) &&
zone.equals(that.zone);
}
@Override
public int hashCode() {
return Objects.hash(metricName, version, zone);
}
}
} |
Since `MetricsReporter` runs at an interval and this loops over all entries every time, this metric will end up counting the same entries multiple times. I suggest that you instead calculate the total count and use `metric.set`. You can verify that the metric is as expected by calling `metricsReporter.maintain()` more than once in the test. | private void reportAuditLog() {
final String OPERATOR = "operator";
AuditLog log = controller().auditLogger().readLog();
for (AuditLog.Entry entry : log.entries()) {
String[] resource = entry.resource().split("/");
String operationMetric;
if(resource[1] != null) {
String api = resource[1];
operationMetric = OPERATION_PREFIX + api;
Metric.Context context = metric.createContext(Map.of(OPERATOR, entry.principal()));
metric.add(operationMetric, 1, context);
}
}
} | metric.add(operationMetric, 1, context); | private void reportAuditLog() {
AuditLog log = controller().auditLogger().readLog();
HashMap<String, HashMap<String, Integer>> metricCounts = new HashMap<>();
for (AuditLog.Entry entry : log.entries()) {
String[] resource = entry.resource().split("/");
if((resource.length > 1) && (resource[1] != null)) {
String api = resource[1];
String operationMetric = OPERATION_PREFIX + api;
HashMap<String, Integer> dimension = metricCounts.get(operationMetric);
if (dimension != null) {
Integer count = dimension.get(entry.principal());
if (count != null) {
dimension.replace(entry.principal(), ++count);
} else {
dimension.put(entry.principal(), 1);
}
} else {
dimension = new HashMap<>();
dimension.put(entry.principal(),1);
metricCounts.put(operationMetric, dimension);
}
}
}
for (String operationMetric : metricCounts.keySet()) {
for (String userDimension : metricCounts.get(operationMetric).keySet()) {
metric.set(operationMetric, (metricCounts.get(operationMetric)).get(userDimension), metric.createContext(Map.of("operator", userDimension)));
}
}
} | class MetricsReporter extends ControllerMaintainer {
public static final String DEPLOYMENT_FAIL_METRIC = "deployment.failurePercentage";
public static final String DEPLOYMENT_AVERAGE_DURATION = "deployment.averageDuration";
public static final String DEPLOYMENT_FAILING_UPGRADES = "deployment.failingUpgrades";
public static final String DEPLOYMENT_BUILD_AGE_SECONDS = "deployment.buildAgeSeconds";
public static final String DEPLOYMENT_WARNINGS = "deployment.warnings";
public static final String OS_CHANGE_DURATION = "deployment.osChangeDuration";
public static final String PLATFORM_CHANGE_DURATION = "deployment.platformChangeDuration";
public static final String OS_NODE_COUNT = "deployment.nodeCountByOsVersion";
public static final String PLATFORM_NODE_COUNT = "deployment.nodeCountByPlatformVersion";
public static final String REMAINING_ROTATIONS = "remaining_rotations";
public static final String NAME_SERVICE_REQUESTS_QUEUED = "dns.queuedRequests";
public static final String OPERATION_PREFIX = "operation.";
private final Metric metric;
private final Clock clock;
private final ConcurrentHashMap<NodeCountKey, Long> nodeCounts = new ConcurrentHashMap<>();
public MetricsReporter(Controller controller, Metric metric) {
super(controller, Duration.ofMinutes(1));
this.metric = metric;
this.clock = controller.clock();
}
@Override
public void maintain() {
reportDeploymentMetrics();
reportRemainingRotations();
reportQueuedNameServiceRequests();
reportInfrastructureUpgradeMetrics();
reportAuditLog();
}
private void reportInfrastructureUpgradeMetrics() {
Map<NodeVersion, Duration> osChangeDurations = osChangeDurations();
Map<NodeVersion, Duration> platformChangeDurations = platformChangeDurations();
reportChangeDurations(osChangeDurations, OS_CHANGE_DURATION);
reportChangeDurations(platformChangeDurations, PLATFORM_CHANGE_DURATION);
reportNodeCount(osChangeDurations.keySet(), OS_NODE_COUNT);
reportNodeCount(platformChangeDurations.keySet(), PLATFORM_NODE_COUNT);
}
private void reportRemainingRotations() {
try (RotationLock lock = controller().routing().rotations().lock()) {
int availableRotations = controller().routing().rotations().availableRotations(lock).size();
metric.set(REMAINING_ROTATIONS, availableRotations, metric.createContext(Map.of()));
}
}
private void reportDeploymentMetrics() {
ApplicationList applications = ApplicationList.from(controller().applications().readable())
.withProductionDeployment();
DeploymentStatusList deployments = controller().jobController().deploymentStatuses(applications);
metric.set(DEPLOYMENT_FAIL_METRIC, deploymentFailRatio(deployments) * 100, metric.createContext(Map.of()));
averageDeploymentDurations(deployments, clock.instant()).forEach((instance, duration) -> {
metric.set(DEPLOYMENT_AVERAGE_DURATION, duration.getSeconds(), metric.createContext(dimensions(instance)));
});
deploymentsFailingUpgrade(deployments).forEach((instance, failingJobs) -> {
metric.set(DEPLOYMENT_FAILING_UPGRADES, failingJobs, metric.createContext(dimensions(instance)));
});
deploymentWarnings(deployments).forEach((application, warnings) -> {
metric.set(DEPLOYMENT_WARNINGS, warnings, metric.createContext(dimensions(application)));
});
for (Application application : applications.asList())
application.latestVersion()
.flatMap(ApplicationVersion::buildTime)
.ifPresent(buildTime -> metric.set(DEPLOYMENT_BUILD_AGE_SECONDS,
controller().clock().instant().getEpochSecond() - buildTime.getEpochSecond(),
metric.createContext(dimensions(application.id().defaultInstance()))));
}
private void reportQueuedNameServiceRequests() {
metric.set(NAME_SERVICE_REQUESTS_QUEUED, controller().curator().readNameServiceQueue().requests().size(),
metric.createContext(Map.of()));
}
private void reportNodeCount(Set<NodeVersion> nodeVersions, String metricName) {
Map<NodeCountKey, Long> newNodeCounts = nodeVersions.stream()
.collect(Collectors.groupingBy(nodeVersion -> {
return new NodeCountKey(metricName,
nodeVersion.currentVersion(),
nodeVersion.zone());
}, Collectors.counting()));
nodeCounts.putAll(newNodeCounts);
nodeCounts.forEach((key, count) -> {
if (newNodeCounts.containsKey(key)) {
metric.set(metricName, count, metric.createContext(dimensions(key.zone, key.version)));
} else if (key.metricName.equals(metricName)) {
metric.set(metricName, 0, metric.createContext(dimensions(key.zone, key.version)));
}
});
}
private void reportChangeDurations(Map<NodeVersion, Duration> changeDurations, String metricName) {
changeDurations.forEach((nodeVersion, duration) -> {
metric.set(metricName, duration.toSeconds(), metric.createContext(dimensions(nodeVersion.hostname(), nodeVersion.zone())));
});
}
private Map<NodeVersion, Duration> platformChangeDurations() {
return changeDurations(controller().versionStatus().versions(), VespaVersion::nodeVersions);
}
private Map<NodeVersion, Duration> osChangeDurations() {
return changeDurations(controller().osVersionStatus().versions().values(), Function.identity());
}
private <V> Map<NodeVersion, Duration> changeDurations(Collection<V> versions, Function<V, NodeVersions> versionsGetter) {
var now = clock.instant();
var durations = new HashMap<NodeVersion, Duration>();
for (var version : versions) {
for (var nodeVersion : versionsGetter.apply(version).asMap().values()) {
durations.put(nodeVersion, nodeVersion.changeDuration(now));
}
}
return durations;
}
private static double deploymentFailRatio(DeploymentStatusList statuses) {
return statuses.asList().stream()
.mapToInt(status -> status.hasFailures() ? 1 : 0)
.average().orElse(0);
}
private static Map<ApplicationId, Duration> averageDeploymentDurations(DeploymentStatusList statuses, Instant now) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> averageDeploymentDuration(entry.getValue(), now)));
}
private static Map<ApplicationId, Integer> deploymentsFailingUpgrade(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> deploymentsFailingUpgrade(entry.getValue())));
}
private static int deploymentsFailingUpgrade(JobList jobs) {
return jobs.failing().not().failingApplicationChange().size();
}
private static Duration averageDeploymentDuration(JobList jobs, Instant now) {
List<Duration> jobDurations = jobs.lastTriggered()
.mapToList(run -> Duration.between(run.start(), run.end().orElse(now)));
return jobDurations.stream()
.reduce(Duration::plus)
.map(totalDuration -> totalDuration.dividedBy(jobDurations.size()))
.orElse(Duration.ZERO);
}
private static Map<ApplicationId, Integer> deploymentWarnings(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.application().instances().values().stream())
.collect(Collectors.toMap(Instance::id, a -> maxWarningCountOf(a.deployments().values())));
}
private static int maxWarningCountOf(Collection<Deployment> deployments) {
return deployments.stream()
.map(Deployment::metrics)
.map(DeploymentMetrics::warnings)
.map(Map::values)
.flatMap(Collection::stream)
.max(Integer::compareTo)
.orElse(0);
}
private static Map<String, String> dimensions(ApplicationId application) {
return Map.of("tenant", application.tenant().value(),
"app",application.application().value() + "." + application.instance().value());
}
private static Map<String, String> dimensions(HostName hostname, ZoneId zone) {
return Map.of("host", hostname.value(),
"zone", zone.value());
}
private static Map<String, String> dimensions(ZoneId zone, Version currentVersion) {
return Map.of("zone", zone.value(),
"currentVersion", currentVersion.toFullString());
}
private static class NodeCountKey {
private final String metricName;
private final Version version;
private final ZoneId zone;
public NodeCountKey(String metricName, Version version, ZoneId zone) {
this.metricName = metricName;
this.version = version;
this.zone = zone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeCountKey that = (NodeCountKey) o;
return metricName.equals(that.metricName) &&
version.equals(that.version) &&
zone.equals(that.zone);
}
@Override
public int hashCode() {
return Objects.hash(metricName, version, zone);
}
}
} | class MetricsReporter extends ControllerMaintainer {
public static final String DEPLOYMENT_FAIL_METRIC = "deployment.failurePercentage";
public static final String DEPLOYMENT_AVERAGE_DURATION = "deployment.averageDuration";
public static final String DEPLOYMENT_FAILING_UPGRADES = "deployment.failingUpgrades";
public static final String DEPLOYMENT_BUILD_AGE_SECONDS = "deployment.buildAgeSeconds";
public static final String DEPLOYMENT_WARNINGS = "deployment.warnings";
public static final String OS_CHANGE_DURATION = "deployment.osChangeDuration";
public static final String PLATFORM_CHANGE_DURATION = "deployment.platformChangeDuration";
public static final String OS_NODE_COUNT = "deployment.nodeCountByOsVersion";
public static final String PLATFORM_NODE_COUNT = "deployment.nodeCountByPlatformVersion";
public static final String REMAINING_ROTATIONS = "remaining_rotations";
public static final String NAME_SERVICE_REQUESTS_QUEUED = "dns.queuedRequests";
public static final String OPERATION_PREFIX = "operation.";
private final Metric metric;
private final Clock clock;
private final ConcurrentHashMap<NodeCountKey, Long> nodeCounts = new ConcurrentHashMap<>();
public MetricsReporter(Controller controller, Metric metric) {
super(controller, Duration.ofMinutes(1));
this.metric = metric;
this.clock = controller.clock();
}
@Override
public void maintain() {
reportDeploymentMetrics();
reportRemainingRotations();
reportQueuedNameServiceRequests();
reportInfrastructureUpgradeMetrics();
reportAuditLog();
}
private void reportInfrastructureUpgradeMetrics() {
Map<NodeVersion, Duration> osChangeDurations = osChangeDurations();
Map<NodeVersion, Duration> platformChangeDurations = platformChangeDurations();
reportChangeDurations(osChangeDurations, OS_CHANGE_DURATION);
reportChangeDurations(platformChangeDurations, PLATFORM_CHANGE_DURATION);
reportNodeCount(osChangeDurations.keySet(), OS_NODE_COUNT);
reportNodeCount(platformChangeDurations.keySet(), PLATFORM_NODE_COUNT);
}
private void reportRemainingRotations() {
try (RotationLock lock = controller().routing().rotations().lock()) {
int availableRotations = controller().routing().rotations().availableRotations(lock).size();
metric.set(REMAINING_ROTATIONS, availableRotations, metric.createContext(Map.of()));
}
}
private void reportDeploymentMetrics() {
ApplicationList applications = ApplicationList.from(controller().applications().readable())
.withProductionDeployment();
DeploymentStatusList deployments = controller().jobController().deploymentStatuses(applications);
metric.set(DEPLOYMENT_FAIL_METRIC, deploymentFailRatio(deployments) * 100, metric.createContext(Map.of()));
averageDeploymentDurations(deployments, clock.instant()).forEach((instance, duration) -> {
metric.set(DEPLOYMENT_AVERAGE_DURATION, duration.getSeconds(), metric.createContext(dimensions(instance)));
});
deploymentsFailingUpgrade(deployments).forEach((instance, failingJobs) -> {
metric.set(DEPLOYMENT_FAILING_UPGRADES, failingJobs, metric.createContext(dimensions(instance)));
});
deploymentWarnings(deployments).forEach((application, warnings) -> {
metric.set(DEPLOYMENT_WARNINGS, warnings, metric.createContext(dimensions(application)));
});
for (Application application : applications.asList())
application.latestVersion()
.flatMap(ApplicationVersion::buildTime)
.ifPresent(buildTime -> metric.set(DEPLOYMENT_BUILD_AGE_SECONDS,
controller().clock().instant().getEpochSecond() - buildTime.getEpochSecond(),
metric.createContext(dimensions(application.id().defaultInstance()))));
}
private void reportQueuedNameServiceRequests() {
metric.set(NAME_SERVICE_REQUESTS_QUEUED, controller().curator().readNameServiceQueue().requests().size(),
metric.createContext(Map.of()));
}
private void reportNodeCount(Set<NodeVersion> nodeVersions, String metricName) {
Map<NodeCountKey, Long> newNodeCounts = nodeVersions.stream()
.collect(Collectors.groupingBy(nodeVersion -> {
return new NodeCountKey(metricName,
nodeVersion.currentVersion(),
nodeVersion.zone());
}, Collectors.counting()));
nodeCounts.putAll(newNodeCounts);
nodeCounts.forEach((key, count) -> {
if (newNodeCounts.containsKey(key)) {
metric.set(metricName, count, metric.createContext(dimensions(key.zone, key.version)));
} else if (key.metricName.equals(metricName)) {
metric.set(metricName, 0, metric.createContext(dimensions(key.zone, key.version)));
}
});
}
private void reportChangeDurations(Map<NodeVersion, Duration> changeDurations, String metricName) {
changeDurations.forEach((nodeVersion, duration) -> {
metric.set(metricName, duration.toSeconds(), metric.createContext(dimensions(nodeVersion.hostname(), nodeVersion.zone())));
});
}
private Map<NodeVersion, Duration> platformChangeDurations() {
return changeDurations(controller().versionStatus().versions(), VespaVersion::nodeVersions);
}
private Map<NodeVersion, Duration> osChangeDurations() {
return changeDurations(controller().osVersionStatus().versions().values(), Function.identity());
}
private <V> Map<NodeVersion, Duration> changeDurations(Collection<V> versions, Function<V, NodeVersions> versionsGetter) {
var now = clock.instant();
var durations = new HashMap<NodeVersion, Duration>();
for (var version : versions) {
for (var nodeVersion : versionsGetter.apply(version).asMap().values()) {
durations.put(nodeVersion, nodeVersion.changeDuration(now));
}
}
return durations;
}
private static double deploymentFailRatio(DeploymentStatusList statuses) {
return statuses.asList().stream()
.mapToInt(status -> status.hasFailures() ? 1 : 0)
.average().orElse(0);
}
private static Map<ApplicationId, Duration> averageDeploymentDurations(DeploymentStatusList statuses, Instant now) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> averageDeploymentDuration(entry.getValue(), now)));
}
private static Map<ApplicationId, Integer> deploymentsFailingUpgrade(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> deploymentsFailingUpgrade(entry.getValue())));
}
private static int deploymentsFailingUpgrade(JobList jobs) {
return jobs.failing().not().failingApplicationChange().size();
}
private static Duration averageDeploymentDuration(JobList jobs, Instant now) {
List<Duration> jobDurations = jobs.lastTriggered()
.mapToList(run -> Duration.between(run.start(), run.end().orElse(now)));
return jobDurations.stream()
.reduce(Duration::plus)
.map(totalDuration -> totalDuration.dividedBy(jobDurations.size()))
.orElse(Duration.ZERO);
}
private static Map<ApplicationId, Integer> deploymentWarnings(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.application().instances().values().stream())
.collect(Collectors.toMap(Instance::id, a -> maxWarningCountOf(a.deployments().values())));
}
private static int maxWarningCountOf(Collection<Deployment> deployments) {
return deployments.stream()
.map(Deployment::metrics)
.map(DeploymentMetrics::warnings)
.map(Map::values)
.flatMap(Collection::stream)
.max(Integer::compareTo)
.orElse(0);
}
private static Map<String, String> dimensions(ApplicationId application) {
return Map.of("tenant", application.tenant().value(),
"app",application.application().value() + "." + application.instance().value());
}
private static Map<String, String> dimensions(HostName hostname, ZoneId zone) {
return Map.of("host", hostname.value(),
"zone", zone.value());
}
private static Map<String, String> dimensions(ZoneId zone, Version currentVersion) {
return Map.of("zone", zone.value(),
"currentVersion", currentVersion.toFullString());
}
private static class NodeCountKey {
private final String metricName;
private final Version version;
private final ZoneId zone;
public NodeCountKey(String metricName, Version version, ZoneId zone) {
this.metricName = metricName;
this.version = version;
this.zone = zone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeCountKey that = (NodeCountKey) o;
return metricName.equals(that.metricName) &&
version.equals(that.version) &&
zone.equals(that.zone);
}
@Override
public int hashCode() {
return Objects.hash(metricName, version, zone);
}
}
} |
You can simplify this and drop a key lookup by always doing `metricCounts.get` and checking for `null` value instead of the explicit `containsKey`. Same for the code below. | private void reportAuditLog() {
AuditLog log = controller().auditLogger().readLog();
HashMap<String, HashMap<String, Integer>> metricCounts = new HashMap<>();
for (AuditLog.Entry entry : log.entries()) {
String[] resource = entry.resource().split("/");
if((resource.length > 1) && (resource[1] != null)) {
String api = resource[1];
String operationMetric = OPERATION_PREFIX + api;
if (metricCounts.containsKey(operationMetric)) {
HashMap<String, Integer> dimension = metricCounts.get(operationMetric);
if (dimension.containsKey(entry.principal())) {
Integer count = dimension.get(entry.principal());
dimension.replace(entry.principal(), ++count);
} else {
dimension.put(entry.principal(), 1);
}
} else {
HashMap<String, Integer> dimension = new HashMap<>();
dimension.put(entry.principal(),1);
metricCounts.put(operationMetric, dimension);
}
}
}
for (String operationMetric : metricCounts.keySet()) {
for (String userDimension : metricCounts.get(operationMetric).keySet()) {
metric.set(operationMetric, (metricCounts.get(operationMetric)).get(userDimension), metric.createContext(Map.of("operator", userDimension)));
}
}
} | HashMap<String, Integer> dimension = metricCounts.get(operationMetric); | private void reportAuditLog() {
AuditLog log = controller().auditLogger().readLog();
HashMap<String, HashMap<String, Integer>> metricCounts = new HashMap<>();
for (AuditLog.Entry entry : log.entries()) {
String[] resource = entry.resource().split("/");
if((resource.length > 1) && (resource[1] != null)) {
String api = resource[1];
String operationMetric = OPERATION_PREFIX + api;
HashMap<String, Integer> dimension = metricCounts.get(operationMetric);
if (dimension != null) {
Integer count = dimension.get(entry.principal());
if (count != null) {
dimension.replace(entry.principal(), ++count);
} else {
dimension.put(entry.principal(), 1);
}
} else {
dimension = new HashMap<>();
dimension.put(entry.principal(),1);
metricCounts.put(operationMetric, dimension);
}
}
}
for (String operationMetric : metricCounts.keySet()) {
for (String userDimension : metricCounts.get(operationMetric).keySet()) {
metric.set(operationMetric, (metricCounts.get(operationMetric)).get(userDimension), metric.createContext(Map.of("operator", userDimension)));
}
}
} | class MetricsReporter extends ControllerMaintainer {
public static final String DEPLOYMENT_FAIL_METRIC = "deployment.failurePercentage";
public static final String DEPLOYMENT_AVERAGE_DURATION = "deployment.averageDuration";
public static final String DEPLOYMENT_FAILING_UPGRADES = "deployment.failingUpgrades";
public static final String DEPLOYMENT_BUILD_AGE_SECONDS = "deployment.buildAgeSeconds";
public static final String DEPLOYMENT_WARNINGS = "deployment.warnings";
public static final String OS_CHANGE_DURATION = "deployment.osChangeDuration";
public static final String PLATFORM_CHANGE_DURATION = "deployment.platformChangeDuration";
public static final String OS_NODE_COUNT = "deployment.nodeCountByOsVersion";
public static final String PLATFORM_NODE_COUNT = "deployment.nodeCountByPlatformVersion";
public static final String REMAINING_ROTATIONS = "remaining_rotations";
public static final String NAME_SERVICE_REQUESTS_QUEUED = "dns.queuedRequests";
public static final String OPERATION_PREFIX = "operation.";
private final Metric metric;
private final Clock clock;
private final ConcurrentHashMap<NodeCountKey, Long> nodeCounts = new ConcurrentHashMap<>();
public MetricsReporter(Controller controller, Metric metric) {
super(controller, Duration.ofMinutes(1));
this.metric = metric;
this.clock = controller.clock();
}
@Override
public void maintain() {
reportDeploymentMetrics();
reportRemainingRotations();
reportQueuedNameServiceRequests();
reportInfrastructureUpgradeMetrics();
reportAuditLog();
}
private void reportInfrastructureUpgradeMetrics() {
Map<NodeVersion, Duration> osChangeDurations = osChangeDurations();
Map<NodeVersion, Duration> platformChangeDurations = platformChangeDurations();
reportChangeDurations(osChangeDurations, OS_CHANGE_DURATION);
reportChangeDurations(platformChangeDurations, PLATFORM_CHANGE_DURATION);
reportNodeCount(osChangeDurations.keySet(), OS_NODE_COUNT);
reportNodeCount(platformChangeDurations.keySet(), PLATFORM_NODE_COUNT);
}
private void reportRemainingRotations() {
try (RotationLock lock = controller().routing().rotations().lock()) {
int availableRotations = controller().routing().rotations().availableRotations(lock).size();
metric.set(REMAINING_ROTATIONS, availableRotations, metric.createContext(Map.of()));
}
}
private void reportDeploymentMetrics() {
ApplicationList applications = ApplicationList.from(controller().applications().readable())
.withProductionDeployment();
DeploymentStatusList deployments = controller().jobController().deploymentStatuses(applications);
metric.set(DEPLOYMENT_FAIL_METRIC, deploymentFailRatio(deployments) * 100, metric.createContext(Map.of()));
averageDeploymentDurations(deployments, clock.instant()).forEach((instance, duration) -> {
metric.set(DEPLOYMENT_AVERAGE_DURATION, duration.getSeconds(), metric.createContext(dimensions(instance)));
});
deploymentsFailingUpgrade(deployments).forEach((instance, failingJobs) -> {
metric.set(DEPLOYMENT_FAILING_UPGRADES, failingJobs, metric.createContext(dimensions(instance)));
});
deploymentWarnings(deployments).forEach((application, warnings) -> {
metric.set(DEPLOYMENT_WARNINGS, warnings, metric.createContext(dimensions(application)));
});
for (Application application : applications.asList())
application.latestVersion()
.flatMap(ApplicationVersion::buildTime)
.ifPresent(buildTime -> metric.set(DEPLOYMENT_BUILD_AGE_SECONDS,
controller().clock().instant().getEpochSecond() - buildTime.getEpochSecond(),
metric.createContext(dimensions(application.id().defaultInstance()))));
}
private void reportQueuedNameServiceRequests() {
metric.set(NAME_SERVICE_REQUESTS_QUEUED, controller().curator().readNameServiceQueue().requests().size(),
metric.createContext(Map.of()));
}
private void reportNodeCount(Set<NodeVersion> nodeVersions, String metricName) {
Map<NodeCountKey, Long> newNodeCounts = nodeVersions.stream()
.collect(Collectors.groupingBy(nodeVersion -> {
return new NodeCountKey(metricName,
nodeVersion.currentVersion(),
nodeVersion.zone());
}, Collectors.counting()));
nodeCounts.putAll(newNodeCounts);
nodeCounts.forEach((key, count) -> {
if (newNodeCounts.containsKey(key)) {
metric.set(metricName, count, metric.createContext(dimensions(key.zone, key.version)));
} else if (key.metricName.equals(metricName)) {
metric.set(metricName, 0, metric.createContext(dimensions(key.zone, key.version)));
}
});
}
private void reportChangeDurations(Map<NodeVersion, Duration> changeDurations, String metricName) {
changeDurations.forEach((nodeVersion, duration) -> {
metric.set(metricName, duration.toSeconds(), metric.createContext(dimensions(nodeVersion.hostname(), nodeVersion.zone())));
});
}
private Map<NodeVersion, Duration> platformChangeDurations() {
return changeDurations(controller().versionStatus().versions(), VespaVersion::nodeVersions);
}
private Map<NodeVersion, Duration> osChangeDurations() {
return changeDurations(controller().osVersionStatus().versions().values(), Function.identity());
}
private <V> Map<NodeVersion, Duration> changeDurations(Collection<V> versions, Function<V, NodeVersions> versionsGetter) {
var now = clock.instant();
var durations = new HashMap<NodeVersion, Duration>();
for (var version : versions) {
for (var nodeVersion : versionsGetter.apply(version).asMap().values()) {
durations.put(nodeVersion, nodeVersion.changeDuration(now));
}
}
return durations;
}
private static double deploymentFailRatio(DeploymentStatusList statuses) {
return statuses.asList().stream()
.mapToInt(status -> status.hasFailures() ? 1 : 0)
.average().orElse(0);
}
private static Map<ApplicationId, Duration> averageDeploymentDurations(DeploymentStatusList statuses, Instant now) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> averageDeploymentDuration(entry.getValue(), now)));
}
private static Map<ApplicationId, Integer> deploymentsFailingUpgrade(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> deploymentsFailingUpgrade(entry.getValue())));
}
private static int deploymentsFailingUpgrade(JobList jobs) {
return jobs.failing().not().failingApplicationChange().size();
}
private static Duration averageDeploymentDuration(JobList jobs, Instant now) {
List<Duration> jobDurations = jobs.lastTriggered()
.mapToList(run -> Duration.between(run.start(), run.end().orElse(now)));
return jobDurations.stream()
.reduce(Duration::plus)
.map(totalDuration -> totalDuration.dividedBy(jobDurations.size()))
.orElse(Duration.ZERO);
}
private static Map<ApplicationId, Integer> deploymentWarnings(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.application().instances().values().stream())
.collect(Collectors.toMap(Instance::id, a -> maxWarningCountOf(a.deployments().values())));
}
private static int maxWarningCountOf(Collection<Deployment> deployments) {
return deployments.stream()
.map(Deployment::metrics)
.map(DeploymentMetrics::warnings)
.map(Map::values)
.flatMap(Collection::stream)
.max(Integer::compareTo)
.orElse(0);
}
private static Map<String, String> dimensions(ApplicationId application) {
return Map.of("tenant", application.tenant().value(),
"app",application.application().value() + "." + application.instance().value());
}
private static Map<String, String> dimensions(HostName hostname, ZoneId zone) {
return Map.of("host", hostname.value(),
"zone", zone.value());
}
private static Map<String, String> dimensions(ZoneId zone, Version currentVersion) {
return Map.of("zone", zone.value(),
"currentVersion", currentVersion.toFullString());
}
private static class NodeCountKey {
private final String metricName;
private final Version version;
private final ZoneId zone;
public NodeCountKey(String metricName, Version version, ZoneId zone) {
this.metricName = metricName;
this.version = version;
this.zone = zone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeCountKey that = (NodeCountKey) o;
return metricName.equals(that.metricName) &&
version.equals(that.version) &&
zone.equals(that.zone);
}
@Override
public int hashCode() {
return Objects.hash(metricName, version, zone);
}
}
} | class MetricsReporter extends ControllerMaintainer {
public static final String DEPLOYMENT_FAIL_METRIC = "deployment.failurePercentage";
public static final String DEPLOYMENT_AVERAGE_DURATION = "deployment.averageDuration";
public static final String DEPLOYMENT_FAILING_UPGRADES = "deployment.failingUpgrades";
public static final String DEPLOYMENT_BUILD_AGE_SECONDS = "deployment.buildAgeSeconds";
public static final String DEPLOYMENT_WARNINGS = "deployment.warnings";
public static final String OS_CHANGE_DURATION = "deployment.osChangeDuration";
public static final String PLATFORM_CHANGE_DURATION = "deployment.platformChangeDuration";
public static final String OS_NODE_COUNT = "deployment.nodeCountByOsVersion";
public static final String PLATFORM_NODE_COUNT = "deployment.nodeCountByPlatformVersion";
public static final String REMAINING_ROTATIONS = "remaining_rotations";
public static final String NAME_SERVICE_REQUESTS_QUEUED = "dns.queuedRequests";
public static final String OPERATION_PREFIX = "operation.";
private final Metric metric;
private final Clock clock;
private final ConcurrentHashMap<NodeCountKey, Long> nodeCounts = new ConcurrentHashMap<>();
public MetricsReporter(Controller controller, Metric metric) {
super(controller, Duration.ofMinutes(1));
this.metric = metric;
this.clock = controller.clock();
}
@Override
public void maintain() {
reportDeploymentMetrics();
reportRemainingRotations();
reportQueuedNameServiceRequests();
reportInfrastructureUpgradeMetrics();
reportAuditLog();
}
private void reportInfrastructureUpgradeMetrics() {
Map<NodeVersion, Duration> osChangeDurations = osChangeDurations();
Map<NodeVersion, Duration> platformChangeDurations = platformChangeDurations();
reportChangeDurations(osChangeDurations, OS_CHANGE_DURATION);
reportChangeDurations(platformChangeDurations, PLATFORM_CHANGE_DURATION);
reportNodeCount(osChangeDurations.keySet(), OS_NODE_COUNT);
reportNodeCount(platformChangeDurations.keySet(), PLATFORM_NODE_COUNT);
}
private void reportRemainingRotations() {
try (RotationLock lock = controller().routing().rotations().lock()) {
int availableRotations = controller().routing().rotations().availableRotations(lock).size();
metric.set(REMAINING_ROTATIONS, availableRotations, metric.createContext(Map.of()));
}
}
private void reportDeploymentMetrics() {
ApplicationList applications = ApplicationList.from(controller().applications().readable())
.withProductionDeployment();
DeploymentStatusList deployments = controller().jobController().deploymentStatuses(applications);
metric.set(DEPLOYMENT_FAIL_METRIC, deploymentFailRatio(deployments) * 100, metric.createContext(Map.of()));
averageDeploymentDurations(deployments, clock.instant()).forEach((instance, duration) -> {
metric.set(DEPLOYMENT_AVERAGE_DURATION, duration.getSeconds(), metric.createContext(dimensions(instance)));
});
deploymentsFailingUpgrade(deployments).forEach((instance, failingJobs) -> {
metric.set(DEPLOYMENT_FAILING_UPGRADES, failingJobs, metric.createContext(dimensions(instance)));
});
deploymentWarnings(deployments).forEach((application, warnings) -> {
metric.set(DEPLOYMENT_WARNINGS, warnings, metric.createContext(dimensions(application)));
});
for (Application application : applications.asList())
application.latestVersion()
.flatMap(ApplicationVersion::buildTime)
.ifPresent(buildTime -> metric.set(DEPLOYMENT_BUILD_AGE_SECONDS,
controller().clock().instant().getEpochSecond() - buildTime.getEpochSecond(),
metric.createContext(dimensions(application.id().defaultInstance()))));
}
private void reportQueuedNameServiceRequests() {
metric.set(NAME_SERVICE_REQUESTS_QUEUED, controller().curator().readNameServiceQueue().requests().size(),
metric.createContext(Map.of()));
}
private void reportNodeCount(Set<NodeVersion> nodeVersions, String metricName) {
Map<NodeCountKey, Long> newNodeCounts = nodeVersions.stream()
.collect(Collectors.groupingBy(nodeVersion -> {
return new NodeCountKey(metricName,
nodeVersion.currentVersion(),
nodeVersion.zone());
}, Collectors.counting()));
nodeCounts.putAll(newNodeCounts);
nodeCounts.forEach((key, count) -> {
if (newNodeCounts.containsKey(key)) {
metric.set(metricName, count, metric.createContext(dimensions(key.zone, key.version)));
} else if (key.metricName.equals(metricName)) {
metric.set(metricName, 0, metric.createContext(dimensions(key.zone, key.version)));
}
});
}
private void reportChangeDurations(Map<NodeVersion, Duration> changeDurations, String metricName) {
changeDurations.forEach((nodeVersion, duration) -> {
metric.set(metricName, duration.toSeconds(), metric.createContext(dimensions(nodeVersion.hostname(), nodeVersion.zone())));
});
}
private Map<NodeVersion, Duration> platformChangeDurations() {
return changeDurations(controller().versionStatus().versions(), VespaVersion::nodeVersions);
}
private Map<NodeVersion, Duration> osChangeDurations() {
return changeDurations(controller().osVersionStatus().versions().values(), Function.identity());
}
private <V> Map<NodeVersion, Duration> changeDurations(Collection<V> versions, Function<V, NodeVersions> versionsGetter) {
var now = clock.instant();
var durations = new HashMap<NodeVersion, Duration>();
for (var version : versions) {
for (var nodeVersion : versionsGetter.apply(version).asMap().values()) {
durations.put(nodeVersion, nodeVersion.changeDuration(now));
}
}
return durations;
}
private static double deploymentFailRatio(DeploymentStatusList statuses) {
return statuses.asList().stream()
.mapToInt(status -> status.hasFailures() ? 1 : 0)
.average().orElse(0);
}
private static Map<ApplicationId, Duration> averageDeploymentDurations(DeploymentStatusList statuses, Instant now) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> averageDeploymentDuration(entry.getValue(), now)));
}
private static Map<ApplicationId, Integer> deploymentsFailingUpgrade(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.instanceJobs().entrySet().stream())
.collect(Collectors.toUnmodifiableMap(entry -> entry.getKey(),
entry -> deploymentsFailingUpgrade(entry.getValue())));
}
private static int deploymentsFailingUpgrade(JobList jobs) {
return jobs.failing().not().failingApplicationChange().size();
}
private static Duration averageDeploymentDuration(JobList jobs, Instant now) {
List<Duration> jobDurations = jobs.lastTriggered()
.mapToList(run -> Duration.between(run.start(), run.end().orElse(now)));
return jobDurations.stream()
.reduce(Duration::plus)
.map(totalDuration -> totalDuration.dividedBy(jobDurations.size()))
.orElse(Duration.ZERO);
}
private static Map<ApplicationId, Integer> deploymentWarnings(DeploymentStatusList statuses) {
return statuses.asList().stream()
.flatMap(status -> status.application().instances().values().stream())
.collect(Collectors.toMap(Instance::id, a -> maxWarningCountOf(a.deployments().values())));
}
private static int maxWarningCountOf(Collection<Deployment> deployments) {
return deployments.stream()
.map(Deployment::metrics)
.map(DeploymentMetrics::warnings)
.map(Map::values)
.flatMap(Collection::stream)
.max(Integer::compareTo)
.orElse(0);
}
private static Map<String, String> dimensions(ApplicationId application) {
return Map.of("tenant", application.tenant().value(),
"app",application.application().value() + "." + application.instance().value());
}
private static Map<String, String> dimensions(HostName hostname, ZoneId zone) {
return Map.of("host", hostname.value(),
"zone", zone.value());
}
private static Map<String, String> dimensions(ZoneId zone, Version currentVersion) {
return Map.of("zone", zone.value(),
"currentVersion", currentVersion.toFullString());
}
private static class NodeCountKey {
private final String metricName;
private final Version version;
private final ZoneId zone;
public NodeCountKey(String metricName, Version version, ZoneId zone) {
this.metricName = metricName;
this.version = version;
this.zone = zone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeCountKey that = (NodeCountKey) o;
return metricName.equals(that.metricName) &&
version.equals(that.version) &&
zone.equals(that.zone);
}
@Override
public int hashCode() {
return Objects.hash(metricName, version, zone);
}
}
} |
Could probably remove most of these from LocalSession, if they're not to be used on that? | public ApplicationMetaData getMetaData() {
return zooKeeperClient.loadApplicationPackage().getMetaData();
} | } | public ApplicationMetaData getMetaData() {
return zooKeeperClient.loadApplicationPackage().getMetaData();
} | class RemoteSession extends Session {
private static final Logger log = Logger.getLogger(RemoteSession.class.getName());
private ApplicationSet applicationSet = null;
private final ActivatedModelsBuilder applicationLoader;
private final Clock clock;
/**
* Creates a session. This involves loading the application, validating it and distributing it.
*
* @param tenant The name of the tenant creating session
* @param sessionId The session id for this session.
* @param componentRegistry a registry of global components
* @param zooKeeperClient a SessionZooKeeperClient instance
*/
public RemoteSession(TenantName tenant,
long sessionId,
GlobalComponentRegistry componentRegistry,
SessionZooKeeperClient zooKeeperClient) {
super(tenant, sessionId, zooKeeperClient);
this.applicationLoader = new ActivatedModelsBuilder(tenant, sessionId, zooKeeperClient, componentRegistry);
this.clock = componentRegistry.getClock();
}
void loadPrepared() {
Curator.CompletionWaiter waiter = zooKeeperClient.getPrepareWaiter();
ensureApplicationLoaded();
notifyCompletion(waiter);
}
private ApplicationSet loadApplication() {
ApplicationPackage applicationPackage = zooKeeperClient.loadApplicationPackage();
Optional<AllocatedHosts> allocatedHosts = applicationPackage.getAllocatedHosts();
return ApplicationSet.fromList(applicationLoader.buildModels(zooKeeperClient.readApplicationId(),
zooKeeperClient.readDockerImageRepository(),
zooKeeperClient.readVespaVersion(),
applicationPackage,
new SettableOptional<>(allocatedHosts),
clock.instant()));
}
public synchronized ApplicationSet ensureApplicationLoaded() {
return applicationSet == null ? applicationSet = loadApplication() : applicationSet;
}
public Session.Status getStatus() {
return zooKeeperClient.readStatus();
}
public synchronized void deactivate() {
applicationSet = null;
}
public Transaction createDeleteTransaction() {
return zooKeeperClient.createWriteStatusTransaction(Status.DELETE);
}
void makeActive(ReloadHandler reloadHandler) {
Curator.CompletionWaiter waiter = zooKeeperClient.getActiveWaiter();
log.log(Level.FINE, () -> logPre() + "Getting session from repo: " + getSessionId());
ApplicationSet app = ensureApplicationLoaded();
log.log(Level.FINE, () -> logPre() + "Reloading config for " + getSessionId());
reloadHandler.reloadConfig(app);
log.log(Level.FINE, () -> logPre() + "Notifying " + waiter);
notifyCompletion(waiter);
log.log(Level.INFO, logPre() + "Session activated: " + getSessionId());
}
@Override
public String logPre() {
if (getApplicationId().equals(ApplicationId.defaultId())) {
return TenantRepository.logPre(getTenant());
} else {
return TenantRepository.logPre(getApplicationId());
}
}
void confirmUpload() {
Curator.CompletionWaiter waiter = zooKeeperClient.getUploadWaiter();
log.log(Level.FINE, "Notifying upload waiter for session " + getSessionId());
notifyCompletion(waiter);
log.log(Level.FINE, "Done notifying upload for session " + getSessionId());
}
private void notifyCompletion(Curator.CompletionWaiter completionWaiter) {
try {
completionWaiter.notifyCompletion();
} catch (RuntimeException e) {
if (e.getCause().getClass() != KeeperException.NoNodeException.class) {
throw e;
} else {
log.log(Level.INFO, "Not able to notify completion for session: " + getSessionId() + ", node has been deleted");
}
}
}
public void delete() {
Transaction transaction = zooKeeperClient.deleteTransaction();
transaction.commit();
transaction.close();
}
public ApplicationId getApplicationId() { return zooKeeperClient.readApplicationId(); }
public Optional<DockerImage> getDockerImageRepository() { return zooKeeperClient.readDockerImageRepository(); }
public Version getVespaVersion() { return zooKeeperClient.readVespaVersion(); }
public Optional<AthenzDomain> getAthenzDomain() { return zooKeeperClient.readAthenzDomain(); }
public AllocatedHosts getAllocatedHosts() {
return zooKeeperClient.getAllocatedHosts();
}
public boolean isNewerThan(long sessionId) {
return getSessionId() > sessionId;
}
public Transaction createDeactivateTransaction() {
return createSetStatusTransaction(Status.DEACTIVATE);
}
private Transaction createSetStatusTransaction(Status status) {
return zooKeeperClient.createWriteStatusTransaction(status);
}
} | class RemoteSession extends Session {
private static final Logger log = Logger.getLogger(RemoteSession.class.getName());
private ApplicationSet applicationSet = null;
private final ActivatedModelsBuilder applicationLoader;
private final Clock clock;
/**
* Creates a session. This involves loading the application, validating it and distributing it.
*
* @param tenant The name of the tenant creating session
* @param sessionId The session id for this session.
* @param componentRegistry a registry of global components
* @param zooKeeperClient a SessionZooKeeperClient instance
*/
public RemoteSession(TenantName tenant,
long sessionId,
GlobalComponentRegistry componentRegistry,
SessionZooKeeperClient zooKeeperClient) {
super(tenant, sessionId, zooKeeperClient);
this.applicationLoader = new ActivatedModelsBuilder(tenant, sessionId, zooKeeperClient, componentRegistry);
this.clock = componentRegistry.getClock();
}
void loadPrepared() {
Curator.CompletionWaiter waiter = zooKeeperClient.getPrepareWaiter();
ensureApplicationLoaded();
notifyCompletion(waiter);
}
private ApplicationSet loadApplication() {
ApplicationPackage applicationPackage = zooKeeperClient.loadApplicationPackage();
Optional<AllocatedHosts> allocatedHosts = applicationPackage.getAllocatedHosts();
return ApplicationSet.fromList(applicationLoader.buildModels(zooKeeperClient.readApplicationId(),
zooKeeperClient.readDockerImageRepository(),
zooKeeperClient.readVespaVersion(),
applicationPackage,
new SettableOptional<>(allocatedHosts),
clock.instant()));
}
public synchronized ApplicationSet ensureApplicationLoaded() {
return applicationSet == null ? applicationSet = loadApplication() : applicationSet;
}
public Session.Status getStatus() {
return zooKeeperClient.readStatus();
}
public synchronized void deactivate() {
applicationSet = null;
}
public Transaction createDeleteTransaction() {
return zooKeeperClient.createWriteStatusTransaction(Status.DELETE);
}
void makeActive(ReloadHandler reloadHandler) {
Curator.CompletionWaiter waiter = zooKeeperClient.getActiveWaiter();
log.log(Level.FINE, () -> logPre() + "Getting session from repo: " + getSessionId());
ApplicationSet app = ensureApplicationLoaded();
log.log(Level.FINE, () -> logPre() + "Reloading config for " + getSessionId());
reloadHandler.reloadConfig(app);
log.log(Level.FINE, () -> logPre() + "Notifying " + waiter);
notifyCompletion(waiter);
log.log(Level.INFO, logPre() + "Session activated: " + getSessionId());
}
@Override
public String logPre() {
if (getApplicationId().equals(ApplicationId.defaultId())) {
return TenantRepository.logPre(getTenant());
} else {
return TenantRepository.logPre(getApplicationId());
}
}
void confirmUpload() {
Curator.CompletionWaiter waiter = zooKeeperClient.getUploadWaiter();
log.log(Level.FINE, "Notifying upload waiter for session " + getSessionId());
notifyCompletion(waiter);
log.log(Level.FINE, "Done notifying upload for session " + getSessionId());
}
private void notifyCompletion(Curator.CompletionWaiter completionWaiter) {
try {
completionWaiter.notifyCompletion();
} catch (RuntimeException e) {
if (e.getCause().getClass() != KeeperException.NoNodeException.class) {
throw e;
} else {
log.log(Level.INFO, "Not able to notify completion for session: " + getSessionId() + ", node has been deleted");
}
}
}
public void delete() {
Transaction transaction = zooKeeperClient.deleteTransaction();
transaction.commit();
transaction.close();
}
public ApplicationId getApplicationId() { return zooKeeperClient.readApplicationId(); }
public Optional<DockerImage> getDockerImageRepository() { return zooKeeperClient.readDockerImageRepository(); }
public Version getVespaVersion() { return zooKeeperClient.readVespaVersion(); }
public Optional<AthenzDomain> getAthenzDomain() { return zooKeeperClient.readAthenzDomain(); }
public AllocatedHosts getAllocatedHosts() {
return zooKeeperClient.getAllocatedHosts();
}
public boolean isNewerThan(long sessionId) {
return getSessionId() > sessionId;
}
public Transaction createDeactivateTransaction() {
return createSetStatusTransaction(Status.DEACTIVATE);
}
private Transaction createSetStatusTransaction(Status status) {
return zooKeeperClient.createWriteStatusTransaction(status);
}
} |
I think I removed those that could be removed. I want to do more refactoring in this area, but let's try this first. | public ApplicationMetaData getMetaData() {
return zooKeeperClient.loadApplicationPackage().getMetaData();
} | } | public ApplicationMetaData getMetaData() {
return zooKeeperClient.loadApplicationPackage().getMetaData();
} | class RemoteSession extends Session {
private static final Logger log = Logger.getLogger(RemoteSession.class.getName());
private ApplicationSet applicationSet = null;
private final ActivatedModelsBuilder applicationLoader;
private final Clock clock;
/**
* Creates a session. This involves loading the application, validating it and distributing it.
*
* @param tenant The name of the tenant creating session
* @param sessionId The session id for this session.
* @param componentRegistry a registry of global components
* @param zooKeeperClient a SessionZooKeeperClient instance
*/
public RemoteSession(TenantName tenant,
long sessionId,
GlobalComponentRegistry componentRegistry,
SessionZooKeeperClient zooKeeperClient) {
super(tenant, sessionId, zooKeeperClient);
this.applicationLoader = new ActivatedModelsBuilder(tenant, sessionId, zooKeeperClient, componentRegistry);
this.clock = componentRegistry.getClock();
}
void loadPrepared() {
Curator.CompletionWaiter waiter = zooKeeperClient.getPrepareWaiter();
ensureApplicationLoaded();
notifyCompletion(waiter);
}
private ApplicationSet loadApplication() {
ApplicationPackage applicationPackage = zooKeeperClient.loadApplicationPackage();
Optional<AllocatedHosts> allocatedHosts = applicationPackage.getAllocatedHosts();
return ApplicationSet.fromList(applicationLoader.buildModels(zooKeeperClient.readApplicationId(),
zooKeeperClient.readDockerImageRepository(),
zooKeeperClient.readVespaVersion(),
applicationPackage,
new SettableOptional<>(allocatedHosts),
clock.instant()));
}
public synchronized ApplicationSet ensureApplicationLoaded() {
return applicationSet == null ? applicationSet = loadApplication() : applicationSet;
}
public Session.Status getStatus() {
return zooKeeperClient.readStatus();
}
public synchronized void deactivate() {
applicationSet = null;
}
public Transaction createDeleteTransaction() {
return zooKeeperClient.createWriteStatusTransaction(Status.DELETE);
}
void makeActive(ReloadHandler reloadHandler) {
Curator.CompletionWaiter waiter = zooKeeperClient.getActiveWaiter();
log.log(Level.FINE, () -> logPre() + "Getting session from repo: " + getSessionId());
ApplicationSet app = ensureApplicationLoaded();
log.log(Level.FINE, () -> logPre() + "Reloading config for " + getSessionId());
reloadHandler.reloadConfig(app);
log.log(Level.FINE, () -> logPre() + "Notifying " + waiter);
notifyCompletion(waiter);
log.log(Level.INFO, logPre() + "Session activated: " + getSessionId());
}
@Override
public String logPre() {
if (getApplicationId().equals(ApplicationId.defaultId())) {
return TenantRepository.logPre(getTenant());
} else {
return TenantRepository.logPre(getApplicationId());
}
}
void confirmUpload() {
Curator.CompletionWaiter waiter = zooKeeperClient.getUploadWaiter();
log.log(Level.FINE, "Notifying upload waiter for session " + getSessionId());
notifyCompletion(waiter);
log.log(Level.FINE, "Done notifying upload for session " + getSessionId());
}
private void notifyCompletion(Curator.CompletionWaiter completionWaiter) {
try {
completionWaiter.notifyCompletion();
} catch (RuntimeException e) {
if (e.getCause().getClass() != KeeperException.NoNodeException.class) {
throw e;
} else {
log.log(Level.INFO, "Not able to notify completion for session: " + getSessionId() + ", node has been deleted");
}
}
}
public void delete() {
Transaction transaction = zooKeeperClient.deleteTransaction();
transaction.commit();
transaction.close();
}
public ApplicationId getApplicationId() { return zooKeeperClient.readApplicationId(); }
public Optional<DockerImage> getDockerImageRepository() { return zooKeeperClient.readDockerImageRepository(); }
public Version getVespaVersion() { return zooKeeperClient.readVespaVersion(); }
public Optional<AthenzDomain> getAthenzDomain() { return zooKeeperClient.readAthenzDomain(); }
public AllocatedHosts getAllocatedHosts() {
return zooKeeperClient.getAllocatedHosts();
}
public boolean isNewerThan(long sessionId) {
return getSessionId() > sessionId;
}
public Transaction createDeactivateTransaction() {
return createSetStatusTransaction(Status.DEACTIVATE);
}
private Transaction createSetStatusTransaction(Status status) {
return zooKeeperClient.createWriteStatusTransaction(status);
}
} | class RemoteSession extends Session {
private static final Logger log = Logger.getLogger(RemoteSession.class.getName());
private ApplicationSet applicationSet = null;
private final ActivatedModelsBuilder applicationLoader;
private final Clock clock;
/**
* Creates a session. This involves loading the application, validating it and distributing it.
*
* @param tenant The name of the tenant creating session
* @param sessionId The session id for this session.
* @param componentRegistry a registry of global components
* @param zooKeeperClient a SessionZooKeeperClient instance
*/
public RemoteSession(TenantName tenant,
long sessionId,
GlobalComponentRegistry componentRegistry,
SessionZooKeeperClient zooKeeperClient) {
super(tenant, sessionId, zooKeeperClient);
this.applicationLoader = new ActivatedModelsBuilder(tenant, sessionId, zooKeeperClient, componentRegistry);
this.clock = componentRegistry.getClock();
}
void loadPrepared() {
Curator.CompletionWaiter waiter = zooKeeperClient.getPrepareWaiter();
ensureApplicationLoaded();
notifyCompletion(waiter);
}
private ApplicationSet loadApplication() {
ApplicationPackage applicationPackage = zooKeeperClient.loadApplicationPackage();
Optional<AllocatedHosts> allocatedHosts = applicationPackage.getAllocatedHosts();
return ApplicationSet.fromList(applicationLoader.buildModels(zooKeeperClient.readApplicationId(),
zooKeeperClient.readDockerImageRepository(),
zooKeeperClient.readVespaVersion(),
applicationPackage,
new SettableOptional<>(allocatedHosts),
clock.instant()));
}
public synchronized ApplicationSet ensureApplicationLoaded() {
return applicationSet == null ? applicationSet = loadApplication() : applicationSet;
}
public Session.Status getStatus() {
return zooKeeperClient.readStatus();
}
public synchronized void deactivate() {
applicationSet = null;
}
public Transaction createDeleteTransaction() {
return zooKeeperClient.createWriteStatusTransaction(Status.DELETE);
}
void makeActive(ReloadHandler reloadHandler) {
Curator.CompletionWaiter waiter = zooKeeperClient.getActiveWaiter();
log.log(Level.FINE, () -> logPre() + "Getting session from repo: " + getSessionId());
ApplicationSet app = ensureApplicationLoaded();
log.log(Level.FINE, () -> logPre() + "Reloading config for " + getSessionId());
reloadHandler.reloadConfig(app);
log.log(Level.FINE, () -> logPre() + "Notifying " + waiter);
notifyCompletion(waiter);
log.log(Level.INFO, logPre() + "Session activated: " + getSessionId());
}
@Override
public String logPre() {
if (getApplicationId().equals(ApplicationId.defaultId())) {
return TenantRepository.logPre(getTenant());
} else {
return TenantRepository.logPre(getApplicationId());
}
}
void confirmUpload() {
Curator.CompletionWaiter waiter = zooKeeperClient.getUploadWaiter();
log.log(Level.FINE, "Notifying upload waiter for session " + getSessionId());
notifyCompletion(waiter);
log.log(Level.FINE, "Done notifying upload for session " + getSessionId());
}
private void notifyCompletion(Curator.CompletionWaiter completionWaiter) {
try {
completionWaiter.notifyCompletion();
} catch (RuntimeException e) {
if (e.getCause().getClass() != KeeperException.NoNodeException.class) {
throw e;
} else {
log.log(Level.INFO, "Not able to notify completion for session: " + getSessionId() + ", node has been deleted");
}
}
}
public void delete() {
Transaction transaction = zooKeeperClient.deleteTransaction();
transaction.commit();
transaction.close();
}
public ApplicationId getApplicationId() { return zooKeeperClient.readApplicationId(); }
public Optional<DockerImage> getDockerImageRepository() { return zooKeeperClient.readDockerImageRepository(); }
public Version getVespaVersion() { return zooKeeperClient.readVespaVersion(); }
public Optional<AthenzDomain> getAthenzDomain() { return zooKeeperClient.readAthenzDomain(); }
public AllocatedHosts getAllocatedHosts() {
return zooKeeperClient.getAllocatedHosts();
}
public boolean isNewerThan(long sessionId) {
return getSessionId() > sessionId;
}
public Transaction createDeactivateTransaction() {
return createSetStatusTransaction(Status.DEACTIVATE);
}
private Transaction createSetStatusTransaction(Status status) {
return zooKeeperClient.createWriteStatusTransaction(status);
}
} |
There are issues both with using the target platform version, and with using the system version. Sometimes you want one, sometimes the other. We _could_ use system version if the application wasn't _pinned_ to a particular version, and that particular version if it was, to address this in a better way. Probably not the answer to everything either, but should solve this. | private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version targetPlatform = controller.jobController().run(id).get().versions().targetPlatform();
final Version platform = targetPlatform.equals(Version.fromString("7.220.14"))
? targetPlatform
: controller.systemVersion();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
platform),
controller.jobController().run(id).get()
.stepInfo(deployTester).get()
.startTime().get(),
logger);
} | final Version platform = targetPlatform.equals(Version.fromString("7.220.14")) | private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version targetPlatform = controller.jobController().run(id).get().versions().targetPlatform();
final Version platform = targetPlatform.equals(Version.fromString("7.220.14"))
? targetPlatform
: controller.systemVersion();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
platform),
controller.jobController().run(id).get()
.stepInfo(deployTester).get()
.startTime().get(),
logger);
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
private final Timeouts timeouts;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
this.timeouts = Timeouts.of(controller.system());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startStagingSetup: return startTests(id, true, logger);
case endStagingSetup:
case endTests: return endTests(id, logger);
case startTests: return startTests(id, false, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (step.get().alwaysRun()) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, DualLogger logger) {
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy2(id.job(), setTheStage),
controller.jobController().run(id).get()
.stepInfo(setTheStage ? deployInitialReal : deployReal).get()
.startTime().get(),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment,
Instant startTime, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if (prepareResponse.log != null)
logger.logAll(prepareResponse.log.stream()
.map(entry -> new LogEntry(0,
Instant.ofEpochMilli(entry.time),
LogEntry.typeOf(LogLevel.parse(entry.level)),
entry.message))
.collect(toList()));
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Schedule service restart on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
Optional<RunStatus> result = startTime.isBefore(controller.clock().instant().minus(Duration.ofHours(1)))
? Optional.of(deploymentFailed) : Optional.empty();
switch (e.getErrorCode()) {
case CERTIFICATE_NOT_READY:
if (startTime.plus(timeouts.endpointCertificate()).isBefore(controller.clock().instant())) {
logger.log("Deployment failed to find provisioned endpoint certificate after " + timeouts.endpointCertificate());
return Optional.of(RunStatus.endpointCertificateTimeout);
}
return result;
case ACTIVATION_CONFLICT:
case APPLICATION_LOCK_FAILURE:
logger.log("Deployment failed with possibly transient error " + e.getErrorCode() +
", will retry: " + e.getMessage());
return result;
case LOAD_BALANCER_NOT_READY:
case PARENT_HOST_NOT_READY:
logger.log(e.getServerMessage());
return result;
case OUT_OF_CAPACITY:
logger.log(e.getServerMessage());
return controller.system().isCd() && startTime.plus(timeouts.capacity()).isAfter(controller.clock().instant())
? Optional.empty()
: Optional.of(outOfCapacity);
case INVALID_APPLICATION_PACKAGE:
case BAD_REQUEST:
logger.log(e.getMessage());
return Optional.of(deploymentFailed);
}
throw e;
}
catch (EndpointCertificateException e) {
switch (e.type()) {
case CERT_NOT_AVAILABLE:
if (startTime.plus(timeouts.endpointCertificate()).isBefore(controller.clock().instant())) {
logger.log("Deployment failed to find provisioned endpoint certificate after " + timeouts.endpointCertificate());
return Optional.of(RunStatus.endpointCertificateTimeout);
}
return Optional.empty();
default:
throw e;
}
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
Run run = controller.jobController().run(id).get();
Optional<ServiceConvergence> services = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id.application(), id.type().zone(controller.system())),
Optional.of(platform));
if (services.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return Optional.empty();
}
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(id.type().zone(controller.system()),
id.application(),
ImmutableSet.of(active, reserved));
List<Node> parents = controller.serviceRegistry().configServer().nodeRepository().list(id.type().zone(controller.system()),
nodes.stream().map(node -> node.parentHostname().get()).collect(toList()));
NodeList nodeList = NodeList.of(nodes, parents, services.get());
boolean firstTick = run.convergenceSummary().isEmpty();
if (firstTick) {
logger.log("
logger.log(nodeList.asList().stream()
.flatMap(node -> nodeDetails(node, true))
.collect(toList()));
}
ConvergenceSummary summary = nodeList.summary();
if (summary.converged()) {
controller.jobController().locked(id, lockedRun -> lockedRun.withSummary(null));
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), timeouts.endpoint())) {
logger.log(WARNING, "Endpoints failed to show up within " + timeouts.endpoint().toMinutes() + " minutes!");
return Optional.of(error);
}
}
String failureReason = null;
NodeList suspendedTooLong = nodeList.suspendedSince(controller.clock().instant().minus(timeouts.nodesDown()));
if ( ! suspendedTooLong.isEmpty()) {
failureReason = "Some nodes have been suspended for more than " + timeouts.nodesDown().toMinutes() + " minutes:\n" +
suspendedTooLong.asList().stream().map(node -> node.node().hostname().value()).collect(joining("\n"));
}
if (run.noNodesDownSince()
.map(since -> since.isBefore(controller.clock().instant().minus(timeouts.noNodesDown())))
.orElse(false)) {
if (summary.needPlatformUpgrade() > 0 || summary.needReboot() > 0 || summary.needRestart() > 0)
failureReason = "No nodes allowed to suspend to progress installation for " + timeouts.noNodesDown().toMinutes() + " minutes.";
else
failureReason = "Nodes not able to start with new application package.";
}
Duration timeout = JobRunner.jobTimeout.minusHours(1);
if (timedOut(id, deployment.get(), timeout)) {
failureReason = "Installation failed to complete within " + timeout.toHours() + "hours!";
}
if (failureReason != null) {
logger.log("
logger.log(nodeList.asList().stream()
.flatMap(node -> nodeDetails(node, true))
.collect(toList()));
logger.log("
logger.log(nodeList.not().in(nodeList.not().needsNewConfig()
.not().needsPlatformUpgrade()
.not().needsReboot()
.not().needsRestart()
.not().needsFirmwareUpgrade()
.not().needsOsUpgrade())
.asList().stream()
.flatMap(node -> nodeDetails(node, true))
.collect(toList()));
logger.log(INFO, failureReason);
return Optional.of(installationFailed);
}
if ( ! firstTick)
logger.log(nodeList.expectedDown().concat(nodeList.needsNewConfig()).asList().stream()
.distinct()
.flatMap(node -> nodeDetails(node, false))
.collect(toList()));
controller.jobController().locked(id, lockedRun -> {
Instant noNodesDownSince = nodeList.allowedDown().size() == 0 ? lockedRun.noNodesDownSince().orElse(controller.clock().instant()) : null;
return lockedRun.noNodesDownSince(noNodesDownSince).withSummary(summary);
});
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Run run = controller.jobController().run(id).get();
Version platform = controller.systemVersion();
ZoneId zone = id.type().zone(controller.system());
ApplicationId testerId = id.tester().id();
Optional<ServiceConvergence> services = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(testerId, zone),
Optional.of(platform));
if (services.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return run.stepInfo(installTester).get().startTime().get().isBefore(controller.clock().instant().minus(Duration.ofMinutes(5)))
? Optional.of(error)
: Optional.empty();
}
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone,
testerId,
ImmutableSet.of(active, reserved));
List<Node> parents = controller.serviceRegistry().configServer().nodeRepository().list(zone,
nodes.stream().map(node -> node.parentHostname().get()).collect(toList()));
NodeList nodeList = NodeList.of(nodes, parents, services.get());
logger.log(nodeList.asList().stream()
.flatMap(node -> nodeDetails(node, false))
.collect(toList()));
if (nodeList.summary().converged() && testerContainersAreUp(testerId, zone, logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
if (run.stepInfo(installTester).get().startTime().get().plus(timeouts.tester()).isBefore(controller.clock().instant())) {
logger.log(WARNING, "Installation of tester failed to complete within " + timeouts.tester().toMinutes() + " minutes!");
return Optional.of(error);
}
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.routing().zoneEndpointsOf(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (var endpoint : endpoints.get(zoneId)) {
boolean ready = controller.jobController().cloud().ready(endpoint.url());
if ( ! ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
/** Returns true iff all containers in the tester deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean testerContainersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
DeploymentId deploymentId = new DeploymentId(id, zoneId);
if (controller.jobController().cloud().testerReady(deploymentId)) {
return true;
} else {
logger.log("Failed to get 100 consecutive OKs from tester container for " + deploymentId);
return false;
}
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
var endpoints = controller.routing().zoneEndpointsOf(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
var policies = controller.routing().policies().get(new DeploymentId(id, zone));
for (var endpoint : endpoints.get(zone)) {
HostName endpointName = HostName.from(endpoint.dnsName());
var ipAddress = controller.jobController().cloud().resolveHostName(endpointName);
if (ipAddress.isEmpty()) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpointName + "'.");
return false;
}
if (endpoint.routingMethod() == RoutingMethod.exclusive) {
var policy = policies.get(new RoutingPolicyId(id, ClusterSpec.Id.from(endpoint.name()), zone));
if (policy == null)
throw new IllegalStateException(endpoint + " has no matching policy in " + policies);
var cNameValue = controller.jobController().cloud().resolveCname(endpointName);
if ( ! cNameValue.map(policy.canonicalName()::equals).orElse(false)) {
logger.log(INFO, "CNAME '" + endpointName + "' points at " +
cNameValue.map(name -> "'" + name + "'").orElse("nothing") +
" but should point at load balancer '" + policy.canonicalName() + "'");
return false;
}
var loadBalancerAddress = controller.jobController().cloud().resolveHostName(policy.canonicalName());
if ( ! loadBalancerAddress.equals(ipAddress)) {
logger.log(INFO, "IP address of CNAME '" + endpointName + "' (" + ipAddress.get() + ") and load balancer '" +
policy.canonicalName() + "' (" + loadBalancerAddress.orElse("empty") + ") are not equal");
return false;
}
}
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, List<Endpoint>> zoneEndpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
zoneEndpoints.forEach((zone, endpoints) -> {
messages.add("- " + zone);
for (Endpoint endpoint : endpoints)
messages.add(" |-- " + endpoint.url() + " (cluster '" + endpoint.name() + "')");
});
logger.log(messages);
}
private Stream<String> nodeDetails(NodeWithServices node, boolean printAllServices) {
return Stream.concat(Stream.of(node.node().hostname() + ": " + humanize(node.node().serviceState()) + (node.node().suspendedSince().map(since -> " since " + since).orElse("")),
"--- platform " + wantedPlatform(node.node()) + (node.needsPlatformUpgrade()
? " <-- " + currentPlatform(node.node())
: "") +
(node.needsOsUpgrade() && node.isAllowedDown()
? ", upgrading OS (" + node.node().wantedOsVersion() + " <-- " + node.node().currentOsVersion() + ")"
: "") +
(node.needsFirmwareUpgrade() && node.isAllowedDown()
? ", upgrading firmware"
: "") +
(node.needsRestart()
? ", restart pending (" + node.node().wantedRestartGeneration() + " <-- " + node.node().restartGeneration() + ")"
: "") +
(node.needsReboot()
? ", reboot pending (" + node.node().wantedRebootGeneration() + " <-- " + node.node().rebootGeneration() + ")"
: "")),
node.services().stream()
.filter(service -> printAllServices || node.needsNewConfig())
.map(service -> "--- " + service.type() + " on port " + service.port() + (service.currentGeneration() == -1
? " has not started "
: " has config generation " + service.currentGeneration() + ", wanted is " + node.wantedConfigGeneration())));
}
private String wantedPlatform(Node node) {
return node.wantedDockerImage().repository() + ":" + node.wantedVersion();
}
private String currentPlatform(Node node) {
String currentRepo = node.currentDockerImage().repository();
String wantedRepo = node.wantedDockerImage().repository();
return (currentRepo.equals(wantedRepo) ? "" : currentRepo + ":") + node.currentVersion();
}
private String humanize(Node.ServiceState state) {
switch (state) {
case allowedDown: return "allowed to be DOWN";
case expectedUp: return "expected to be UP";
case unorchestrated: return "unorchestrated";
default: return state.name();
}
}
private Optional<RunStatus> startTests(RunId id, boolean isSetup, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(error);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
ZoneId zoneId = id.type().zone(controller.system());
deployments.add(new DeploymentId(id.application(), zoneId));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.routing().zoneEndpointsOf(deployments);
if ( ! endpoints.containsKey(zoneId)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
if (!controller.jobController().cloud().testerReady(getTesterDeploymentId(id))) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
TesterCloud.Suite suite = TesterCloud.Suite.of(id.type(), isSetup);
byte[] config = testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments));
controller.jobController().cloud().startTests(getTesterDeploymentId(id), suite, config);
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isEmpty()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(getTesterDeploymentId(id));
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return Optional.of(running);
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
Instant startTime = controller.jobController().run(id).get().stepInfo(deactivateReal).get().startTime().get();
return startTime.isBefore(controller.clock().instant().minus(Duration.ofHours(1)))
? Optional.of(error)
: Optional.empty();
}
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return Optional.of(running);
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
Instant startTime = controller.jobController().run(id).get().stepInfo(deactivateTester).get().startTime().get();
return startTime.isBefore(controller.clock().instant().minus(Duration.ofHours(1)))
? Optional.of(error)
: Optional.empty();
}
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.require(run.id().application().instance()).change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
logger.log(INFO, "Sending failure notification to " + String.join(", ", recipients));
mailOf(run, recipients).ifPresent(controller.serviceRegistry().mailer()::send);
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
private Optional<Mail> mailOf(Run run, List<String> recipients) {
switch (run.status()) {
case running:
case aborted:
case success:
return Optional.empty();
case outOfCapacity:
return run.id().type().isProduction() ? Optional.of(mails.outOfCapacity(run.id(), recipients)) : Optional.empty();
case deploymentFailed:
return Optional.of(mails.deploymentFailure(run.id(), recipients));
case installationFailed:
return Optional.of(mails.installationFailure(run.id(), recipients));
case testFailure:
return Optional.of(mails.testFailure(run.id(), recipients));
case error:
case endpointCertificateTimeout:
return Optional.of(mails.systemError(run.id(), recipients));
default:
logger.log(WARNING, "Don't know what mail to send for run status '" + run.status() + "'");
return Optional.of(mails.systemError(run.id(), recipients));
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zones where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if ( ! controller.system().isCd() && run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().environment().isTest();
byte[] servicesXml = servicesXml(! controller.system().isPublic(),
useTesterCertificate,
testerResourcesFor(zone, spec.requireInstance(id.application().instance())));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(timeouts.testerCertificate()),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private DeploymentId getTesterDeploymentId(RunId runId) {
ZoneId zoneId = runId.type().zone(controller.system());
return new DeploymentId(runId.tester().id(), zoneId);
}
static NodeResources testerResourcesFor(ZoneId zone, DeploymentInstanceSpec spec) {
return spec.steps().stream()
.filter(step -> step.concerns(zone.environment()))
.findFirst()
.flatMap(step -> step.zones().get(0).testerFlavor())
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES);
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(boolean systemUsesAthenz, boolean useTesterCertificate, NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + systemUsesAthenz + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void logAll(List<LogEntry> messages) {
controller.jobController().log(id, step, messages);
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
static class Timeouts {
private final SystemName system;
private Timeouts(SystemName system) {
this.system = requireNonNull(system);
}
public static Timeouts of(SystemName system) {
return new Timeouts(system);
}
Duration capacity() { return Duration.ofMinutes(system.isCd() ? 5 : 0); }
Duration endpoint() { return Duration.ofMinutes(15); }
Duration endpointCertificate() { return Duration.ofMinutes(20); }
Duration tester() { return Duration.ofMinutes(30); }
Duration nodesDown() { return Duration.ofMinutes(system.isCd() ? 30 : 60); }
Duration noNodesDown() { return Duration.ofMinutes(system.isCd() ? 30 : 120); }
Duration testerCertificate() { return Duration.ofMinutes(300); }
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
private final Timeouts timeouts;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
this.timeouts = Timeouts.of(controller.system());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startStagingSetup: return startTests(id, true, logger);
case endStagingSetup:
case endTests: return endTests(id, logger);
case startTests: return startTests(id, false, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (step.get().alwaysRun()) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, DualLogger logger) {
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy2(id.job(), setTheStage),
controller.jobController().run(id).get()
.stepInfo(setTheStage ? deployInitialReal : deployReal).get()
.startTime().get(),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment,
Instant startTime, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if (prepareResponse.log != null)
logger.logAll(prepareResponse.log.stream()
.map(entry -> new LogEntry(0,
Instant.ofEpochMilli(entry.time),
LogEntry.typeOf(LogLevel.parse(entry.level)),
entry.message))
.collect(toList()));
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Schedule service restart on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
Optional<RunStatus> result = startTime.isBefore(controller.clock().instant().minus(Duration.ofHours(1)))
? Optional.of(deploymentFailed) : Optional.empty();
switch (e.getErrorCode()) {
case CERTIFICATE_NOT_READY:
if (startTime.plus(timeouts.endpointCertificate()).isBefore(controller.clock().instant())) {
logger.log("Deployment failed to find provisioned endpoint certificate after " + timeouts.endpointCertificate());
return Optional.of(RunStatus.endpointCertificateTimeout);
}
return result;
case ACTIVATION_CONFLICT:
case APPLICATION_LOCK_FAILURE:
logger.log("Deployment failed with possibly transient error " + e.getErrorCode() +
", will retry: " + e.getMessage());
return result;
case LOAD_BALANCER_NOT_READY:
case PARENT_HOST_NOT_READY:
logger.log(e.getServerMessage());
return result;
case OUT_OF_CAPACITY:
logger.log(e.getServerMessage());
return controller.system().isCd() && startTime.plus(timeouts.capacity()).isAfter(controller.clock().instant())
? Optional.empty()
: Optional.of(outOfCapacity);
case INVALID_APPLICATION_PACKAGE:
case BAD_REQUEST:
logger.log(e.getMessage());
return Optional.of(deploymentFailed);
}
throw e;
}
catch (EndpointCertificateException e) {
switch (e.type()) {
case CERT_NOT_AVAILABLE:
if (startTime.plus(timeouts.endpointCertificate()).isBefore(controller.clock().instant())) {
logger.log("Deployment failed to find provisioned endpoint certificate after " + timeouts.endpointCertificate());
return Optional.of(RunStatus.endpointCertificateTimeout);
}
return Optional.empty();
default:
throw e;
}
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
Run run = controller.jobController().run(id).get();
Optional<ServiceConvergence> services = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id.application(), id.type().zone(controller.system())),
Optional.of(platform));
if (services.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return Optional.empty();
}
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(id.type().zone(controller.system()),
id.application(),
ImmutableSet.of(active, reserved));
List<Node> parents = controller.serviceRegistry().configServer().nodeRepository().list(id.type().zone(controller.system()),
nodes.stream().map(node -> node.parentHostname().get()).collect(toList()));
NodeList nodeList = NodeList.of(nodes, parents, services.get());
boolean firstTick = run.convergenceSummary().isEmpty();
if (firstTick) {
logger.log("
logger.log(nodeList.asList().stream()
.flatMap(node -> nodeDetails(node, true))
.collect(toList()));
}
ConvergenceSummary summary = nodeList.summary();
if (summary.converged()) {
controller.jobController().locked(id, lockedRun -> lockedRun.withSummary(null));
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), timeouts.endpoint())) {
logger.log(WARNING, "Endpoints failed to show up within " + timeouts.endpoint().toMinutes() + " minutes!");
return Optional.of(error);
}
}
String failureReason = null;
NodeList suspendedTooLong = nodeList.suspendedSince(controller.clock().instant().minus(timeouts.nodesDown()));
if ( ! suspendedTooLong.isEmpty()) {
failureReason = "Some nodes have been suspended for more than " + timeouts.nodesDown().toMinutes() + " minutes:\n" +
suspendedTooLong.asList().stream().map(node -> node.node().hostname().value()).collect(joining("\n"));
}
if (run.noNodesDownSince()
.map(since -> since.isBefore(controller.clock().instant().minus(timeouts.noNodesDown())))
.orElse(false)) {
if (summary.needPlatformUpgrade() > 0 || summary.needReboot() > 0 || summary.needRestart() > 0)
failureReason = "No nodes allowed to suspend to progress installation for " + timeouts.noNodesDown().toMinutes() + " minutes.";
else
failureReason = "Nodes not able to start with new application package.";
}
Duration timeout = JobRunner.jobTimeout.minusHours(1);
if (timedOut(id, deployment.get(), timeout)) {
failureReason = "Installation failed to complete within " + timeout.toHours() + "hours!";
}
if (failureReason != null) {
logger.log("
logger.log(nodeList.asList().stream()
.flatMap(node -> nodeDetails(node, true))
.collect(toList()));
logger.log("
logger.log(nodeList.not().in(nodeList.not().needsNewConfig()
.not().needsPlatformUpgrade()
.not().needsReboot()
.not().needsRestart()
.not().needsFirmwareUpgrade()
.not().needsOsUpgrade())
.asList().stream()
.flatMap(node -> nodeDetails(node, true))
.collect(toList()));
logger.log(INFO, failureReason);
return Optional.of(installationFailed);
}
if ( ! firstTick)
logger.log(nodeList.expectedDown().concat(nodeList.needsNewConfig()).asList().stream()
.distinct()
.flatMap(node -> nodeDetails(node, false))
.collect(toList()));
controller.jobController().locked(id, lockedRun -> {
Instant noNodesDownSince = nodeList.allowedDown().size() == 0 ? lockedRun.noNodesDownSince().orElse(controller.clock().instant()) : null;
return lockedRun.noNodesDownSince(noNodesDownSince).withSummary(summary);
});
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Run run = controller.jobController().run(id).get();
Version platform = controller.systemVersion();
ZoneId zone = id.type().zone(controller.system());
ApplicationId testerId = id.tester().id();
Optional<ServiceConvergence> services = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(testerId, zone),
Optional.of(platform));
if (services.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return run.stepInfo(installTester).get().startTime().get().isBefore(controller.clock().instant().minus(Duration.ofMinutes(5)))
? Optional.of(error)
: Optional.empty();
}
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone,
testerId,
ImmutableSet.of(active, reserved));
List<Node> parents = controller.serviceRegistry().configServer().nodeRepository().list(zone,
nodes.stream().map(node -> node.parentHostname().get()).collect(toList()));
NodeList nodeList = NodeList.of(nodes, parents, services.get());
logger.log(nodeList.asList().stream()
.flatMap(node -> nodeDetails(node, false))
.collect(toList()));
if (nodeList.summary().converged() && testerContainersAreUp(testerId, zone, logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
if (run.stepInfo(installTester).get().startTime().get().plus(timeouts.tester()).isBefore(controller.clock().instant())) {
logger.log(WARNING, "Installation of tester failed to complete within " + timeouts.tester().toMinutes() + " minutes!");
return Optional.of(error);
}
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.routing().zoneEndpointsOf(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (var endpoint : endpoints.get(zoneId)) {
boolean ready = controller.jobController().cloud().ready(endpoint.url());
if ( ! ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
/** Returns true iff all containers in the tester deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean testerContainersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
DeploymentId deploymentId = new DeploymentId(id, zoneId);
if (controller.jobController().cloud().testerReady(deploymentId)) {
return true;
} else {
logger.log("Failed to get 100 consecutive OKs from tester container for " + deploymentId);
return false;
}
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
var endpoints = controller.routing().zoneEndpointsOf(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
var policies = controller.routing().policies().get(new DeploymentId(id, zone));
for (var endpoint : endpoints.get(zone)) {
HostName endpointName = HostName.from(endpoint.dnsName());
var ipAddress = controller.jobController().cloud().resolveHostName(endpointName);
if (ipAddress.isEmpty()) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpointName + "'.");
return false;
}
if (endpoint.routingMethod() == RoutingMethod.exclusive) {
var policy = policies.get(new RoutingPolicyId(id, ClusterSpec.Id.from(endpoint.name()), zone));
if (policy == null)
throw new IllegalStateException(endpoint + " has no matching policy in " + policies);
var cNameValue = controller.jobController().cloud().resolveCname(endpointName);
if ( ! cNameValue.map(policy.canonicalName()::equals).orElse(false)) {
logger.log(INFO, "CNAME '" + endpointName + "' points at " +
cNameValue.map(name -> "'" + name + "'").orElse("nothing") +
" but should point at load balancer '" + policy.canonicalName() + "'");
return false;
}
var loadBalancerAddress = controller.jobController().cloud().resolveHostName(policy.canonicalName());
if ( ! loadBalancerAddress.equals(ipAddress)) {
logger.log(INFO, "IP address of CNAME '" + endpointName + "' (" + ipAddress.get() + ") and load balancer '" +
policy.canonicalName() + "' (" + loadBalancerAddress.orElse("empty") + ") are not equal");
return false;
}
}
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, List<Endpoint>> zoneEndpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
zoneEndpoints.forEach((zone, endpoints) -> {
messages.add("- " + zone);
for (Endpoint endpoint : endpoints)
messages.add(" |-- " + endpoint.url() + " (cluster '" + endpoint.name() + "')");
});
logger.log(messages);
}
private Stream<String> nodeDetails(NodeWithServices node, boolean printAllServices) {
return Stream.concat(Stream.of(node.node().hostname() + ": " + humanize(node.node().serviceState()) + (node.node().suspendedSince().map(since -> " since " + since).orElse("")),
"--- platform " + wantedPlatform(node.node()) + (node.needsPlatformUpgrade()
? " <-- " + currentPlatform(node.node())
: "") +
(node.needsOsUpgrade() && node.isAllowedDown()
? ", upgrading OS (" + node.node().wantedOsVersion() + " <-- " + node.node().currentOsVersion() + ")"
: "") +
(node.needsFirmwareUpgrade() && node.isAllowedDown()
? ", upgrading firmware"
: "") +
(node.needsRestart()
? ", restart pending (" + node.node().wantedRestartGeneration() + " <-- " + node.node().restartGeneration() + ")"
: "") +
(node.needsReboot()
? ", reboot pending (" + node.node().wantedRebootGeneration() + " <-- " + node.node().rebootGeneration() + ")"
: "")),
node.services().stream()
.filter(service -> printAllServices || node.needsNewConfig())
.map(service -> "--- " + service.type() + " on port " + service.port() + (service.currentGeneration() == -1
? " has not started "
: " has config generation " + service.currentGeneration() + ", wanted is " + node.wantedConfigGeneration())));
}
private String wantedPlatform(Node node) {
return node.wantedDockerImage().repository() + ":" + node.wantedVersion();
}
private String currentPlatform(Node node) {
String currentRepo = node.currentDockerImage().repository();
String wantedRepo = node.wantedDockerImage().repository();
return (currentRepo.equals(wantedRepo) ? "" : currentRepo + ":") + node.currentVersion();
}
private String humanize(Node.ServiceState state) {
switch (state) {
case allowedDown: return "allowed to be DOWN";
case expectedUp: return "expected to be UP";
case unorchestrated: return "unorchestrated";
default: return state.name();
}
}
private Optional<RunStatus> startTests(RunId id, boolean isSetup, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(error);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
ZoneId zoneId = id.type().zone(controller.system());
deployments.add(new DeploymentId(id.application(), zoneId));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.routing().zoneEndpointsOf(deployments);
if ( ! endpoints.containsKey(zoneId)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
if (!controller.jobController().cloud().testerReady(getTesterDeploymentId(id))) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
TesterCloud.Suite suite = TesterCloud.Suite.of(id.type(), isSetup);
byte[] config = testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments));
controller.jobController().cloud().startTests(getTesterDeploymentId(id), suite, config);
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isEmpty()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(getTesterDeploymentId(id));
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return Optional.of(running);
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
Instant startTime = controller.jobController().run(id).get().stepInfo(deactivateReal).get().startTime().get();
return startTime.isBefore(controller.clock().instant().minus(Duration.ofHours(1)))
? Optional.of(error)
: Optional.empty();
}
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return Optional.of(running);
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
Instant startTime = controller.jobController().run(id).get().stepInfo(deactivateTester).get().startTime().get();
return startTime.isBefore(controller.clock().instant().minus(Duration.ofHours(1)))
? Optional.of(error)
: Optional.empty();
}
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.require(run.id().application().instance()).change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
logger.log(INFO, "Sending failure notification to " + String.join(", ", recipients));
mailOf(run, recipients).ifPresent(controller.serviceRegistry().mailer()::send);
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
private Optional<Mail> mailOf(Run run, List<String> recipients) {
switch (run.status()) {
case running:
case aborted:
case success:
return Optional.empty();
case outOfCapacity:
return run.id().type().isProduction() ? Optional.of(mails.outOfCapacity(run.id(), recipients)) : Optional.empty();
case deploymentFailed:
return Optional.of(mails.deploymentFailure(run.id(), recipients));
case installationFailed:
return Optional.of(mails.installationFailure(run.id(), recipients));
case testFailure:
return Optional.of(mails.testFailure(run.id(), recipients));
case error:
case endpointCertificateTimeout:
return Optional.of(mails.systemError(run.id(), recipients));
default:
logger.log(WARNING, "Don't know what mail to send for run status '" + run.status() + "'");
return Optional.of(mails.systemError(run.id(), recipients));
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zones where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if ( ! controller.system().isCd() && run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().environment().isTest();
byte[] servicesXml = servicesXml(! controller.system().isPublic(),
useTesterCertificate,
testerResourcesFor(zone, spec.requireInstance(id.application().instance())));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(timeouts.testerCertificate()),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private DeploymentId getTesterDeploymentId(RunId runId) {
ZoneId zoneId = runId.type().zone(controller.system());
return new DeploymentId(runId.tester().id(), zoneId);
}
static NodeResources testerResourcesFor(ZoneId zone, DeploymentInstanceSpec spec) {
return spec.steps().stream()
.filter(step -> step.concerns(zone.environment()))
.findFirst()
.flatMap(step -> step.zones().get(0).testerFlavor())
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES);
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(boolean systemUsesAthenz, boolean useTesterCertificate, NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + systemUsesAthenz + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void logAll(List<LogEntry> messages) {
controller.jobController().log(id, step, messages);
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
static class Timeouts {
private final SystemName system;
private Timeouts(SystemName system) {
this.system = requireNonNull(system);
}
public static Timeouts of(SystemName system) {
return new Timeouts(system);
}
Duration capacity() { return Duration.ofMinutes(system.isCd() ? 5 : 0); }
Duration endpoint() { return Duration.ofMinutes(15); }
Duration endpointCertificate() { return Duration.ofMinutes(20); }
Duration tester() { return Duration.ofMinutes(30); }
Duration nodesDown() { return Duration.ofMinutes(system.isCd() ? 30 : 60); }
Duration noNodesDown() { return Duration.ofMinutes(system.isCd() ? 30 : 120); }
Duration testerCertificate() { return Duration.ofMinutes(300); }
}
} |
Sounds like a pragmatic solution to me | private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version targetPlatform = controller.jobController().run(id).get().versions().targetPlatform();
final Version platform = targetPlatform.equals(Version.fromString("7.220.14"))
? targetPlatform
: controller.systemVersion();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
platform),
controller.jobController().run(id).get()
.stepInfo(deployTester).get()
.startTime().get(),
logger);
} | final Version platform = targetPlatform.equals(Version.fromString("7.220.14")) | private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version targetPlatform = controller.jobController().run(id).get().versions().targetPlatform();
final Version platform = targetPlatform.equals(Version.fromString("7.220.14"))
? targetPlatform
: controller.systemVersion();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
platform),
controller.jobController().run(id).get()
.stepInfo(deployTester).get()
.startTime().get(),
logger);
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
private final Timeouts timeouts;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
this.timeouts = Timeouts.of(controller.system());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startStagingSetup: return startTests(id, true, logger);
case endStagingSetup:
case endTests: return endTests(id, logger);
case startTests: return startTests(id, false, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (step.get().alwaysRun()) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, DualLogger logger) {
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy2(id.job(), setTheStage),
controller.jobController().run(id).get()
.stepInfo(setTheStage ? deployInitialReal : deployReal).get()
.startTime().get(),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment,
Instant startTime, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if (prepareResponse.log != null)
logger.logAll(prepareResponse.log.stream()
.map(entry -> new LogEntry(0,
Instant.ofEpochMilli(entry.time),
LogEntry.typeOf(LogLevel.parse(entry.level)),
entry.message))
.collect(toList()));
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Schedule service restart on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
Optional<RunStatus> result = startTime.isBefore(controller.clock().instant().minus(Duration.ofHours(1)))
? Optional.of(deploymentFailed) : Optional.empty();
switch (e.getErrorCode()) {
case CERTIFICATE_NOT_READY:
if (startTime.plus(timeouts.endpointCertificate()).isBefore(controller.clock().instant())) {
logger.log("Deployment failed to find provisioned endpoint certificate after " + timeouts.endpointCertificate());
return Optional.of(RunStatus.endpointCertificateTimeout);
}
return result;
case ACTIVATION_CONFLICT:
case APPLICATION_LOCK_FAILURE:
logger.log("Deployment failed with possibly transient error " + e.getErrorCode() +
", will retry: " + e.getMessage());
return result;
case LOAD_BALANCER_NOT_READY:
case PARENT_HOST_NOT_READY:
logger.log(e.getServerMessage());
return result;
case OUT_OF_CAPACITY:
logger.log(e.getServerMessage());
return controller.system().isCd() && startTime.plus(timeouts.capacity()).isAfter(controller.clock().instant())
? Optional.empty()
: Optional.of(outOfCapacity);
case INVALID_APPLICATION_PACKAGE:
case BAD_REQUEST:
logger.log(e.getMessage());
return Optional.of(deploymentFailed);
}
throw e;
}
catch (EndpointCertificateException e) {
switch (e.type()) {
case CERT_NOT_AVAILABLE:
if (startTime.plus(timeouts.endpointCertificate()).isBefore(controller.clock().instant())) {
logger.log("Deployment failed to find provisioned endpoint certificate after " + timeouts.endpointCertificate());
return Optional.of(RunStatus.endpointCertificateTimeout);
}
return Optional.empty();
default:
throw e;
}
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
Run run = controller.jobController().run(id).get();
Optional<ServiceConvergence> services = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id.application(), id.type().zone(controller.system())),
Optional.of(platform));
if (services.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return Optional.empty();
}
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(id.type().zone(controller.system()),
id.application(),
ImmutableSet.of(active, reserved));
List<Node> parents = controller.serviceRegistry().configServer().nodeRepository().list(id.type().zone(controller.system()),
nodes.stream().map(node -> node.parentHostname().get()).collect(toList()));
NodeList nodeList = NodeList.of(nodes, parents, services.get());
boolean firstTick = run.convergenceSummary().isEmpty();
if (firstTick) {
logger.log("
logger.log(nodeList.asList().stream()
.flatMap(node -> nodeDetails(node, true))
.collect(toList()));
}
ConvergenceSummary summary = nodeList.summary();
if (summary.converged()) {
controller.jobController().locked(id, lockedRun -> lockedRun.withSummary(null));
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), timeouts.endpoint())) {
logger.log(WARNING, "Endpoints failed to show up within " + timeouts.endpoint().toMinutes() + " minutes!");
return Optional.of(error);
}
}
String failureReason = null;
NodeList suspendedTooLong = nodeList.suspendedSince(controller.clock().instant().minus(timeouts.nodesDown()));
if ( ! suspendedTooLong.isEmpty()) {
failureReason = "Some nodes have been suspended for more than " + timeouts.nodesDown().toMinutes() + " minutes:\n" +
suspendedTooLong.asList().stream().map(node -> node.node().hostname().value()).collect(joining("\n"));
}
if (run.noNodesDownSince()
.map(since -> since.isBefore(controller.clock().instant().minus(timeouts.noNodesDown())))
.orElse(false)) {
if (summary.needPlatformUpgrade() > 0 || summary.needReboot() > 0 || summary.needRestart() > 0)
failureReason = "No nodes allowed to suspend to progress installation for " + timeouts.noNodesDown().toMinutes() + " minutes.";
else
failureReason = "Nodes not able to start with new application package.";
}
Duration timeout = JobRunner.jobTimeout.minusHours(1);
if (timedOut(id, deployment.get(), timeout)) {
failureReason = "Installation failed to complete within " + timeout.toHours() + "hours!";
}
if (failureReason != null) {
logger.log("
logger.log(nodeList.asList().stream()
.flatMap(node -> nodeDetails(node, true))
.collect(toList()));
logger.log("
logger.log(nodeList.not().in(nodeList.not().needsNewConfig()
.not().needsPlatformUpgrade()
.not().needsReboot()
.not().needsRestart()
.not().needsFirmwareUpgrade()
.not().needsOsUpgrade())
.asList().stream()
.flatMap(node -> nodeDetails(node, true))
.collect(toList()));
logger.log(INFO, failureReason);
return Optional.of(installationFailed);
}
if ( ! firstTick)
logger.log(nodeList.expectedDown().concat(nodeList.needsNewConfig()).asList().stream()
.distinct()
.flatMap(node -> nodeDetails(node, false))
.collect(toList()));
controller.jobController().locked(id, lockedRun -> {
Instant noNodesDownSince = nodeList.allowedDown().size() == 0 ? lockedRun.noNodesDownSince().orElse(controller.clock().instant()) : null;
return lockedRun.noNodesDownSince(noNodesDownSince).withSummary(summary);
});
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Run run = controller.jobController().run(id).get();
Version platform = controller.systemVersion();
ZoneId zone = id.type().zone(controller.system());
ApplicationId testerId = id.tester().id();
Optional<ServiceConvergence> services = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(testerId, zone),
Optional.of(platform));
if (services.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return run.stepInfo(installTester).get().startTime().get().isBefore(controller.clock().instant().minus(Duration.ofMinutes(5)))
? Optional.of(error)
: Optional.empty();
}
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone,
testerId,
ImmutableSet.of(active, reserved));
List<Node> parents = controller.serviceRegistry().configServer().nodeRepository().list(zone,
nodes.stream().map(node -> node.parentHostname().get()).collect(toList()));
NodeList nodeList = NodeList.of(nodes, parents, services.get());
logger.log(nodeList.asList().stream()
.flatMap(node -> nodeDetails(node, false))
.collect(toList()));
if (nodeList.summary().converged() && testerContainersAreUp(testerId, zone, logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
if (run.stepInfo(installTester).get().startTime().get().plus(timeouts.tester()).isBefore(controller.clock().instant())) {
logger.log(WARNING, "Installation of tester failed to complete within " + timeouts.tester().toMinutes() + " minutes!");
return Optional.of(error);
}
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.routing().zoneEndpointsOf(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (var endpoint : endpoints.get(zoneId)) {
boolean ready = controller.jobController().cloud().ready(endpoint.url());
if ( ! ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
/** Returns true iff all containers in the tester deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean testerContainersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
DeploymentId deploymentId = new DeploymentId(id, zoneId);
if (controller.jobController().cloud().testerReady(deploymentId)) {
return true;
} else {
logger.log("Failed to get 100 consecutive OKs from tester container for " + deploymentId);
return false;
}
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
var endpoints = controller.routing().zoneEndpointsOf(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
var policies = controller.routing().policies().get(new DeploymentId(id, zone));
for (var endpoint : endpoints.get(zone)) {
HostName endpointName = HostName.from(endpoint.dnsName());
var ipAddress = controller.jobController().cloud().resolveHostName(endpointName);
if (ipAddress.isEmpty()) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpointName + "'.");
return false;
}
if (endpoint.routingMethod() == RoutingMethod.exclusive) {
var policy = policies.get(new RoutingPolicyId(id, ClusterSpec.Id.from(endpoint.name()), zone));
if (policy == null)
throw new IllegalStateException(endpoint + " has no matching policy in " + policies);
var cNameValue = controller.jobController().cloud().resolveCname(endpointName);
if ( ! cNameValue.map(policy.canonicalName()::equals).orElse(false)) {
logger.log(INFO, "CNAME '" + endpointName + "' points at " +
cNameValue.map(name -> "'" + name + "'").orElse("nothing") +
" but should point at load balancer '" + policy.canonicalName() + "'");
return false;
}
var loadBalancerAddress = controller.jobController().cloud().resolveHostName(policy.canonicalName());
if ( ! loadBalancerAddress.equals(ipAddress)) {
logger.log(INFO, "IP address of CNAME '" + endpointName + "' (" + ipAddress.get() + ") and load balancer '" +
policy.canonicalName() + "' (" + loadBalancerAddress.orElse("empty") + ") are not equal");
return false;
}
}
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, List<Endpoint>> zoneEndpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
zoneEndpoints.forEach((zone, endpoints) -> {
messages.add("- " + zone);
for (Endpoint endpoint : endpoints)
messages.add(" |-- " + endpoint.url() + " (cluster '" + endpoint.name() + "')");
});
logger.log(messages);
}
private Stream<String> nodeDetails(NodeWithServices node, boolean printAllServices) {
return Stream.concat(Stream.of(node.node().hostname() + ": " + humanize(node.node().serviceState()) + (node.node().suspendedSince().map(since -> " since " + since).orElse("")),
"--- platform " + wantedPlatform(node.node()) + (node.needsPlatformUpgrade()
? " <-- " + currentPlatform(node.node())
: "") +
(node.needsOsUpgrade() && node.isAllowedDown()
? ", upgrading OS (" + node.node().wantedOsVersion() + " <-- " + node.node().currentOsVersion() + ")"
: "") +
(node.needsFirmwareUpgrade() && node.isAllowedDown()
? ", upgrading firmware"
: "") +
(node.needsRestart()
? ", restart pending (" + node.node().wantedRestartGeneration() + " <-- " + node.node().restartGeneration() + ")"
: "") +
(node.needsReboot()
? ", reboot pending (" + node.node().wantedRebootGeneration() + " <-- " + node.node().rebootGeneration() + ")"
: "")),
node.services().stream()
.filter(service -> printAllServices || node.needsNewConfig())
.map(service -> "--- " + service.type() + " on port " + service.port() + (service.currentGeneration() == -1
? " has not started "
: " has config generation " + service.currentGeneration() + ", wanted is " + node.wantedConfigGeneration())));
}
private String wantedPlatform(Node node) {
return node.wantedDockerImage().repository() + ":" + node.wantedVersion();
}
private String currentPlatform(Node node) {
String currentRepo = node.currentDockerImage().repository();
String wantedRepo = node.wantedDockerImage().repository();
return (currentRepo.equals(wantedRepo) ? "" : currentRepo + ":") + node.currentVersion();
}
private String humanize(Node.ServiceState state) {
switch (state) {
case allowedDown: return "allowed to be DOWN";
case expectedUp: return "expected to be UP";
case unorchestrated: return "unorchestrated";
default: return state.name();
}
}
private Optional<RunStatus> startTests(RunId id, boolean isSetup, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(error);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
ZoneId zoneId = id.type().zone(controller.system());
deployments.add(new DeploymentId(id.application(), zoneId));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.routing().zoneEndpointsOf(deployments);
if ( ! endpoints.containsKey(zoneId)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
if (!controller.jobController().cloud().testerReady(getTesterDeploymentId(id))) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
TesterCloud.Suite suite = TesterCloud.Suite.of(id.type(), isSetup);
byte[] config = testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments));
controller.jobController().cloud().startTests(getTesterDeploymentId(id), suite, config);
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isEmpty()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(getTesterDeploymentId(id));
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return Optional.of(running);
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
Instant startTime = controller.jobController().run(id).get().stepInfo(deactivateReal).get().startTime().get();
return startTime.isBefore(controller.clock().instant().minus(Duration.ofHours(1)))
? Optional.of(error)
: Optional.empty();
}
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return Optional.of(running);
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
Instant startTime = controller.jobController().run(id).get().stepInfo(deactivateTester).get().startTime().get();
return startTime.isBefore(controller.clock().instant().minus(Duration.ofHours(1)))
? Optional.of(error)
: Optional.empty();
}
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.require(run.id().application().instance()).change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
logger.log(INFO, "Sending failure notification to " + String.join(", ", recipients));
mailOf(run, recipients).ifPresent(controller.serviceRegistry().mailer()::send);
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
private Optional<Mail> mailOf(Run run, List<String> recipients) {
switch (run.status()) {
case running:
case aborted:
case success:
return Optional.empty();
case outOfCapacity:
return run.id().type().isProduction() ? Optional.of(mails.outOfCapacity(run.id(), recipients)) : Optional.empty();
case deploymentFailed:
return Optional.of(mails.deploymentFailure(run.id(), recipients));
case installationFailed:
return Optional.of(mails.installationFailure(run.id(), recipients));
case testFailure:
return Optional.of(mails.testFailure(run.id(), recipients));
case error:
case endpointCertificateTimeout:
return Optional.of(mails.systemError(run.id(), recipients));
default:
logger.log(WARNING, "Don't know what mail to send for run status '" + run.status() + "'");
return Optional.of(mails.systemError(run.id(), recipients));
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zones where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if ( ! controller.system().isCd() && run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().environment().isTest();
byte[] servicesXml = servicesXml(! controller.system().isPublic(),
useTesterCertificate,
testerResourcesFor(zone, spec.requireInstance(id.application().instance())));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(timeouts.testerCertificate()),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private DeploymentId getTesterDeploymentId(RunId runId) {
ZoneId zoneId = runId.type().zone(controller.system());
return new DeploymentId(runId.tester().id(), zoneId);
}
static NodeResources testerResourcesFor(ZoneId zone, DeploymentInstanceSpec spec) {
return spec.steps().stream()
.filter(step -> step.concerns(zone.environment()))
.findFirst()
.flatMap(step -> step.zones().get(0).testerFlavor())
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES);
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(boolean systemUsesAthenz, boolean useTesterCertificate, NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + systemUsesAthenz + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void logAll(List<LogEntry> messages) {
controller.jobController().log(id, step, messages);
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
static class Timeouts {
private final SystemName system;
private Timeouts(SystemName system) {
this.system = requireNonNull(system);
}
public static Timeouts of(SystemName system) {
return new Timeouts(system);
}
Duration capacity() { return Duration.ofMinutes(system.isCd() ? 5 : 0); }
Duration endpoint() { return Duration.ofMinutes(15); }
Duration endpointCertificate() { return Duration.ofMinutes(20); }
Duration tester() { return Duration.ofMinutes(30); }
Duration nodesDown() { return Duration.ofMinutes(system.isCd() ? 30 : 60); }
Duration noNodesDown() { return Duration.ofMinutes(system.isCd() ? 30 : 120); }
Duration testerCertificate() { return Duration.ofMinutes(300); }
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
private final Timeouts timeouts;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
this.timeouts = Timeouts.of(controller.system());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startStagingSetup: return startTests(id, true, logger);
case endStagingSetup:
case endTests: return endTests(id, logger);
case startTests: return startTests(id, false, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (step.get().alwaysRun()) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, DualLogger logger) {
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy2(id.job(), setTheStage),
controller.jobController().run(id).get()
.stepInfo(setTheStage ? deployInitialReal : deployReal).get()
.startTime().get(),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment,
Instant startTime, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if (prepareResponse.log != null)
logger.logAll(prepareResponse.log.stream()
.map(entry -> new LogEntry(0,
Instant.ofEpochMilli(entry.time),
LogEntry.typeOf(LogLevel.parse(entry.level)),
entry.message))
.collect(toList()));
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Schedule service restart on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
Optional<RunStatus> result = startTime.isBefore(controller.clock().instant().minus(Duration.ofHours(1)))
? Optional.of(deploymentFailed) : Optional.empty();
switch (e.getErrorCode()) {
case CERTIFICATE_NOT_READY:
if (startTime.plus(timeouts.endpointCertificate()).isBefore(controller.clock().instant())) {
logger.log("Deployment failed to find provisioned endpoint certificate after " + timeouts.endpointCertificate());
return Optional.of(RunStatus.endpointCertificateTimeout);
}
return result;
case ACTIVATION_CONFLICT:
case APPLICATION_LOCK_FAILURE:
logger.log("Deployment failed with possibly transient error " + e.getErrorCode() +
", will retry: " + e.getMessage());
return result;
case LOAD_BALANCER_NOT_READY:
case PARENT_HOST_NOT_READY:
logger.log(e.getServerMessage());
return result;
case OUT_OF_CAPACITY:
logger.log(e.getServerMessage());
return controller.system().isCd() && startTime.plus(timeouts.capacity()).isAfter(controller.clock().instant())
? Optional.empty()
: Optional.of(outOfCapacity);
case INVALID_APPLICATION_PACKAGE:
case BAD_REQUEST:
logger.log(e.getMessage());
return Optional.of(deploymentFailed);
}
throw e;
}
catch (EndpointCertificateException e) {
switch (e.type()) {
case CERT_NOT_AVAILABLE:
if (startTime.plus(timeouts.endpointCertificate()).isBefore(controller.clock().instant())) {
logger.log("Deployment failed to find provisioned endpoint certificate after " + timeouts.endpointCertificate());
return Optional.of(RunStatus.endpointCertificateTimeout);
}
return Optional.empty();
default:
throw e;
}
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
Run run = controller.jobController().run(id).get();
Optional<ServiceConvergence> services = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id.application(), id.type().zone(controller.system())),
Optional.of(platform));
if (services.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return Optional.empty();
}
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(id.type().zone(controller.system()),
id.application(),
ImmutableSet.of(active, reserved));
List<Node> parents = controller.serviceRegistry().configServer().nodeRepository().list(id.type().zone(controller.system()),
nodes.stream().map(node -> node.parentHostname().get()).collect(toList()));
NodeList nodeList = NodeList.of(nodes, parents, services.get());
boolean firstTick = run.convergenceSummary().isEmpty();
if (firstTick) {
logger.log("
logger.log(nodeList.asList().stream()
.flatMap(node -> nodeDetails(node, true))
.collect(toList()));
}
ConvergenceSummary summary = nodeList.summary();
if (summary.converged()) {
controller.jobController().locked(id, lockedRun -> lockedRun.withSummary(null));
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), timeouts.endpoint())) {
logger.log(WARNING, "Endpoints failed to show up within " + timeouts.endpoint().toMinutes() + " minutes!");
return Optional.of(error);
}
}
String failureReason = null;
NodeList suspendedTooLong = nodeList.suspendedSince(controller.clock().instant().minus(timeouts.nodesDown()));
if ( ! suspendedTooLong.isEmpty()) {
failureReason = "Some nodes have been suspended for more than " + timeouts.nodesDown().toMinutes() + " minutes:\n" +
suspendedTooLong.asList().stream().map(node -> node.node().hostname().value()).collect(joining("\n"));
}
if (run.noNodesDownSince()
.map(since -> since.isBefore(controller.clock().instant().minus(timeouts.noNodesDown())))
.orElse(false)) {
if (summary.needPlatformUpgrade() > 0 || summary.needReboot() > 0 || summary.needRestart() > 0)
failureReason = "No nodes allowed to suspend to progress installation for " + timeouts.noNodesDown().toMinutes() + " minutes.";
else
failureReason = "Nodes not able to start with new application package.";
}
Duration timeout = JobRunner.jobTimeout.minusHours(1);
if (timedOut(id, deployment.get(), timeout)) {
failureReason = "Installation failed to complete within " + timeout.toHours() + "hours!";
}
if (failureReason != null) {
logger.log("
logger.log(nodeList.asList().stream()
.flatMap(node -> nodeDetails(node, true))
.collect(toList()));
logger.log("
logger.log(nodeList.not().in(nodeList.not().needsNewConfig()
.not().needsPlatformUpgrade()
.not().needsReboot()
.not().needsRestart()
.not().needsFirmwareUpgrade()
.not().needsOsUpgrade())
.asList().stream()
.flatMap(node -> nodeDetails(node, true))
.collect(toList()));
logger.log(INFO, failureReason);
return Optional.of(installationFailed);
}
if ( ! firstTick)
logger.log(nodeList.expectedDown().concat(nodeList.needsNewConfig()).asList().stream()
.distinct()
.flatMap(node -> nodeDetails(node, false))
.collect(toList()));
controller.jobController().locked(id, lockedRun -> {
Instant noNodesDownSince = nodeList.allowedDown().size() == 0 ? lockedRun.noNodesDownSince().orElse(controller.clock().instant()) : null;
return lockedRun.noNodesDownSince(noNodesDownSince).withSummary(summary);
});
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Run run = controller.jobController().run(id).get();
Version platform = controller.systemVersion();
ZoneId zone = id.type().zone(controller.system());
ApplicationId testerId = id.tester().id();
Optional<ServiceConvergence> services = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(testerId, zone),
Optional.of(platform));
if (services.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return run.stepInfo(installTester).get().startTime().get().isBefore(controller.clock().instant().minus(Duration.ofMinutes(5)))
? Optional.of(error)
: Optional.empty();
}
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone,
testerId,
ImmutableSet.of(active, reserved));
List<Node> parents = controller.serviceRegistry().configServer().nodeRepository().list(zone,
nodes.stream().map(node -> node.parentHostname().get()).collect(toList()));
NodeList nodeList = NodeList.of(nodes, parents, services.get());
logger.log(nodeList.asList().stream()
.flatMap(node -> nodeDetails(node, false))
.collect(toList()));
if (nodeList.summary().converged() && testerContainersAreUp(testerId, zone, logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
if (run.stepInfo(installTester).get().startTime().get().plus(timeouts.tester()).isBefore(controller.clock().instant())) {
logger.log(WARNING, "Installation of tester failed to complete within " + timeouts.tester().toMinutes() + " minutes!");
return Optional.of(error);
}
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.routing().zoneEndpointsOf(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (var endpoint : endpoints.get(zoneId)) {
boolean ready = controller.jobController().cloud().ready(endpoint.url());
if ( ! ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
/** Returns true iff all containers in the tester deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean testerContainersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
DeploymentId deploymentId = new DeploymentId(id, zoneId);
if (controller.jobController().cloud().testerReady(deploymentId)) {
return true;
} else {
logger.log("Failed to get 100 consecutive OKs from tester container for " + deploymentId);
return false;
}
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
var endpoints = controller.routing().zoneEndpointsOf(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
var policies = controller.routing().policies().get(new DeploymentId(id, zone));
for (var endpoint : endpoints.get(zone)) {
HostName endpointName = HostName.from(endpoint.dnsName());
var ipAddress = controller.jobController().cloud().resolveHostName(endpointName);
if (ipAddress.isEmpty()) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpointName + "'.");
return false;
}
if (endpoint.routingMethod() == RoutingMethod.exclusive) {
var policy = policies.get(new RoutingPolicyId(id, ClusterSpec.Id.from(endpoint.name()), zone));
if (policy == null)
throw new IllegalStateException(endpoint + " has no matching policy in " + policies);
var cNameValue = controller.jobController().cloud().resolveCname(endpointName);
if ( ! cNameValue.map(policy.canonicalName()::equals).orElse(false)) {
logger.log(INFO, "CNAME '" + endpointName + "' points at " +
cNameValue.map(name -> "'" + name + "'").orElse("nothing") +
" but should point at load balancer '" + policy.canonicalName() + "'");
return false;
}
var loadBalancerAddress = controller.jobController().cloud().resolveHostName(policy.canonicalName());
if ( ! loadBalancerAddress.equals(ipAddress)) {
logger.log(INFO, "IP address of CNAME '" + endpointName + "' (" + ipAddress.get() + ") and load balancer '" +
policy.canonicalName() + "' (" + loadBalancerAddress.orElse("empty") + ") are not equal");
return false;
}
}
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, List<Endpoint>> zoneEndpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
zoneEndpoints.forEach((zone, endpoints) -> {
messages.add("- " + zone);
for (Endpoint endpoint : endpoints)
messages.add(" |-- " + endpoint.url() + " (cluster '" + endpoint.name() + "')");
});
logger.log(messages);
}
private Stream<String> nodeDetails(NodeWithServices node, boolean printAllServices) {
return Stream.concat(Stream.of(node.node().hostname() + ": " + humanize(node.node().serviceState()) + (node.node().suspendedSince().map(since -> " since " + since).orElse("")),
"--- platform " + wantedPlatform(node.node()) + (node.needsPlatformUpgrade()
? " <-- " + currentPlatform(node.node())
: "") +
(node.needsOsUpgrade() && node.isAllowedDown()
? ", upgrading OS (" + node.node().wantedOsVersion() + " <-- " + node.node().currentOsVersion() + ")"
: "") +
(node.needsFirmwareUpgrade() && node.isAllowedDown()
? ", upgrading firmware"
: "") +
(node.needsRestart()
? ", restart pending (" + node.node().wantedRestartGeneration() + " <-- " + node.node().restartGeneration() + ")"
: "") +
(node.needsReboot()
? ", reboot pending (" + node.node().wantedRebootGeneration() + " <-- " + node.node().rebootGeneration() + ")"
: "")),
node.services().stream()
.filter(service -> printAllServices || node.needsNewConfig())
.map(service -> "--- " + service.type() + " on port " + service.port() + (service.currentGeneration() == -1
? " has not started "
: " has config generation " + service.currentGeneration() + ", wanted is " + node.wantedConfigGeneration())));
}
private String wantedPlatform(Node node) {
return node.wantedDockerImage().repository() + ":" + node.wantedVersion();
}
private String currentPlatform(Node node) {
String currentRepo = node.currentDockerImage().repository();
String wantedRepo = node.wantedDockerImage().repository();
return (currentRepo.equals(wantedRepo) ? "" : currentRepo + ":") + node.currentVersion();
}
private String humanize(Node.ServiceState state) {
switch (state) {
case allowedDown: return "allowed to be DOWN";
case expectedUp: return "expected to be UP";
case unorchestrated: return "unorchestrated";
default: return state.name();
}
}
private Optional<RunStatus> startTests(RunId id, boolean isSetup, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(error);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
ZoneId zoneId = id.type().zone(controller.system());
deployments.add(new DeploymentId(id.application(), zoneId));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.routing().zoneEndpointsOf(deployments);
if ( ! endpoints.containsKey(zoneId)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
if (!controller.jobController().cloud().testerReady(getTesterDeploymentId(id))) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
TesterCloud.Suite suite = TesterCloud.Suite.of(id.type(), isSetup);
byte[] config = testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments));
controller.jobController().cloud().startTests(getTesterDeploymentId(id), suite, config);
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isEmpty()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(getTesterDeploymentId(id));
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return Optional.of(running);
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
Instant startTime = controller.jobController().run(id).get().stepInfo(deactivateReal).get().startTime().get();
return startTime.isBefore(controller.clock().instant().minus(Duration.ofHours(1)))
? Optional.of(error)
: Optional.empty();
}
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return Optional.of(running);
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
Instant startTime = controller.jobController().run(id).get().stepInfo(deactivateTester).get().startTime().get();
return startTime.isBefore(controller.clock().instant().minus(Duration.ofHours(1)))
? Optional.of(error)
: Optional.empty();
}
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.require(run.id().application().instance()).change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
logger.log(INFO, "Sending failure notification to " + String.join(", ", recipients));
mailOf(run, recipients).ifPresent(controller.serviceRegistry().mailer()::send);
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
private Optional<Mail> mailOf(Run run, List<String> recipients) {
switch (run.status()) {
case running:
case aborted:
case success:
return Optional.empty();
case outOfCapacity:
return run.id().type().isProduction() ? Optional.of(mails.outOfCapacity(run.id(), recipients)) : Optional.empty();
case deploymentFailed:
return Optional.of(mails.deploymentFailure(run.id(), recipients));
case installationFailed:
return Optional.of(mails.installationFailure(run.id(), recipients));
case testFailure:
return Optional.of(mails.testFailure(run.id(), recipients));
case error:
case endpointCertificateTimeout:
return Optional.of(mails.systemError(run.id(), recipients));
default:
logger.log(WARNING, "Don't know what mail to send for run status '" + run.status() + "'");
return Optional.of(mails.systemError(run.id(), recipients));
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zones where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if ( ! controller.system().isCd() && run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().environment().isTest();
byte[] servicesXml = servicesXml(! controller.system().isPublic(),
useTesterCertificate,
testerResourcesFor(zone, spec.requireInstance(id.application().instance())));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(timeouts.testerCertificate()),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private DeploymentId getTesterDeploymentId(RunId runId) {
ZoneId zoneId = runId.type().zone(controller.system());
return new DeploymentId(runId.tester().id(), zoneId);
}
static NodeResources testerResourcesFor(ZoneId zone, DeploymentInstanceSpec spec) {
return spec.steps().stream()
.filter(step -> step.concerns(zone.environment()))
.findFirst()
.flatMap(step -> step.zones().get(0).testerFlavor())
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES);
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(boolean systemUsesAthenz, boolean useTesterCertificate, NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + systemUsesAthenz + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void logAll(List<LogEntry> messages) {
controller.jobController().log(id, step, messages);
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
static class Timeouts {
private final SystemName system;
private Timeouts(SystemName system) {
this.system = requireNonNull(system);
}
public static Timeouts of(SystemName system) {
return new Timeouts(system);
}
Duration capacity() { return Duration.ofMinutes(system.isCd() ? 5 : 0); }
Duration endpoint() { return Duration.ofMinutes(15); }
Duration endpointCertificate() { return Duration.ofMinutes(20); }
Duration tester() { return Duration.ofMinutes(30); }
Duration nodesDown() { return Duration.ofMinutes(system.isCd() ? 30 : 60); }
Duration noNodesDown() { return Duration.ofMinutes(system.isCd() ? 30 : 120); }
Duration testerCertificate() { return Duration.ofMinutes(300); }
}
} |
This meant that if NA spent >1 HA tick, the context it eventually picked up on its next NA tick was >1 HA tick old? | public NodeAgentContext nextContext() throws InterruptedException {
synchronized (monitor) {
nextContext = null;
Duration untilNextContext = Duration.ZERO;
while (setAndGetIsFrozen(wantFrozen) ||
nextContext == null ||
(untilNextContext = Duration.between(Instant.now(), nextContextAt)).toMillis() > 0) {
if (pendingInterrupt) {
pendingInterrupt = false;
throw new InterruptedException("interrupt() was called before next context was scheduled");
}
try {
monitor.wait(Math.max(untilNextContext.toMillis(), 0L));
} catch (InterruptedException ignored) { }
}
currentContext = nextContext;
return currentContext;
}
} | currentContext = nextContext; | public NodeAgentContext nextContext() throws InterruptedException {
synchronized (monitor) {
nextContext = null;
Duration untilNextContext = Duration.ZERO;
while (setAndGetIsFrozen(wantFrozen) ||
nextContext == null ||
(untilNextContext = Duration.between(Instant.now(), nextContextAt)).toMillis() > 0) {
if (pendingInterrupt) {
pendingInterrupt = false;
throw new InterruptedException("interrupt() was called before next context was scheduled");
}
try {
monitor.wait(Math.max(untilNextContext.toMillis(), 0L));
} catch (InterruptedException ignored) { }
}
currentContext = nextContext;
return currentContext;
}
} | class NodeAgentContextManager implements NodeAgentContextSupplier, NodeAgentScheduler {
private final Object monitor = new Object();
private final Clock clock;
private NodeAgentContext currentContext;
private NodeAgentContext nextContext;
private Instant nextContextAt;
private boolean wantFrozen = false;
private boolean isFrozen = true;
private boolean pendingInterrupt = false;
public NodeAgentContextManager(Clock clock, NodeAgentContext context) {
this.clock = clock;
this.currentContext = context;
}
@Override
public void scheduleTickWith(NodeAgentContext context, Instant at) {
synchronized (monitor) {
nextContext = Objects.requireNonNull(context);
nextContextAt = Objects.requireNonNull(at);
monitor.notifyAll();
}
}
@Override
public boolean setFrozen(boolean frozen, Duration timeout) {
synchronized (monitor) {
if (wantFrozen != frozen) {
wantFrozen = frozen;
monitor.notifyAll();
}
boolean successful;
long remainder;
long end = clock.instant().plus(timeout).toEpochMilli();
while (!(successful = isFrozen == frozen) && (remainder = end - clock.millis()) > 0) {
try {
monitor.wait(remainder);
} catch (InterruptedException ignored) { }
}
return successful;
}
}
@Override
@Override
public NodeAgentContext currentContext() {
synchronized (monitor) {
return currentContext;
}
}
@Override
public void interrupt() {
synchronized (monitor) {
pendingInterrupt = true;
monitor.notifyAll();
}
}
private boolean setAndGetIsFrozen(boolean isFrozen) {
synchronized (monitor) {
if (this.isFrozen != isFrozen) {
this.isFrozen = isFrozen;
monitor.notifyAll();
}
return this.isFrozen;
}
}
} | class NodeAgentContextManager implements NodeAgentContextSupplier, NodeAgentScheduler {
private final Object monitor = new Object();
private final Clock clock;
private NodeAgentContext currentContext;
private NodeAgentContext nextContext;
private Instant nextContextAt;
private boolean wantFrozen = false;
private boolean isFrozen = true;
private boolean pendingInterrupt = false;
public NodeAgentContextManager(Clock clock, NodeAgentContext context) {
this.clock = clock;
this.currentContext = context;
}
@Override
public void scheduleTickWith(NodeAgentContext context, Instant at) {
synchronized (monitor) {
nextContext = Objects.requireNonNull(context);
nextContextAt = Objects.requireNonNull(at);
monitor.notifyAll();
}
}
@Override
public boolean setFrozen(boolean frozen, Duration timeout) {
synchronized (monitor) {
if (wantFrozen != frozen) {
wantFrozen = frozen;
monitor.notifyAll();
}
boolean successful;
long remainder;
long end = clock.instant().plus(timeout).toEpochMilli();
while (!(successful = isFrozen == frozen) && (remainder = end - clock.millis()) > 0) {
try {
monitor.wait(remainder);
} catch (InterruptedException ignored) { }
}
return successful;
}
}
@Override
@Override
public NodeAgentContext currentContext() {
synchronized (monitor) {
return currentContext;
}
}
@Override
public void interrupt() {
synchronized (monitor) {
pendingInterrupt = true;
monitor.notifyAll();
}
}
private boolean setAndGetIsFrozen(boolean isFrozen) {
synchronized (monitor) {
if (this.isFrozen != isFrozen) {
this.isFrozen = isFrozen;
monitor.notifyAll();
}
return this.isFrozen;
}
}
} |
No, NA would pick up the context set during the last HA tick. | public NodeAgentContext nextContext() throws InterruptedException {
synchronized (monitor) {
nextContext = null;
Duration untilNextContext = Duration.ZERO;
while (setAndGetIsFrozen(wantFrozen) ||
nextContext == null ||
(untilNextContext = Duration.between(Instant.now(), nextContextAt)).toMillis() > 0) {
if (pendingInterrupt) {
pendingInterrupt = false;
throw new InterruptedException("interrupt() was called before next context was scheduled");
}
try {
monitor.wait(Math.max(untilNextContext.toMillis(), 0L));
} catch (InterruptedException ignored) { }
}
currentContext = nextContext;
return currentContext;
}
} | currentContext = nextContext; | public NodeAgentContext nextContext() throws InterruptedException {
synchronized (monitor) {
nextContext = null;
Duration untilNextContext = Duration.ZERO;
while (setAndGetIsFrozen(wantFrozen) ||
nextContext == null ||
(untilNextContext = Duration.between(Instant.now(), nextContextAt)).toMillis() > 0) {
if (pendingInterrupt) {
pendingInterrupt = false;
throw new InterruptedException("interrupt() was called before next context was scheduled");
}
try {
monitor.wait(Math.max(untilNextContext.toMillis(), 0L));
} catch (InterruptedException ignored) { }
}
currentContext = nextContext;
return currentContext;
}
} | class NodeAgentContextManager implements NodeAgentContextSupplier, NodeAgentScheduler {
private final Object monitor = new Object();
private final Clock clock;
private NodeAgentContext currentContext;
private NodeAgentContext nextContext;
private Instant nextContextAt;
private boolean wantFrozen = false;
private boolean isFrozen = true;
private boolean pendingInterrupt = false;
public NodeAgentContextManager(Clock clock, NodeAgentContext context) {
this.clock = clock;
this.currentContext = context;
}
@Override
public void scheduleTickWith(NodeAgentContext context, Instant at) {
synchronized (monitor) {
nextContext = Objects.requireNonNull(context);
nextContextAt = Objects.requireNonNull(at);
monitor.notifyAll();
}
}
@Override
public boolean setFrozen(boolean frozen, Duration timeout) {
synchronized (monitor) {
if (wantFrozen != frozen) {
wantFrozen = frozen;
monitor.notifyAll();
}
boolean successful;
long remainder;
long end = clock.instant().plus(timeout).toEpochMilli();
while (!(successful = isFrozen == frozen) && (remainder = end - clock.millis()) > 0) {
try {
monitor.wait(remainder);
} catch (InterruptedException ignored) { }
}
return successful;
}
}
@Override
@Override
public NodeAgentContext currentContext() {
synchronized (monitor) {
return currentContext;
}
}
@Override
public void interrupt() {
synchronized (monitor) {
pendingInterrupt = true;
monitor.notifyAll();
}
}
private boolean setAndGetIsFrozen(boolean isFrozen) {
synchronized (monitor) {
if (this.isFrozen != isFrozen) {
this.isFrozen = isFrozen;
monitor.notifyAll();
}
return this.isFrozen;
}
}
} | class NodeAgentContextManager implements NodeAgentContextSupplier, NodeAgentScheduler {
private final Object monitor = new Object();
private final Clock clock;
private NodeAgentContext currentContext;
private NodeAgentContext nextContext;
private Instant nextContextAt;
private boolean wantFrozen = false;
private boolean isFrozen = true;
private boolean pendingInterrupt = false;
public NodeAgentContextManager(Clock clock, NodeAgentContext context) {
this.clock = clock;
this.currentContext = context;
}
@Override
public void scheduleTickWith(NodeAgentContext context, Instant at) {
synchronized (monitor) {
nextContext = Objects.requireNonNull(context);
nextContextAt = Objects.requireNonNull(at);
monitor.notifyAll();
}
}
@Override
public boolean setFrozen(boolean frozen, Duration timeout) {
synchronized (monitor) {
if (wantFrozen != frozen) {
wantFrozen = frozen;
monitor.notifyAll();
}
boolean successful;
long remainder;
long end = clock.instant().plus(timeout).toEpochMilli();
while (!(successful = isFrozen == frozen) && (remainder = end - clock.millis()) > 0) {
try {
monitor.wait(remainder);
} catch (InterruptedException ignored) { }
}
return successful;
}
}
@Override
@Override
public NodeAgentContext currentContext() {
synchronized (monitor) {
return currentContext;
}
}
@Override
public void interrupt() {
synchronized (monitor) {
pendingInterrupt = true;
monitor.notifyAll();
}
}
private boolean setAndGetIsFrozen(boolean isFrozen) {
synchronized (monitor) {
if (this.isFrozen != isFrozen) {
this.isFrozen = isFrozen;
monitor.notifyAll();
}
return this.isFrozen;
}
}
} |
`removableHosts()` only contains "free" hosts, so if you were to allocate some of the host, this would lead to provisioning more hosts with exactly-provision-capacity? Generally, I think `preprovisionCapacity()` and `provisionExactCapacity()` can be merged, instead you should have 2 variants of `removableHostsOf()` | private void convergeToCapacity(NodeList nodes) {
List<Node> removableHosts = removableHostsOf(nodes);
List<Node> excessHosts;
if (nodeRepository().zone().getCloud().dynamicProvisioning()) {
excessHosts = preprovisionCapacity(removableHosts);
} else {
excessHosts = provisionExactCapacity(removableHosts);
}
excessHosts.forEach(host -> {
try {
hostProvisioner.deprovision(host);
nodeRepository().removeRecursively(host, true);
} catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to deprovision " + host.hostname() + ", will retry in " + interval(), e);
}
});
} | List<Node> removableHosts = removableHostsOf(nodes); | private void convergeToCapacity(NodeList nodes) {
List<NodeResources> capacity = targetCapacity();
List<Node> excessHosts = provision(capacity, nodes);
excessHosts.forEach(host -> {
try {
hostProvisioner.deprovision(host);
nodeRepository().removeRecursively(host, true);
} catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to deprovision " + host.hostname() + ", will retry in " + interval(), e);
}
});
} | class DynamicProvisioningMaintainer extends NodeRepositoryMaintainer {
private static final Logger log = Logger.getLogger(DynamicProvisioningMaintainer.class.getName());
private static final ApplicationId preprovisionAppId = ApplicationId.from("hosted-vespa", "tenant-host", "preprovision");
private final HostProvisioner hostProvisioner;
private final ListFlag<HostCapacity> preprovisionCapacityFlag;
private final ListFlag<HostCapacity> exactCapacityFlag;
DynamicProvisioningMaintainer(NodeRepository nodeRepository,
Duration interval,
HostProvisioner hostProvisioner,
FlagSource flagSource) {
super(nodeRepository, interval);
this.hostProvisioner = hostProvisioner;
this.preprovisionCapacityFlag = Flags.PREPROVISION_CAPACITY.bindTo(flagSource);
this.exactCapacityFlag = Flags.EXACT_PROVISION_CAPACITY.bindTo(flagSource);
}
@Override
protected void maintain() {
try (Mutex lock = nodeRepository().lockUnallocated()) {
NodeList nodes = nodeRepository().list();
resumeProvisioning(nodes, lock);
convergeToCapacity(nodes);
}
}
/** Resume provisioning of already provisioned hosts and their children */
private void resumeProvisioning(NodeList nodes, Mutex lock) {
Map<String, Set<Node>> nodesByProvisionedParentHostname = nodes.nodeType(NodeType.tenant).asList().stream()
.filter(node -> node.parentHostname().isPresent())
.collect(Collectors.groupingBy(
node -> node.parentHostname().get(),
Collectors.toSet()));
nodes.state(Node.State.provisioned).nodeType(NodeType.host).forEach(host -> {
Set<Node> children = nodesByProvisionedParentHostname.getOrDefault(host.hostname(), Set.of());
try {
List<Node> updatedNodes = hostProvisioner.provision(host, children);
nodeRepository().write(updatedNodes, lock);
} catch (IllegalArgumentException | IllegalStateException e) {
log.log(Level.INFO, "Failed to provision " + host.hostname() + " with " + children.size() + " children: " +
Exceptions.toMessageString(e));
} catch (FatalProvisioningException e) {
log.log(Level.SEVERE, "Failed to provision " + host.hostname() + " with " + children.size() +
" children, failing out the host recursively", e);
nodeRepository().failRecursively(
host.hostname(), Agent.operator, "Failed by HostProvisioner due to provisioning failure");
} catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to provision " + host.hostname() + ", will retry in " + interval(), e);
}
});
}
/** Converge zone to wanted capacity */
/** Provision the exact capacity declared for this zone, if any.
*
* @return Excess hosts that can be deprovisioned.
*/
private List<Node> provisionExactCapacity(List<Node> removableHosts) {
List<NodeResources> capacity = capacityFrom(exactCapacityFlag);
if (capacity.isEmpty()) return List.of();
List<Node> excessHosts = new ArrayList<>(removableHosts);
List<NodeResources> unsatisfiedCapacity = new ArrayList<>(capacity);
for (var resources : capacity) {
for (var host : removableHosts) {
if (!nodeRepository().canAllocateTenantNodeTo(host)) continue;
if (!nodeRepository().resourcesCalculator().advertisedResourcesOf(host.flavor()).satisfies(resources)) continue;
unsatisfiedCapacity.remove(resources);
excessHosts.remove(host);
}
}
provision(unsatisfiedCapacity);
return excessHosts;
}
/**
* Preprovision capacity declared for this zone, if any.
*
* @return Excess hosts that can be deprovisioned.
*/
private List<Node> preprovisionCapacity(List<Node> removableHosts) {
List<Node> excessHosts = new ArrayList<>(removableHosts);
List<NodeResources> capacity = capacityFrom(preprovisionCapacityFlag);
for (Iterator<NodeResources> it = capacity.iterator(); it.hasNext() && !excessHosts.isEmpty(); ) {
NodeResources resources = it.next();
excessHosts.stream()
.filter(nodeRepository()::canAllocateTenantNodeTo)
.filter(host -> nodeRepository().resourcesCalculator().advertisedResourcesOf(host.flavor()).satisfies(resources))
.min(Comparator.comparingInt(n -> n.flavor().cost()))
.ifPresent(host -> {
excessHosts.remove(host);
it.remove();
});
}
provision(capacity);
return excessHosts;
}
/** Provision hosts according to given capacity */
private void provision(List<NodeResources> capacity) {
capacity.forEach(resources -> {
try {
Version osVersion = nodeRepository().osVersions().targetFor(NodeType.host).orElse(Version.emptyVersion);
List<Node> hosts = hostProvisioner.provisionHosts(nodeRepository().database().getProvisionIndexes(1),
resources, preprovisionAppId, osVersion)
.stream()
.map(ProvisionedHost::generateHost)
.collect(Collectors.toList());
nodeRepository().addNodes(hosts, Agent.DynamicProvisioningMaintainer);
} catch (OutOfCapacityException | IllegalArgumentException | IllegalStateException e) {
log.log(Level.WARNING, "Failed to pre-provision " + resources + ": " + e.getMessage());
} catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to pre-provision " + resources + ", will retry in " + interval(), e);
}
});
}
/** Reads node resources declared by given flag */
private List<NodeResources> capacityFrom(ListFlag<HostCapacity> flag) {
return flag.value().stream()
.flatMap(cap -> {
NodeResources resources = new NodeResources(cap.getVcpu(), cap.getMemoryGb(),
cap.getDiskGb(), 1);
return IntStream.range(0, cap.getCount()).mapToObj(i -> resources);
})
.sorted(NodeResourceComparator.memoryDiskCpuOrder().reversed())
.collect(Collectors.toList());
}
/** Returns hosts that are candidates for removal, e.g. hosts that have no containers or are failed */
private static List<Node> removableHostsOf(NodeList nodes) {
Map<String, Node> hostsByHostname = nodes.nodeType(NodeType.host)
.matching(host -> host.state() != Node.State.parked ||
host.status().wantToDeprovision())
.stream()
.collect(Collectors.toMap(Node::hostname, Function.identity()));
nodes.asList().stream()
.filter(node -> node.allocation().isPresent())
.flatMap(node -> node.parentHostname().stream())
.distinct()
.forEach(hostsByHostname::remove);
return List.copyOf(hostsByHostname.values());
}
} | class DynamicProvisioningMaintainer extends NodeRepositoryMaintainer {
private static final Logger log = Logger.getLogger(DynamicProvisioningMaintainer.class.getName());
private static final ApplicationId preprovisionAppId = ApplicationId.from("hosted-vespa", "tenant-host", "preprovision");
private final HostProvisioner hostProvisioner;
private final ListFlag<HostCapacity> targetCapacityFlag;
DynamicProvisioningMaintainer(NodeRepository nodeRepository,
Duration interval,
HostProvisioner hostProvisioner,
FlagSource flagSource) {
super(nodeRepository, interval);
this.hostProvisioner = hostProvisioner;
this.targetCapacityFlag = Flags.TARGET_CAPACITY.bindTo(flagSource);
}
@Override
protected void maintain() {
try (Mutex lock = nodeRepository().lockUnallocated()) {
NodeList nodes = nodeRepository().list();
resumeProvisioning(nodes, lock);
convergeToCapacity(nodes);
}
}
/** Resume provisioning of already provisioned hosts and their children */
private void resumeProvisioning(NodeList nodes, Mutex lock) {
Map<String, Set<Node>> nodesByProvisionedParentHostname = nodes.nodeType(NodeType.tenant).asList().stream()
.filter(node -> node.parentHostname().isPresent())
.collect(Collectors.groupingBy(
node -> node.parentHostname().get(),
Collectors.toSet()));
nodes.state(Node.State.provisioned).nodeType(NodeType.host).forEach(host -> {
Set<Node> children = nodesByProvisionedParentHostname.getOrDefault(host.hostname(), Set.of());
try {
List<Node> updatedNodes = hostProvisioner.provision(host, children);
nodeRepository().write(updatedNodes, lock);
} catch (IllegalArgumentException | IllegalStateException e) {
log.log(Level.INFO, "Failed to provision " + host.hostname() + " with " + children.size() + " children: " +
Exceptions.toMessageString(e));
} catch (FatalProvisioningException e) {
log.log(Level.SEVERE, "Failed to provision " + host.hostname() + " with " + children.size() +
" children, failing out the host recursively", e);
nodeRepository().failRecursively(
host.hostname(), Agent.operator, "Failed by HostProvisioner due to provisioning failure");
} catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to provision " + host.hostname() + ", will retry in " + interval(), e);
}
});
}
/** Converge zone to wanted capacity */
/**
* Provision the nodes necessary to satisfy given capacity.
*
* @return Excess hosts that can safely be deprovisioned, if any.
*/
private List<Node> provision(List<NodeResources> capacity, NodeList nodes) {
List<Node> existingHosts = availableHostsOf(nodes);
if (nodeRepository().zone().getCloud().dynamicProvisioning()) {
existingHosts = removableHostsOf(existingHosts, nodes);
} else if (capacity.isEmpty()) {
return List.of();
}
List<Node> excessHosts = new ArrayList<>(existingHosts);
for (Iterator<NodeResources> it = capacity.iterator(); it.hasNext() && !excessHosts.isEmpty(); ) {
NodeResources resources = it.next();
excessHosts.stream()
.filter(nodeRepository()::canAllocateTenantNodeTo)
.filter(host -> nodeRepository().resourcesCalculator()
.advertisedResourcesOf(host.flavor())
.satisfies(resources))
.min(Comparator.comparingInt(n -> n.flavor().cost()))
.ifPresent(host -> {
excessHosts.remove(host);
it.remove();
});
}
capacity.forEach(resources -> {
try {
Version osVersion = nodeRepository().osVersions().targetFor(NodeType.host).orElse(Version.emptyVersion);
List<Node> hosts = hostProvisioner.provisionHosts(nodeRepository().database().getProvisionIndexes(1),
resources, preprovisionAppId, osVersion)
.stream()
.map(ProvisionedHost::generateHost)
.collect(Collectors.toList());
nodeRepository().addNodes(hosts, Agent.DynamicProvisioningMaintainer);
} catch (OutOfCapacityException | IllegalArgumentException | IllegalStateException e) {
log.log(Level.WARNING, "Failed to pre-provision " + resources + ": " + e.getMessage());
} catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to pre-provision " + resources + ", will retry in " + interval(), e);
}
});
return removableHostsOf(excessHosts, nodes);
}
/** Reads node resources declared by target capacity flag */
private List<NodeResources> targetCapacity() {
return targetCapacityFlag.value().stream()
.flatMap(cap -> {
NodeResources resources = new NodeResources(cap.getVcpu(), cap.getMemoryGb(),
cap.getDiskGb(), 1);
return IntStream.range(0, cap.getCount()).mapToObj(i -> resources);
})
.sorted(NodeResourceComparator.memoryDiskCpuOrder().reversed())
.collect(Collectors.toList());
}
/** Returns hosts that are considered available, i.e. not parked or flagged for deprovisioning */
private static List<Node> availableHostsOf(NodeList nodes) {
return nodes.nodeType(NodeType.host)
.matching(host -> host.state() != Node.State.parked || host.status().wantToDeprovision())
.asList();
}
/** Returns the subset of given hosts that have no containers and are thus removable */
private static List<Node> removableHostsOf(List<Node> hosts, NodeList allNodes) {
Map<String, Node> hostsByHostname = hosts.stream()
.collect(Collectors.toMap(Node::hostname,
Function.identity()));
allNodes.asList().stream()
.filter(node -> node.allocation().isPresent())
.flatMap(node -> node.parentHostname().stream())
.distinct()
.forEach(hostsByHostname::remove);
return List.copyOf(hostsByHostname.values());
}
} |
> this would lead to provisioning more hosts with exactly-provision-capacity? Good catch, will fix. | private void convergeToCapacity(NodeList nodes) {
List<Node> removableHosts = removableHostsOf(nodes);
List<Node> excessHosts;
if (nodeRepository().zone().getCloud().dynamicProvisioning()) {
excessHosts = preprovisionCapacity(removableHosts);
} else {
excessHosts = provisionExactCapacity(removableHosts);
}
excessHosts.forEach(host -> {
try {
hostProvisioner.deprovision(host);
nodeRepository().removeRecursively(host, true);
} catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to deprovision " + host.hostname() + ", will retry in " + interval(), e);
}
});
} | List<Node> removableHosts = removableHostsOf(nodes); | private void convergeToCapacity(NodeList nodes) {
List<NodeResources> capacity = targetCapacity();
List<Node> excessHosts = provision(capacity, nodes);
excessHosts.forEach(host -> {
try {
hostProvisioner.deprovision(host);
nodeRepository().removeRecursively(host, true);
} catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to deprovision " + host.hostname() + ", will retry in " + interval(), e);
}
});
} | class DynamicProvisioningMaintainer extends NodeRepositoryMaintainer {
private static final Logger log = Logger.getLogger(DynamicProvisioningMaintainer.class.getName());
private static final ApplicationId preprovisionAppId = ApplicationId.from("hosted-vespa", "tenant-host", "preprovision");
private final HostProvisioner hostProvisioner;
private final ListFlag<HostCapacity> preprovisionCapacityFlag;
private final ListFlag<HostCapacity> exactCapacityFlag;
DynamicProvisioningMaintainer(NodeRepository nodeRepository,
Duration interval,
HostProvisioner hostProvisioner,
FlagSource flagSource) {
super(nodeRepository, interval);
this.hostProvisioner = hostProvisioner;
this.preprovisionCapacityFlag = Flags.PREPROVISION_CAPACITY.bindTo(flagSource);
this.exactCapacityFlag = Flags.EXACT_PROVISION_CAPACITY.bindTo(flagSource);
}
@Override
protected void maintain() {
try (Mutex lock = nodeRepository().lockUnallocated()) {
NodeList nodes = nodeRepository().list();
resumeProvisioning(nodes, lock);
convergeToCapacity(nodes);
}
}
/** Resume provisioning of already provisioned hosts and their children */
private void resumeProvisioning(NodeList nodes, Mutex lock) {
Map<String, Set<Node>> nodesByProvisionedParentHostname = nodes.nodeType(NodeType.tenant).asList().stream()
.filter(node -> node.parentHostname().isPresent())
.collect(Collectors.groupingBy(
node -> node.parentHostname().get(),
Collectors.toSet()));
nodes.state(Node.State.provisioned).nodeType(NodeType.host).forEach(host -> {
Set<Node> children = nodesByProvisionedParentHostname.getOrDefault(host.hostname(), Set.of());
try {
List<Node> updatedNodes = hostProvisioner.provision(host, children);
nodeRepository().write(updatedNodes, lock);
} catch (IllegalArgumentException | IllegalStateException e) {
log.log(Level.INFO, "Failed to provision " + host.hostname() + " with " + children.size() + " children: " +
Exceptions.toMessageString(e));
} catch (FatalProvisioningException e) {
log.log(Level.SEVERE, "Failed to provision " + host.hostname() + " with " + children.size() +
" children, failing out the host recursively", e);
nodeRepository().failRecursively(
host.hostname(), Agent.operator, "Failed by HostProvisioner due to provisioning failure");
} catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to provision " + host.hostname() + ", will retry in " + interval(), e);
}
});
}
/** Converge zone to wanted capacity */
/** Provision the exact capacity declared for this zone, if any.
*
* @return Excess hosts that can be deprovisioned.
*/
private List<Node> provisionExactCapacity(List<Node> removableHosts) {
List<NodeResources> capacity = capacityFrom(exactCapacityFlag);
if (capacity.isEmpty()) return List.of();
List<Node> excessHosts = new ArrayList<>(removableHosts);
List<NodeResources> unsatisfiedCapacity = new ArrayList<>(capacity);
for (var resources : capacity) {
for (var host : removableHosts) {
if (!nodeRepository().canAllocateTenantNodeTo(host)) continue;
if (!nodeRepository().resourcesCalculator().advertisedResourcesOf(host.flavor()).satisfies(resources)) continue;
unsatisfiedCapacity.remove(resources);
excessHosts.remove(host);
}
}
provision(unsatisfiedCapacity);
return excessHosts;
}
/**
* Preprovision capacity declared for this zone, if any.
*
* @return Excess hosts that can be deprovisioned.
*/
private List<Node> preprovisionCapacity(List<Node> removableHosts) {
List<Node> excessHosts = new ArrayList<>(removableHosts);
List<NodeResources> capacity = capacityFrom(preprovisionCapacityFlag);
for (Iterator<NodeResources> it = capacity.iterator(); it.hasNext() && !excessHosts.isEmpty(); ) {
NodeResources resources = it.next();
excessHosts.stream()
.filter(nodeRepository()::canAllocateTenantNodeTo)
.filter(host -> nodeRepository().resourcesCalculator().advertisedResourcesOf(host.flavor()).satisfies(resources))
.min(Comparator.comparingInt(n -> n.flavor().cost()))
.ifPresent(host -> {
excessHosts.remove(host);
it.remove();
});
}
provision(capacity);
return excessHosts;
}
/** Provision hosts according to given capacity */
private void provision(List<NodeResources> capacity) {
capacity.forEach(resources -> {
try {
Version osVersion = nodeRepository().osVersions().targetFor(NodeType.host).orElse(Version.emptyVersion);
List<Node> hosts = hostProvisioner.provisionHosts(nodeRepository().database().getProvisionIndexes(1),
resources, preprovisionAppId, osVersion)
.stream()
.map(ProvisionedHost::generateHost)
.collect(Collectors.toList());
nodeRepository().addNodes(hosts, Agent.DynamicProvisioningMaintainer);
} catch (OutOfCapacityException | IllegalArgumentException | IllegalStateException e) {
log.log(Level.WARNING, "Failed to pre-provision " + resources + ": " + e.getMessage());
} catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to pre-provision " + resources + ", will retry in " + interval(), e);
}
});
}
/** Reads node resources declared by given flag */
private List<NodeResources> capacityFrom(ListFlag<HostCapacity> flag) {
return flag.value().stream()
.flatMap(cap -> {
NodeResources resources = new NodeResources(cap.getVcpu(), cap.getMemoryGb(),
cap.getDiskGb(), 1);
return IntStream.range(0, cap.getCount()).mapToObj(i -> resources);
})
.sorted(NodeResourceComparator.memoryDiskCpuOrder().reversed())
.collect(Collectors.toList());
}
/** Returns hosts that are candidates for removal, e.g. hosts that have no containers or are failed */
private static List<Node> removableHostsOf(NodeList nodes) {
Map<String, Node> hostsByHostname = nodes.nodeType(NodeType.host)
.matching(host -> host.state() != Node.State.parked ||
host.status().wantToDeprovision())
.stream()
.collect(Collectors.toMap(Node::hostname, Function.identity()));
nodes.asList().stream()
.filter(node -> node.allocation().isPresent())
.flatMap(node -> node.parentHostname().stream())
.distinct()
.forEach(hostsByHostname::remove);
return List.copyOf(hostsByHostname.values());
}
} | class DynamicProvisioningMaintainer extends NodeRepositoryMaintainer {
private static final Logger log = Logger.getLogger(DynamicProvisioningMaintainer.class.getName());
private static final ApplicationId preprovisionAppId = ApplicationId.from("hosted-vespa", "tenant-host", "preprovision");
private final HostProvisioner hostProvisioner;
private final ListFlag<HostCapacity> targetCapacityFlag;
DynamicProvisioningMaintainer(NodeRepository nodeRepository,
Duration interval,
HostProvisioner hostProvisioner,
FlagSource flagSource) {
super(nodeRepository, interval);
this.hostProvisioner = hostProvisioner;
this.targetCapacityFlag = Flags.TARGET_CAPACITY.bindTo(flagSource);
}
@Override
protected void maintain() {
try (Mutex lock = nodeRepository().lockUnallocated()) {
NodeList nodes = nodeRepository().list();
resumeProvisioning(nodes, lock);
convergeToCapacity(nodes);
}
}
/** Resume provisioning of already provisioned hosts and their children */
private void resumeProvisioning(NodeList nodes, Mutex lock) {
Map<String, Set<Node>> nodesByProvisionedParentHostname = nodes.nodeType(NodeType.tenant).asList().stream()
.filter(node -> node.parentHostname().isPresent())
.collect(Collectors.groupingBy(
node -> node.parentHostname().get(),
Collectors.toSet()));
nodes.state(Node.State.provisioned).nodeType(NodeType.host).forEach(host -> {
Set<Node> children = nodesByProvisionedParentHostname.getOrDefault(host.hostname(), Set.of());
try {
List<Node> updatedNodes = hostProvisioner.provision(host, children);
nodeRepository().write(updatedNodes, lock);
} catch (IllegalArgumentException | IllegalStateException e) {
log.log(Level.INFO, "Failed to provision " + host.hostname() + " with " + children.size() + " children: " +
Exceptions.toMessageString(e));
} catch (FatalProvisioningException e) {
log.log(Level.SEVERE, "Failed to provision " + host.hostname() + " with " + children.size() +
" children, failing out the host recursively", e);
nodeRepository().failRecursively(
host.hostname(), Agent.operator, "Failed by HostProvisioner due to provisioning failure");
} catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to provision " + host.hostname() + ", will retry in " + interval(), e);
}
});
}
/** Converge zone to wanted capacity */
/**
* Provision the nodes necessary to satisfy given capacity.
*
* @return Excess hosts that can safely be deprovisioned, if any.
*/
private List<Node> provision(List<NodeResources> capacity, NodeList nodes) {
List<Node> existingHosts = availableHostsOf(nodes);
if (nodeRepository().zone().getCloud().dynamicProvisioning()) {
existingHosts = removableHostsOf(existingHosts, nodes);
} else if (capacity.isEmpty()) {
return List.of();
}
List<Node> excessHosts = new ArrayList<>(existingHosts);
for (Iterator<NodeResources> it = capacity.iterator(); it.hasNext() && !excessHosts.isEmpty(); ) {
NodeResources resources = it.next();
excessHosts.stream()
.filter(nodeRepository()::canAllocateTenantNodeTo)
.filter(host -> nodeRepository().resourcesCalculator()
.advertisedResourcesOf(host.flavor())
.satisfies(resources))
.min(Comparator.comparingInt(n -> n.flavor().cost()))
.ifPresent(host -> {
excessHosts.remove(host);
it.remove();
});
}
capacity.forEach(resources -> {
try {
Version osVersion = nodeRepository().osVersions().targetFor(NodeType.host).orElse(Version.emptyVersion);
List<Node> hosts = hostProvisioner.provisionHosts(nodeRepository().database().getProvisionIndexes(1),
resources, preprovisionAppId, osVersion)
.stream()
.map(ProvisionedHost::generateHost)
.collect(Collectors.toList());
nodeRepository().addNodes(hosts, Agent.DynamicProvisioningMaintainer);
} catch (OutOfCapacityException | IllegalArgumentException | IllegalStateException e) {
log.log(Level.WARNING, "Failed to pre-provision " + resources + ": " + e.getMessage());
} catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to pre-provision " + resources + ", will retry in " + interval(), e);
}
});
return removableHostsOf(excessHosts, nodes);
}
/** Reads node resources declared by target capacity flag */
private List<NodeResources> targetCapacity() {
return targetCapacityFlag.value().stream()
.flatMap(cap -> {
NodeResources resources = new NodeResources(cap.getVcpu(), cap.getMemoryGb(),
cap.getDiskGb(), 1);
return IntStream.range(0, cap.getCount()).mapToObj(i -> resources);
})
.sorted(NodeResourceComparator.memoryDiskCpuOrder().reversed())
.collect(Collectors.toList());
}
/** Returns hosts that are considered available, i.e. not parked or flagged for deprovisioning */
private static List<Node> availableHostsOf(NodeList nodes) {
return nodes.nodeType(NodeType.host)
.matching(host -> host.state() != Node.State.parked || host.status().wantToDeprovision())
.asList();
}
/** Returns the subset of given hosts that have no containers and are thus removable */
private static List<Node> removableHostsOf(List<Node> hosts, NodeList allNodes) {
Map<String, Node> hostsByHostname = hosts.stream()
.collect(Collectors.toMap(Node::hostname,
Function.identity()));
allNodes.asList().stream()
.filter(node -> node.allocation().isPresent())
.flatMap(node -> node.parentHostname().stream())
.distinct()
.forEach(hostsByHostname::remove);
return List.copyOf(hostsByHostname.values());
}
} |
Add unit test: This would then fail. | private static void verifyValues(JsonNode root) {
var cursor = new JsonAccessor(root);
cursor.get("rules").forEachArrayElement(rule -> rule.get("conditions").forEachArrayElement(condition -> {
var dimension = condition.get("dimension");
if (dimension.isEqualTo(DimensionHelper.toWire(FetchVector.Dimension.APPLICATION_ID))) {
condition.get("values").forEachArrayElement(conditionValue -> {
String applicationIdString = conditionValue.asString()
.orElseThrow(() -> new IllegalArgumentException("Non-string application ID: " + conditionValue));
ApplicationId.fromSerializedForm(applicationIdString);
});
} else if (dimension.isEqualTo(DimensionHelper.toWire(FetchVector.Dimension.NODE_TYPE))) {
condition.get("values").forEachArrayElement(conditionValue -> {
String nodeTypeString = conditionValue.asString()
.orElseThrow(() -> new IllegalArgumentException("Non-string node type: " + conditionValue));
NodeType.valueOf(nodeTypeString);
});
} else if (dimension.isEqualTo(DimensionHelper.toWire(FetchVector.Dimension.CONSOLE_USER_EMAIL))) {
condition.get("values").forEachArrayElement(conditionValue -> {
String consoleUserEmailString = conditionValue.asString()
.orElseThrow(() -> new IllegalArgumentException("Non-string email address: " + conditionValue));
NodeType.valueOf(consoleUserEmailString);
});
}
}));
} | NodeType.valueOf(consoleUserEmailString); | private static void verifyValues(JsonNode root) {
var cursor = new JsonAccessor(root);
cursor.get("rules").forEachArrayElement(rule -> rule.get("conditions").forEachArrayElement(condition -> {
var dimension = condition.get("dimension");
if (dimension.isEqualTo(DimensionHelper.toWire(FetchVector.Dimension.APPLICATION_ID))) {
condition.get("values").forEachArrayElement(conditionValue -> {
String applicationIdString = conditionValue.asString()
.orElseThrow(() -> new IllegalArgumentException("Non-string application ID: " + conditionValue));
ApplicationId.fromSerializedForm(applicationIdString);
});
} else if (dimension.isEqualTo(DimensionHelper.toWire(FetchVector.Dimension.NODE_TYPE))) {
condition.get("values").forEachArrayElement(conditionValue -> {
String nodeTypeString = conditionValue.asString()
.orElseThrow(() -> new IllegalArgumentException("Non-string node type: " + conditionValue));
NodeType.valueOf(nodeTypeString);
});
} else if (dimension.isEqualTo(DimensionHelper.toWire(FetchVector.Dimension.CONSOLE_USER_EMAIL))) {
condition.get("values").forEachArrayElement(conditionValue -> conditionValue.asString()
.orElseThrow(() -> new IllegalArgumentException("Non-string email address: " + conditionValue)));
}
}));
} | class SystemFlagsDataArchive {
private static final ObjectMapper mapper = new ObjectMapper();
private final Map<FlagId, Map<String, FlagData>> files;
private SystemFlagsDataArchive(Map<FlagId, Map<String, FlagData>> files) {
this.files = files;
}
public static SystemFlagsDataArchive fromZip(InputStream rawIn) {
Builder builder = new Builder();
try (ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(rawIn))) {
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
String name = entry.getName();
if (!entry.isDirectory() && name.startsWith("flags/")) {
Path filePath = Paths.get(name);
String rawData = new String(zipIn.readAllBytes(), StandardCharsets.UTF_8);
addFile(builder, rawData, filePath);
}
}
return builder.build();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static SystemFlagsDataArchive fromDirectory(Path directory) {
Path root = directory.toAbsolutePath();
Path flagsDirectory = directory.resolve("flags");
if (!Files.isDirectory(flagsDirectory)) {
throw new IllegalArgumentException("Sub-directory 'flags' does not exist: " + flagsDirectory);
}
try (Stream<Path> directoryStream = Files.walk(root)) {
Builder builder = new Builder();
directoryStream.forEach(absolutePath -> {
Path relativePath = root.relativize(absolutePath);
if (!Files.isDirectory(absolutePath) &&
relativePath.startsWith("flags")) {
String rawData = uncheck(() -> Files.readString(absolutePath, StandardCharsets.UTF_8));
addFile(builder, rawData, relativePath);
}
});
return builder.build();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public void toZip(OutputStream out) {
ZipOutputStream zipOut = new ZipOutputStream(out);
files.forEach((flagId, fileMap) -> {
fileMap.forEach((filename, flagData) -> {
uncheck(() -> {
zipOut.putNextEntry(new ZipEntry(toFilePath(flagId, filename)));
zipOut.write(flagData.serializeToUtf8Json());
zipOut.closeEntry();
});
});
});
uncheck(zipOut::flush);
}
public Set<FlagData> flagData(FlagsTarget target) {
List<String> filenames = target.flagDataFilesPrioritized();
Set<FlagData> targetData = new HashSet<>();
files.forEach((flagId, fileMap) -> {
for (String filename : filenames) {
FlagData data = fileMap.get(filename);
if (data != null) {
if (!data.isEmpty()) {
targetData.add(data);
}
return;
}
}
});
return targetData;
}
public void validateAllFilesAreForTargets(SystemName currentSystem, Set<FlagsTarget> targets) throws IllegalArgumentException {
Set<String> validFiles = targets.stream()
.flatMap(target -> target.flagDataFilesPrioritized().stream())
.collect(Collectors.toSet());
Set<SystemName> otherSystems = Arrays.stream(SystemName.values())
.filter(systemName -> systemName != currentSystem)
.collect(Collectors.toSet());
files.forEach((flagId, fileMap) -> {
for (String filename : fileMap.keySet()) {
boolean isFileForOtherSystem = otherSystems.stream()
.anyMatch(system -> filename.startsWith(system.value() + "."));
boolean isFileForCurrentSystem = validFiles.contains(filename);
if (!isFileForOtherSystem && !isFileForCurrentSystem) {
throw new IllegalArgumentException("Unknown flag file: " + toFilePath(flagId, filename));
}
}
});
}
private static void addFile(Builder builder, String rawData, Path filePath) {
String filename = filePath.getFileName().toString();
if (filename.startsWith(".")) {
return;
}
if (!filename.endsWith(".json")) {
throw new IllegalArgumentException(String.format("Only JSON files are allowed in 'flags/' directory (found '%s')", filePath.toString()));
}
FlagId directoryDeducedFlagId = new FlagId(filePath.getName(1).toString());
FlagData flagData;
if (rawData.isBlank()) {
flagData = new FlagData(directoryDeducedFlagId);
} else {
String normalizedRawData = normalizeJson(rawData);
flagData = FlagData.deserialize(normalizedRawData);
if (!directoryDeducedFlagId.equals(flagData.id())) {
throw new IllegalArgumentException(
String.format("Flag data file with flag id '%s' in directory for '%s'",
flagData.id(), directoryDeducedFlagId.toString()));
}
String serializedData = flagData.serializeToJson();
if (!JSON.equals(serializedData, normalizedRawData)) {
throw new IllegalArgumentException(filePath + " contains unknown non-comment fields: " +
"after removing any comment fields the JSON is:\n " +
normalizedRawData +
"\nbut deserializing this ended up with a JSON that are missing some of the fields:\n " +
serializedData +
"\nSee https:
}
}
builder.addFile(filename, flagData);
}
static String normalizeJson(String json) {
JsonNode root = uncheck(() -> mapper.readTree(json));
removeCommentsRecursively(root);
verifyValues(root);
return root.toString();
}
private static void removeCommentsRecursively(JsonNode node) {
if (node instanceof ObjectNode) {
ObjectNode objectNode = (ObjectNode) node;
objectNode.remove("comment");
}
node.forEach(SystemFlagsDataArchive::removeCommentsRecursively);
}
private static String toFilePath(FlagId flagId, String filename) {
return "flags/" + flagId.toString() + "/" + filename;
}
public static class Builder {
private final Map<FlagId, Map<String, FlagData>> files = new TreeMap<>();
public Builder() {}
public Builder addFile(String filename, FlagData data) {
files.computeIfAbsent(data.id(), k -> new TreeMap<>()).put(filename, data);
return this;
}
public SystemFlagsDataArchive build() {
Map<FlagId, Map<String, FlagData>> copy = new TreeMap<>();
files.forEach((flagId, map) -> copy.put(flagId, new TreeMap<>(map)));
return new SystemFlagsDataArchive(copy);
}
}
private static class JsonAccessor {
private final JsonNode jsonNode;
public JsonAccessor(JsonNode jsonNode) {
this.jsonNode = jsonNode;
}
public JsonAccessor get(String fieldName) {
if (jsonNode == null) {
return this;
} else {
return new JsonAccessor(jsonNode.get(fieldName));
}
}
public Optional<String> asString() {
return jsonNode != null && jsonNode.isTextual() ? Optional.of(jsonNode.textValue()) : Optional.empty();
}
public void forEachArrayElement(Consumer<JsonAccessor> consumer) {
if (jsonNode != null && jsonNode.isArray()) {
jsonNode.forEach(jsonNodeElement -> consumer.accept(new JsonAccessor(jsonNodeElement)));
}
}
/** Returns true if this (JsonNode) is a string and equal to value. */
public boolean isEqualTo(String value) {
return jsonNode != null && jsonNode.isTextual() && Objects.equals(jsonNode.textValue(), value);
}
@Override
public String toString() {
return jsonNode == null ? "undefined" : jsonNode.toString();
}
}
} | class SystemFlagsDataArchive {
private static final ObjectMapper mapper = new ObjectMapper();
private final Map<FlagId, Map<String, FlagData>> files;
private SystemFlagsDataArchive(Map<FlagId, Map<String, FlagData>> files) {
this.files = files;
}
public static SystemFlagsDataArchive fromZip(InputStream rawIn) {
Builder builder = new Builder();
try (ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(rawIn))) {
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
String name = entry.getName();
if (!entry.isDirectory() && name.startsWith("flags/")) {
Path filePath = Paths.get(name);
String rawData = new String(zipIn.readAllBytes(), StandardCharsets.UTF_8);
addFile(builder, rawData, filePath);
}
}
return builder.build();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static SystemFlagsDataArchive fromDirectory(Path directory) {
Path root = directory.toAbsolutePath();
Path flagsDirectory = directory.resolve("flags");
if (!Files.isDirectory(flagsDirectory)) {
throw new IllegalArgumentException("Sub-directory 'flags' does not exist: " + flagsDirectory);
}
try (Stream<Path> directoryStream = Files.walk(root)) {
Builder builder = new Builder();
directoryStream.forEach(absolutePath -> {
Path relativePath = root.relativize(absolutePath);
if (!Files.isDirectory(absolutePath) &&
relativePath.startsWith("flags")) {
String rawData = uncheck(() -> Files.readString(absolutePath, StandardCharsets.UTF_8));
addFile(builder, rawData, relativePath);
}
});
return builder.build();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public void toZip(OutputStream out) {
ZipOutputStream zipOut = new ZipOutputStream(out);
files.forEach((flagId, fileMap) -> {
fileMap.forEach((filename, flagData) -> {
uncheck(() -> {
zipOut.putNextEntry(new ZipEntry(toFilePath(flagId, filename)));
zipOut.write(flagData.serializeToUtf8Json());
zipOut.closeEntry();
});
});
});
uncheck(zipOut::flush);
}
public Set<FlagData> flagData(FlagsTarget target) {
List<String> filenames = target.flagDataFilesPrioritized();
Set<FlagData> targetData = new HashSet<>();
files.forEach((flagId, fileMap) -> {
for (String filename : filenames) {
FlagData data = fileMap.get(filename);
if (data != null) {
if (!data.isEmpty()) {
targetData.add(data);
}
return;
}
}
});
return targetData;
}
public void validateAllFilesAreForTargets(SystemName currentSystem, Set<FlagsTarget> targets) throws IllegalArgumentException {
Set<String> validFiles = targets.stream()
.flatMap(target -> target.flagDataFilesPrioritized().stream())
.collect(Collectors.toSet());
Set<SystemName> otherSystems = Arrays.stream(SystemName.values())
.filter(systemName -> systemName != currentSystem)
.collect(Collectors.toSet());
files.forEach((flagId, fileMap) -> {
for (String filename : fileMap.keySet()) {
boolean isFileForOtherSystem = otherSystems.stream()
.anyMatch(system -> filename.startsWith(system.value() + "."));
boolean isFileForCurrentSystem = validFiles.contains(filename);
if (!isFileForOtherSystem && !isFileForCurrentSystem) {
throw new IllegalArgumentException("Unknown flag file: " + toFilePath(flagId, filename));
}
}
});
}
private static void addFile(Builder builder, String rawData, Path filePath) {
String filename = filePath.getFileName().toString();
if (filename.startsWith(".")) {
return;
}
if (!filename.endsWith(".json")) {
throw new IllegalArgumentException(String.format("Only JSON files are allowed in 'flags/' directory (found '%s')", filePath.toString()));
}
FlagId directoryDeducedFlagId = new FlagId(filePath.getName(1).toString());
FlagData flagData;
if (rawData.isBlank()) {
flagData = new FlagData(directoryDeducedFlagId);
} else {
String normalizedRawData = normalizeJson(rawData);
flagData = FlagData.deserialize(normalizedRawData);
if (!directoryDeducedFlagId.equals(flagData.id())) {
throw new IllegalArgumentException(
String.format("Flag data file with flag id '%s' in directory for '%s'",
flagData.id(), directoryDeducedFlagId.toString()));
}
String serializedData = flagData.serializeToJson();
if (!JSON.equals(serializedData, normalizedRawData)) {
throw new IllegalArgumentException(filePath + " contains unknown non-comment fields: " +
"after removing any comment fields the JSON is:\n " +
normalizedRawData +
"\nbut deserializing this ended up with a JSON that are missing some of the fields:\n " +
serializedData +
"\nSee https:
}
}
builder.addFile(filename, flagData);
}
static String normalizeJson(String json) {
JsonNode root = uncheck(() -> mapper.readTree(json));
removeCommentsRecursively(root);
verifyValues(root);
return root.toString();
}
private static void removeCommentsRecursively(JsonNode node) {
if (node instanceof ObjectNode) {
ObjectNode objectNode = (ObjectNode) node;
objectNode.remove("comment");
}
node.forEach(SystemFlagsDataArchive::removeCommentsRecursively);
}
private static String toFilePath(FlagId flagId, String filename) {
return "flags/" + flagId.toString() + "/" + filename;
}
public static class Builder {
private final Map<FlagId, Map<String, FlagData>> files = new TreeMap<>();
public Builder() {}
public Builder addFile(String filename, FlagData data) {
files.computeIfAbsent(data.id(), k -> new TreeMap<>()).put(filename, data);
return this;
}
public SystemFlagsDataArchive build() {
Map<FlagId, Map<String, FlagData>> copy = new TreeMap<>();
files.forEach((flagId, map) -> copy.put(flagId, new TreeMap<>(map)));
return new SystemFlagsDataArchive(copy);
}
}
private static class JsonAccessor {
private final JsonNode jsonNode;
public JsonAccessor(JsonNode jsonNode) {
this.jsonNode = jsonNode;
}
public JsonAccessor get(String fieldName) {
if (jsonNode == null) {
return this;
} else {
return new JsonAccessor(jsonNode.get(fieldName));
}
}
public Optional<String> asString() {
return jsonNode != null && jsonNode.isTextual() ? Optional.of(jsonNode.textValue()) : Optional.empty();
}
public void forEachArrayElement(Consumer<JsonAccessor> consumer) {
if (jsonNode != null && jsonNode.isArray()) {
jsonNode.forEach(jsonNodeElement -> consumer.accept(new JsonAccessor(jsonNodeElement)));
}
}
/** Returns true if this (JsonNode) is a string and equal to value. */
public boolean isEqualTo(String value) {
return jsonNode != null && jsonNode.isTextual() && Objects.equals(jsonNode.textValue(), value);
}
@Override
public String toString() {
return jsonNode == null ? "undefined" : jsonNode.toString();
}
}
} |
Yes, looks like I copy pasted a little too much :-) | private static void verifyValues(JsonNode root) {
var cursor = new JsonAccessor(root);
cursor.get("rules").forEachArrayElement(rule -> rule.get("conditions").forEachArrayElement(condition -> {
var dimension = condition.get("dimension");
if (dimension.isEqualTo(DimensionHelper.toWire(FetchVector.Dimension.APPLICATION_ID))) {
condition.get("values").forEachArrayElement(conditionValue -> {
String applicationIdString = conditionValue.asString()
.orElseThrow(() -> new IllegalArgumentException("Non-string application ID: " + conditionValue));
ApplicationId.fromSerializedForm(applicationIdString);
});
} else if (dimension.isEqualTo(DimensionHelper.toWire(FetchVector.Dimension.NODE_TYPE))) {
condition.get("values").forEachArrayElement(conditionValue -> {
String nodeTypeString = conditionValue.asString()
.orElseThrow(() -> new IllegalArgumentException("Non-string node type: " + conditionValue));
NodeType.valueOf(nodeTypeString);
});
} else if (dimension.isEqualTo(DimensionHelper.toWire(FetchVector.Dimension.CONSOLE_USER_EMAIL))) {
condition.get("values").forEachArrayElement(conditionValue -> {
String consoleUserEmailString = conditionValue.asString()
.orElseThrow(() -> new IllegalArgumentException("Non-string email address: " + conditionValue));
NodeType.valueOf(consoleUserEmailString);
});
}
}));
} | NodeType.valueOf(consoleUserEmailString); | private static void verifyValues(JsonNode root) {
var cursor = new JsonAccessor(root);
cursor.get("rules").forEachArrayElement(rule -> rule.get("conditions").forEachArrayElement(condition -> {
var dimension = condition.get("dimension");
if (dimension.isEqualTo(DimensionHelper.toWire(FetchVector.Dimension.APPLICATION_ID))) {
condition.get("values").forEachArrayElement(conditionValue -> {
String applicationIdString = conditionValue.asString()
.orElseThrow(() -> new IllegalArgumentException("Non-string application ID: " + conditionValue));
ApplicationId.fromSerializedForm(applicationIdString);
});
} else if (dimension.isEqualTo(DimensionHelper.toWire(FetchVector.Dimension.NODE_TYPE))) {
condition.get("values").forEachArrayElement(conditionValue -> {
String nodeTypeString = conditionValue.asString()
.orElseThrow(() -> new IllegalArgumentException("Non-string node type: " + conditionValue));
NodeType.valueOf(nodeTypeString);
});
} else if (dimension.isEqualTo(DimensionHelper.toWire(FetchVector.Dimension.CONSOLE_USER_EMAIL))) {
condition.get("values").forEachArrayElement(conditionValue -> conditionValue.asString()
.orElseThrow(() -> new IllegalArgumentException("Non-string email address: " + conditionValue)));
}
}));
} | class SystemFlagsDataArchive {
private static final ObjectMapper mapper = new ObjectMapper();
private final Map<FlagId, Map<String, FlagData>> files;
private SystemFlagsDataArchive(Map<FlagId, Map<String, FlagData>> files) {
this.files = files;
}
public static SystemFlagsDataArchive fromZip(InputStream rawIn) {
Builder builder = new Builder();
try (ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(rawIn))) {
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
String name = entry.getName();
if (!entry.isDirectory() && name.startsWith("flags/")) {
Path filePath = Paths.get(name);
String rawData = new String(zipIn.readAllBytes(), StandardCharsets.UTF_8);
addFile(builder, rawData, filePath);
}
}
return builder.build();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static SystemFlagsDataArchive fromDirectory(Path directory) {
Path root = directory.toAbsolutePath();
Path flagsDirectory = directory.resolve("flags");
if (!Files.isDirectory(flagsDirectory)) {
throw new IllegalArgumentException("Sub-directory 'flags' does not exist: " + flagsDirectory);
}
try (Stream<Path> directoryStream = Files.walk(root)) {
Builder builder = new Builder();
directoryStream.forEach(absolutePath -> {
Path relativePath = root.relativize(absolutePath);
if (!Files.isDirectory(absolutePath) &&
relativePath.startsWith("flags")) {
String rawData = uncheck(() -> Files.readString(absolutePath, StandardCharsets.UTF_8));
addFile(builder, rawData, relativePath);
}
});
return builder.build();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public void toZip(OutputStream out) {
ZipOutputStream zipOut = new ZipOutputStream(out);
files.forEach((flagId, fileMap) -> {
fileMap.forEach((filename, flagData) -> {
uncheck(() -> {
zipOut.putNextEntry(new ZipEntry(toFilePath(flagId, filename)));
zipOut.write(flagData.serializeToUtf8Json());
zipOut.closeEntry();
});
});
});
uncheck(zipOut::flush);
}
public Set<FlagData> flagData(FlagsTarget target) {
List<String> filenames = target.flagDataFilesPrioritized();
Set<FlagData> targetData = new HashSet<>();
files.forEach((flagId, fileMap) -> {
for (String filename : filenames) {
FlagData data = fileMap.get(filename);
if (data != null) {
if (!data.isEmpty()) {
targetData.add(data);
}
return;
}
}
});
return targetData;
}
public void validateAllFilesAreForTargets(SystemName currentSystem, Set<FlagsTarget> targets) throws IllegalArgumentException {
Set<String> validFiles = targets.stream()
.flatMap(target -> target.flagDataFilesPrioritized().stream())
.collect(Collectors.toSet());
Set<SystemName> otherSystems = Arrays.stream(SystemName.values())
.filter(systemName -> systemName != currentSystem)
.collect(Collectors.toSet());
files.forEach((flagId, fileMap) -> {
for (String filename : fileMap.keySet()) {
boolean isFileForOtherSystem = otherSystems.stream()
.anyMatch(system -> filename.startsWith(system.value() + "."));
boolean isFileForCurrentSystem = validFiles.contains(filename);
if (!isFileForOtherSystem && !isFileForCurrentSystem) {
throw new IllegalArgumentException("Unknown flag file: " + toFilePath(flagId, filename));
}
}
});
}
private static void addFile(Builder builder, String rawData, Path filePath) {
String filename = filePath.getFileName().toString();
if (filename.startsWith(".")) {
return;
}
if (!filename.endsWith(".json")) {
throw new IllegalArgumentException(String.format("Only JSON files are allowed in 'flags/' directory (found '%s')", filePath.toString()));
}
FlagId directoryDeducedFlagId = new FlagId(filePath.getName(1).toString());
FlagData flagData;
if (rawData.isBlank()) {
flagData = new FlagData(directoryDeducedFlagId);
} else {
String normalizedRawData = normalizeJson(rawData);
flagData = FlagData.deserialize(normalizedRawData);
if (!directoryDeducedFlagId.equals(flagData.id())) {
throw new IllegalArgumentException(
String.format("Flag data file with flag id '%s' in directory for '%s'",
flagData.id(), directoryDeducedFlagId.toString()));
}
String serializedData = flagData.serializeToJson();
if (!JSON.equals(serializedData, normalizedRawData)) {
throw new IllegalArgumentException(filePath + " contains unknown non-comment fields: " +
"after removing any comment fields the JSON is:\n " +
normalizedRawData +
"\nbut deserializing this ended up with a JSON that are missing some of the fields:\n " +
serializedData +
"\nSee https:
}
}
builder.addFile(filename, flagData);
}
static String normalizeJson(String json) {
JsonNode root = uncheck(() -> mapper.readTree(json));
removeCommentsRecursively(root);
verifyValues(root);
return root.toString();
}
private static void removeCommentsRecursively(JsonNode node) {
if (node instanceof ObjectNode) {
ObjectNode objectNode = (ObjectNode) node;
objectNode.remove("comment");
}
node.forEach(SystemFlagsDataArchive::removeCommentsRecursively);
}
private static String toFilePath(FlagId flagId, String filename) {
return "flags/" + flagId.toString() + "/" + filename;
}
public static class Builder {
private final Map<FlagId, Map<String, FlagData>> files = new TreeMap<>();
public Builder() {}
public Builder addFile(String filename, FlagData data) {
files.computeIfAbsent(data.id(), k -> new TreeMap<>()).put(filename, data);
return this;
}
public SystemFlagsDataArchive build() {
Map<FlagId, Map<String, FlagData>> copy = new TreeMap<>();
files.forEach((flagId, map) -> copy.put(flagId, new TreeMap<>(map)));
return new SystemFlagsDataArchive(copy);
}
}
private static class JsonAccessor {
private final JsonNode jsonNode;
public JsonAccessor(JsonNode jsonNode) {
this.jsonNode = jsonNode;
}
public JsonAccessor get(String fieldName) {
if (jsonNode == null) {
return this;
} else {
return new JsonAccessor(jsonNode.get(fieldName));
}
}
public Optional<String> asString() {
return jsonNode != null && jsonNode.isTextual() ? Optional.of(jsonNode.textValue()) : Optional.empty();
}
public void forEachArrayElement(Consumer<JsonAccessor> consumer) {
if (jsonNode != null && jsonNode.isArray()) {
jsonNode.forEach(jsonNodeElement -> consumer.accept(new JsonAccessor(jsonNodeElement)));
}
}
/** Returns true if this (JsonNode) is a string and equal to value. */
public boolean isEqualTo(String value) {
return jsonNode != null && jsonNode.isTextual() && Objects.equals(jsonNode.textValue(), value);
}
@Override
public String toString() {
return jsonNode == null ? "undefined" : jsonNode.toString();
}
}
} | class SystemFlagsDataArchive {
private static final ObjectMapper mapper = new ObjectMapper();
private final Map<FlagId, Map<String, FlagData>> files;
private SystemFlagsDataArchive(Map<FlagId, Map<String, FlagData>> files) {
this.files = files;
}
public static SystemFlagsDataArchive fromZip(InputStream rawIn) {
Builder builder = new Builder();
try (ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(rawIn))) {
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
String name = entry.getName();
if (!entry.isDirectory() && name.startsWith("flags/")) {
Path filePath = Paths.get(name);
String rawData = new String(zipIn.readAllBytes(), StandardCharsets.UTF_8);
addFile(builder, rawData, filePath);
}
}
return builder.build();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static SystemFlagsDataArchive fromDirectory(Path directory) {
Path root = directory.toAbsolutePath();
Path flagsDirectory = directory.resolve("flags");
if (!Files.isDirectory(flagsDirectory)) {
throw new IllegalArgumentException("Sub-directory 'flags' does not exist: " + flagsDirectory);
}
try (Stream<Path> directoryStream = Files.walk(root)) {
Builder builder = new Builder();
directoryStream.forEach(absolutePath -> {
Path relativePath = root.relativize(absolutePath);
if (!Files.isDirectory(absolutePath) &&
relativePath.startsWith("flags")) {
String rawData = uncheck(() -> Files.readString(absolutePath, StandardCharsets.UTF_8));
addFile(builder, rawData, relativePath);
}
});
return builder.build();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public void toZip(OutputStream out) {
ZipOutputStream zipOut = new ZipOutputStream(out);
files.forEach((flagId, fileMap) -> {
fileMap.forEach((filename, flagData) -> {
uncheck(() -> {
zipOut.putNextEntry(new ZipEntry(toFilePath(flagId, filename)));
zipOut.write(flagData.serializeToUtf8Json());
zipOut.closeEntry();
});
});
});
uncheck(zipOut::flush);
}
public Set<FlagData> flagData(FlagsTarget target) {
List<String> filenames = target.flagDataFilesPrioritized();
Set<FlagData> targetData = new HashSet<>();
files.forEach((flagId, fileMap) -> {
for (String filename : filenames) {
FlagData data = fileMap.get(filename);
if (data != null) {
if (!data.isEmpty()) {
targetData.add(data);
}
return;
}
}
});
return targetData;
}
public void validateAllFilesAreForTargets(SystemName currentSystem, Set<FlagsTarget> targets) throws IllegalArgumentException {
Set<String> validFiles = targets.stream()
.flatMap(target -> target.flagDataFilesPrioritized().stream())
.collect(Collectors.toSet());
Set<SystemName> otherSystems = Arrays.stream(SystemName.values())
.filter(systemName -> systemName != currentSystem)
.collect(Collectors.toSet());
files.forEach((flagId, fileMap) -> {
for (String filename : fileMap.keySet()) {
boolean isFileForOtherSystem = otherSystems.stream()
.anyMatch(system -> filename.startsWith(system.value() + "."));
boolean isFileForCurrentSystem = validFiles.contains(filename);
if (!isFileForOtherSystem && !isFileForCurrentSystem) {
throw new IllegalArgumentException("Unknown flag file: " + toFilePath(flagId, filename));
}
}
});
}
private static void addFile(Builder builder, String rawData, Path filePath) {
String filename = filePath.getFileName().toString();
if (filename.startsWith(".")) {
return;
}
if (!filename.endsWith(".json")) {
throw new IllegalArgumentException(String.format("Only JSON files are allowed in 'flags/' directory (found '%s')", filePath.toString()));
}
FlagId directoryDeducedFlagId = new FlagId(filePath.getName(1).toString());
FlagData flagData;
if (rawData.isBlank()) {
flagData = new FlagData(directoryDeducedFlagId);
} else {
String normalizedRawData = normalizeJson(rawData);
flagData = FlagData.deserialize(normalizedRawData);
if (!directoryDeducedFlagId.equals(flagData.id())) {
throw new IllegalArgumentException(
String.format("Flag data file with flag id '%s' in directory for '%s'",
flagData.id(), directoryDeducedFlagId.toString()));
}
String serializedData = flagData.serializeToJson();
if (!JSON.equals(serializedData, normalizedRawData)) {
throw new IllegalArgumentException(filePath + " contains unknown non-comment fields: " +
"after removing any comment fields the JSON is:\n " +
normalizedRawData +
"\nbut deserializing this ended up with a JSON that are missing some of the fields:\n " +
serializedData +
"\nSee https:
}
}
builder.addFile(filename, flagData);
}
static String normalizeJson(String json) {
JsonNode root = uncheck(() -> mapper.readTree(json));
removeCommentsRecursively(root);
verifyValues(root);
return root.toString();
}
private static void removeCommentsRecursively(JsonNode node) {
if (node instanceof ObjectNode) {
ObjectNode objectNode = (ObjectNode) node;
objectNode.remove("comment");
}
node.forEach(SystemFlagsDataArchive::removeCommentsRecursively);
}
private static String toFilePath(FlagId flagId, String filename) {
return "flags/" + flagId.toString() + "/" + filename;
}
public static class Builder {
private final Map<FlagId, Map<String, FlagData>> files = new TreeMap<>();
public Builder() {}
public Builder addFile(String filename, FlagData data) {
files.computeIfAbsent(data.id(), k -> new TreeMap<>()).put(filename, data);
return this;
}
public SystemFlagsDataArchive build() {
Map<FlagId, Map<String, FlagData>> copy = new TreeMap<>();
files.forEach((flagId, map) -> copy.put(flagId, new TreeMap<>(map)));
return new SystemFlagsDataArchive(copy);
}
}
private static class JsonAccessor {
private final JsonNode jsonNode;
public JsonAccessor(JsonNode jsonNode) {
this.jsonNode = jsonNode;
}
public JsonAccessor get(String fieldName) {
if (jsonNode == null) {
return this;
} else {
return new JsonAccessor(jsonNode.get(fieldName));
}
}
public Optional<String> asString() {
return jsonNode != null && jsonNode.isTextual() ? Optional.of(jsonNode.textValue()) : Optional.empty();
}
public void forEachArrayElement(Consumer<JsonAccessor> consumer) {
if (jsonNode != null && jsonNode.isArray()) {
jsonNode.forEach(jsonNodeElement -> consumer.accept(new JsonAccessor(jsonNodeElement)));
}
}
/** Returns true if this (JsonNode) is a string and equal to value. */
public boolean isEqualTo(String value) {
return jsonNode != null && jsonNode.isTextual() && Objects.equals(jsonNode.textValue(), value);
}
@Override
public String toString() {
return jsonNode == null ? "undefined" : jsonNode.toString();
}
}
} |
`currentDockerImage` is not guaranteed to be set (f.ex. if core is dumped while starting or stopping the container), I suggest defaulting to the RHEL 7 variant. | Path GDBPath(NodeAgentContext context) {
DockerImage image = context.node().currentDockerImage().get();
if (image.tag().get().startsWith("vespa/ci")) {
return vespaHomeInContainer.resolve("bin64/gdb");
}
else {
return Paths.get("/opt/rh/devtoolset-9/root/bin/gdb");
}
} | DockerImage image = context.node().currentDockerImage().get(); | Path GDBPath(NodeAgentContext context) {
Optional<DockerImage> image = context.node().currentDockerImage();
if (image.isPresent() && image.get().repository().endsWith("vespa/ci")) {
return context.pathInNodeUnderVespaHome("bin64/gdb");
}
else {
return Paths.get("/opt/rh/devtoolset-9/root/bin/gdb");
}
} | class CoreCollector {
private static final Logger logger = Logger.getLogger(CoreCollector.class.getName());
private static final Pattern CORE_GENERATOR_PATH_PATTERN = Pattern.compile("^Core was generated by `(?<path>.*?)'.$");
private static final Pattern EXECFN_PATH_PATTERN = Pattern.compile("^.* execfn: '(?<path>.*?)'");
private static final Pattern FROM_PATH_PATTERN = Pattern.compile("^.* from '(?<path>.*?)'");
private final DockerOperations docker;
private final Path vespaHomeInContainer;
public CoreCollector(DockerOperations docker, Path vespaHomeInContainer) {
this.docker = docker;
this.vespaHomeInContainer = vespaHomeInContainer;
}
Path readBinPathFallback(NodeAgentContext context, Path coredumpPath) {
String command = GDBPath(context).toString()
+ " -n -batch -core " + coredumpPath + " | grep \'^Core was generated by\'";
String[] wrappedCommand = {"/bin/sh", "-c", command};
ProcessResult result = docker.executeCommandInContainerAsRoot(context, wrappedCommand);
Matcher matcher = CORE_GENERATOR_PATH_PATTERN.matcher(result.getOutput());
if (! matcher.find()) {
throw new RuntimeException(String.format("Failed to extract binary path from GDB, result: %s, command: %s",
result, Arrays.toString(wrappedCommand)));
}
return Paths.get(matcher.group("path").split(" ")[0]);
}
Path readBinPath(NodeAgentContext context, Path coredumpPath) {
String[] command = {"file", coredumpPath.toString()};
try {
ProcessResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitStatus() != 0) {
throw new RuntimeException("file command failed with " + result);
}
Matcher execfnMatcher = EXECFN_PATH_PATTERN.matcher(result.getOutput());
if (execfnMatcher.find()) {
return Paths.get(execfnMatcher.group("path").split(" ")[0]);
}
Matcher fromMatcher = FROM_PATH_PATTERN.matcher(result.getOutput());
if (fromMatcher.find()) {
return Paths.get(fromMatcher.group("path").split(" ")[0]);
}
} catch (RuntimeException e) {
context.log(logger, Level.WARNING, String.format("Failed getting bin path, command: %s. " +
"Trying fallback instead", Arrays.toString(command)), e);
}
return readBinPathFallback(context, coredumpPath);
}
List<String> readBacktrace(NodeAgentContext context, Path coredumpPath, Path binPath, boolean allThreads) {
String threads = allThreads ? "thread apply all bt" : "bt";
String[] command = {GDBPath(context).toString(), "-n", "-ex", threads, "-batch", binPath.toString(), coredumpPath.toString()};
ProcessResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitStatus() != 0)
throw new RuntimeException("Failed to read backtrace " + result + ", Command: " + Arrays.toString(command));
return List.of(result.getOutput().split("\n"));
}
List<String> readJstack(NodeAgentContext context, Path coredumpPath, Path binPath) {
String[] command = {"jhsdb", "jstack", "--exe", binPath.toString(), "--core", coredumpPath.toString()};
ProcessResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitStatus() != 0)
throw new RuntimeException("Failed to read jstack " + result + ", Command: " + Arrays.toString(command));
return List.of(result.getOutput().split("\n"));
}
/**
* Collects metadata about a given core dump
* @param context context of the NodeAgent that owns the core dump
* @param coredumpPath path to core dump file inside the container
* @return map of relevant metadata about the core dump
*/
Map<String, Object> collect(NodeAgentContext context, Path coredumpPath) {
Map<String, Object> data = new HashMap<>();
try {
Path binPath = readBinPath(context, coredumpPath);
data.put("bin_path", binPath.toString());
if (binPath.getFileName().toString().equals("java")) {
data.put("backtrace_all_threads", readJstack(context, coredumpPath, binPath));
} else {
data.put("backtrace", readBacktrace(context, coredumpPath, binPath, false));
data.put("backtrace_all_threads", readBacktrace(context, coredumpPath, binPath, true));
}
} catch (RuntimeException e) {
context.log(logger, Level.WARNING, "Failed to extract backtrace", e);
}
return data;
}
} | class CoreCollector {
private static final Logger logger = Logger.getLogger(CoreCollector.class.getName());
private static final Pattern CORE_GENERATOR_PATH_PATTERN = Pattern.compile("^Core was generated by `(?<path>.*?)'.$");
private static final Pattern EXECFN_PATH_PATTERN = Pattern.compile("^.* execfn: '(?<path>.*?)'");
private static final Pattern FROM_PATH_PATTERN = Pattern.compile("^.* from '(?<path>.*?)'");
private final DockerOperations docker;
public CoreCollector(DockerOperations docker) {
this.docker = docker;
}
Path readBinPathFallback(NodeAgentContext context, Path coredumpPath) {
String command = GDBPath(context).toString()
+ " -n -batch -core " + coredumpPath + " | grep \'^Core was generated by\'";
String[] wrappedCommand = {"/bin/sh", "-c", command};
ProcessResult result = docker.executeCommandInContainerAsRoot(context, wrappedCommand);
Matcher matcher = CORE_GENERATOR_PATH_PATTERN.matcher(result.getOutput());
if (! matcher.find()) {
throw new RuntimeException(String.format("Failed to extract binary path from GDB, result: %s, command: %s",
result, Arrays.toString(wrappedCommand)));
}
return Paths.get(matcher.group("path").split(" ")[0]);
}
Path readBinPath(NodeAgentContext context, Path coredumpPath) {
String[] command = {"file", coredumpPath.toString()};
try {
ProcessResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitStatus() != 0) {
throw new RuntimeException("file command failed with " + result);
}
Matcher execfnMatcher = EXECFN_PATH_PATTERN.matcher(result.getOutput());
if (execfnMatcher.find()) {
return Paths.get(execfnMatcher.group("path").split(" ")[0]);
}
Matcher fromMatcher = FROM_PATH_PATTERN.matcher(result.getOutput());
if (fromMatcher.find()) {
return Paths.get(fromMatcher.group("path").split(" ")[0]);
}
} catch (RuntimeException e) {
context.log(logger, Level.WARNING, String.format("Failed getting bin path, command: %s. " +
"Trying fallback instead", Arrays.toString(command)), e);
}
return readBinPathFallback(context, coredumpPath);
}
List<String> readBacktrace(NodeAgentContext context, Path coredumpPath, Path binPath, boolean allThreads) {
String threads = allThreads ? "thread apply all bt" : "bt";
String[] command = {GDBPath(context).toString(), "-n", "-ex", threads, "-batch", binPath.toString(), coredumpPath.toString()};
ProcessResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitStatus() != 0)
throw new RuntimeException("Failed to read backtrace " + result + ", Command: " + Arrays.toString(command));
return List.of(result.getOutput().split("\n"));
}
List<String> readJstack(NodeAgentContext context, Path coredumpPath, Path binPath) {
String[] command = {"jhsdb", "jstack", "--exe", binPath.toString(), "--core", coredumpPath.toString()};
ProcessResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitStatus() != 0)
throw new RuntimeException("Failed to read jstack " + result + ", Command: " + Arrays.toString(command));
return List.of(result.getOutput().split("\n"));
}
/**
* Collects metadata about a given core dump
* @param context context of the NodeAgent that owns the core dump
* @param coredumpPath path to core dump file inside the container
* @return map of relevant metadata about the core dump
*/
Map<String, Object> collect(NodeAgentContext context, Path coredumpPath) {
Map<String, Object> data = new HashMap<>();
try {
Path binPath = readBinPath(context, coredumpPath);
data.put("bin_path", binPath.toString());
if (binPath.getFileName().toString().equals("java")) {
data.put("backtrace_all_threads", readJstack(context, coredumpPath, binPath));
} else {
data.put("backtrace", readBacktrace(context, coredumpPath, binPath, false));
data.put("backtrace_all_threads", readBacktrace(context, coredumpPath, binPath, true));
}
} catch (RuntimeException e) {
context.log(logger, Level.WARNING, "Failed to extract backtrace", e);
}
return data;
}
} |
I suggest using `context.pathInNodeUnderVespaHome()` and remove the option from constructor | Path GDBPath(NodeAgentContext context) {
DockerImage image = context.node().currentDockerImage().get();
if (image.tag().get().startsWith("vespa/ci")) {
return vespaHomeInContainer.resolve("bin64/gdb");
}
else {
return Paths.get("/opt/rh/devtoolset-9/root/bin/gdb");
}
} | return vespaHomeInContainer.resolve("bin64/gdb"); | Path GDBPath(NodeAgentContext context) {
Optional<DockerImage> image = context.node().currentDockerImage();
if (image.isPresent() && image.get().repository().endsWith("vespa/ci")) {
return context.pathInNodeUnderVespaHome("bin64/gdb");
}
else {
return Paths.get("/opt/rh/devtoolset-9/root/bin/gdb");
}
} | class CoreCollector {
private static final Logger logger = Logger.getLogger(CoreCollector.class.getName());
private static final Pattern CORE_GENERATOR_PATH_PATTERN = Pattern.compile("^Core was generated by `(?<path>.*?)'.$");
private static final Pattern EXECFN_PATH_PATTERN = Pattern.compile("^.* execfn: '(?<path>.*?)'");
private static final Pattern FROM_PATH_PATTERN = Pattern.compile("^.* from '(?<path>.*?)'");
private final DockerOperations docker;
private final Path vespaHomeInContainer;
public CoreCollector(DockerOperations docker, Path vespaHomeInContainer) {
this.docker = docker;
this.vespaHomeInContainer = vespaHomeInContainer;
}
Path readBinPathFallback(NodeAgentContext context, Path coredumpPath) {
String command = GDBPath(context).toString()
+ " -n -batch -core " + coredumpPath + " | grep \'^Core was generated by\'";
String[] wrappedCommand = {"/bin/sh", "-c", command};
ProcessResult result = docker.executeCommandInContainerAsRoot(context, wrappedCommand);
Matcher matcher = CORE_GENERATOR_PATH_PATTERN.matcher(result.getOutput());
if (! matcher.find()) {
throw new RuntimeException(String.format("Failed to extract binary path from GDB, result: %s, command: %s",
result, Arrays.toString(wrappedCommand)));
}
return Paths.get(matcher.group("path").split(" ")[0]);
}
Path readBinPath(NodeAgentContext context, Path coredumpPath) {
String[] command = {"file", coredumpPath.toString()};
try {
ProcessResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitStatus() != 0) {
throw new RuntimeException("file command failed with " + result);
}
Matcher execfnMatcher = EXECFN_PATH_PATTERN.matcher(result.getOutput());
if (execfnMatcher.find()) {
return Paths.get(execfnMatcher.group("path").split(" ")[0]);
}
Matcher fromMatcher = FROM_PATH_PATTERN.matcher(result.getOutput());
if (fromMatcher.find()) {
return Paths.get(fromMatcher.group("path").split(" ")[0]);
}
} catch (RuntimeException e) {
context.log(logger, Level.WARNING, String.format("Failed getting bin path, command: %s. " +
"Trying fallback instead", Arrays.toString(command)), e);
}
return readBinPathFallback(context, coredumpPath);
}
List<String> readBacktrace(NodeAgentContext context, Path coredumpPath, Path binPath, boolean allThreads) {
String threads = allThreads ? "thread apply all bt" : "bt";
String[] command = {GDBPath(context).toString(), "-n", "-ex", threads, "-batch", binPath.toString(), coredumpPath.toString()};
ProcessResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitStatus() != 0)
throw new RuntimeException("Failed to read backtrace " + result + ", Command: " + Arrays.toString(command));
return List.of(result.getOutput().split("\n"));
}
List<String> readJstack(NodeAgentContext context, Path coredumpPath, Path binPath) {
String[] command = {"jhsdb", "jstack", "--exe", binPath.toString(), "--core", coredumpPath.toString()};
ProcessResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitStatus() != 0)
throw new RuntimeException("Failed to read jstack " + result + ", Command: " + Arrays.toString(command));
return List.of(result.getOutput().split("\n"));
}
/**
* Collects metadata about a given core dump
* @param context context of the NodeAgent that owns the core dump
* @param coredumpPath path to core dump file inside the container
* @return map of relevant metadata about the core dump
*/
Map<String, Object> collect(NodeAgentContext context, Path coredumpPath) {
Map<String, Object> data = new HashMap<>();
try {
Path binPath = readBinPath(context, coredumpPath);
data.put("bin_path", binPath.toString());
if (binPath.getFileName().toString().equals("java")) {
data.put("backtrace_all_threads", readJstack(context, coredumpPath, binPath));
} else {
data.put("backtrace", readBacktrace(context, coredumpPath, binPath, false));
data.put("backtrace_all_threads", readBacktrace(context, coredumpPath, binPath, true));
}
} catch (RuntimeException e) {
context.log(logger, Level.WARNING, "Failed to extract backtrace", e);
}
return data;
}
} | class CoreCollector {
private static final Logger logger = Logger.getLogger(CoreCollector.class.getName());
private static final Pattern CORE_GENERATOR_PATH_PATTERN = Pattern.compile("^Core was generated by `(?<path>.*?)'.$");
private static final Pattern EXECFN_PATH_PATTERN = Pattern.compile("^.* execfn: '(?<path>.*?)'");
private static final Pattern FROM_PATH_PATTERN = Pattern.compile("^.* from '(?<path>.*?)'");
private final DockerOperations docker;
public CoreCollector(DockerOperations docker) {
this.docker = docker;
}
Path readBinPathFallback(NodeAgentContext context, Path coredumpPath) {
String command = GDBPath(context).toString()
+ " -n -batch -core " + coredumpPath + " | grep \'^Core was generated by\'";
String[] wrappedCommand = {"/bin/sh", "-c", command};
ProcessResult result = docker.executeCommandInContainerAsRoot(context, wrappedCommand);
Matcher matcher = CORE_GENERATOR_PATH_PATTERN.matcher(result.getOutput());
if (! matcher.find()) {
throw new RuntimeException(String.format("Failed to extract binary path from GDB, result: %s, command: %s",
result, Arrays.toString(wrappedCommand)));
}
return Paths.get(matcher.group("path").split(" ")[0]);
}
Path readBinPath(NodeAgentContext context, Path coredumpPath) {
String[] command = {"file", coredumpPath.toString()};
try {
ProcessResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitStatus() != 0) {
throw new RuntimeException("file command failed with " + result);
}
Matcher execfnMatcher = EXECFN_PATH_PATTERN.matcher(result.getOutput());
if (execfnMatcher.find()) {
return Paths.get(execfnMatcher.group("path").split(" ")[0]);
}
Matcher fromMatcher = FROM_PATH_PATTERN.matcher(result.getOutput());
if (fromMatcher.find()) {
return Paths.get(fromMatcher.group("path").split(" ")[0]);
}
} catch (RuntimeException e) {
context.log(logger, Level.WARNING, String.format("Failed getting bin path, command: %s. " +
"Trying fallback instead", Arrays.toString(command)), e);
}
return readBinPathFallback(context, coredumpPath);
}
List<String> readBacktrace(NodeAgentContext context, Path coredumpPath, Path binPath, boolean allThreads) {
String threads = allThreads ? "thread apply all bt" : "bt";
String[] command = {GDBPath(context).toString(), "-n", "-ex", threads, "-batch", binPath.toString(), coredumpPath.toString()};
ProcessResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitStatus() != 0)
throw new RuntimeException("Failed to read backtrace " + result + ", Command: " + Arrays.toString(command));
return List.of(result.getOutput().split("\n"));
}
List<String> readJstack(NodeAgentContext context, Path coredumpPath, Path binPath) {
String[] command = {"jhsdb", "jstack", "--exe", binPath.toString(), "--core", coredumpPath.toString()};
ProcessResult result = docker.executeCommandInContainerAsRoot(context, command);
if (result.getExitStatus() != 0)
throw new RuntimeException("Failed to read jstack " + result + ", Command: " + Arrays.toString(command));
return List.of(result.getOutput().split("\n"));
}
/**
* Collects metadata about a given core dump
* @param context context of the NodeAgent that owns the core dump
* @param coredumpPath path to core dump file inside the container
* @return map of relevant metadata about the core dump
*/
Map<String, Object> collect(NodeAgentContext context, Path coredumpPath) {
Map<String, Object> data = new HashMap<>();
try {
Path binPath = readBinPath(context, coredumpPath);
data.put("bin_path", binPath.toString());
if (binPath.getFileName().toString().equals("java")) {
data.put("backtrace_all_threads", readJstack(context, coredumpPath, binPath));
} else {
data.put("backtrace", readBacktrace(context, coredumpPath, binPath, false));
data.put("backtrace_all_threads", readBacktrace(context, coredumpPath, binPath, true));
}
} catch (RuntimeException e) {
context.log(logger, Level.WARNING, "Failed to extract backtrace", e);
}
return data;
}
} |
Do we need any special handling of `candidateA == candidateB`? | Node getRecipient(List<Mirror.Entry> choices) {
if (choices.isEmpty()) return null;
Mirror.Entry entry;
NodeMetrics metrics;
if (choices.size() == 1) {
entry = choices.get(0);
metrics = getNodeMetrics(entry);
} else {
int candidateA = 0;
int candidateB = 1;
if (choices.size() > 2) {
candidateA = random.nextInt(choices.size());
candidateB = random.nextInt(choices.size());
}
entry = choices.get(candidateA);
Mirror.Entry entryB = choices.get(candidateB);
metrics = getNodeMetrics(entry);
NodeMetrics metricsB = getNodeMetrics(entryB);
if (metrics.pending() > metricsB.pending()) {
entry = entryB;
metrics = metricsB;
}
}
metrics.incSend();
return new Node(entry, metrics);
} | } | Node getRecipient(List<Mirror.Entry> choices) {
if (choices.isEmpty()) return null;
Mirror.Entry entry;
NodeMetrics metrics;
if (choices.size() == 1) {
entry = choices.get(0);
metrics = getNodeMetrics(entry);
} else {
int candA = 0;
int candB = 1;
if (choices.size() > 2) {
candA = random.nextInt(choices.size());
candB = random.nextInt(choices.size());
while (candB == candA) {
candB = random.nextInt(choices.size());
}
}
entry = choices.get(candA);
Mirror.Entry entryB = choices.get(candB);
metrics = getNodeMetrics(entry);
NodeMetrics metricsB = getNodeMetrics(entryB);
if (metrics.pending() > metricsB.pending()) {
entry = entryB;
metrics = metricsB;
}
}
metrics.incSend();
return new Node(entry, metrics);
} | class AdaptiveLoadBalancer extends LoadBalancer {
private Random random = new Random();
AdaptiveLoadBalancer(String cluster) {
super(cluster);
}
@Override
@Override
void received(Node node, boolean busy) {
node.metrics.incReceived();
if (busy) {
node.metrics.incBusy();
}
}
} | class AdaptiveLoadBalancer extends LoadBalancer {
private final Random random;
AdaptiveLoadBalancer(String cluster) {
this(cluster, new Random());
}
AdaptiveLoadBalancer(String cluster, Random random) {
super(cluster);
this.random = random;
}
@Override
@Override
void received(Node node, boolean busy) {
node.metrics.incReceived();
if (busy) {
node.metrics.incBusy();
}
}
} |
Nit: some inconsistent spacing here | public void testAdaptiveLoadBalancer() {
LoadBalancer lb = new AdaptiveLoadBalancer("foo");
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
}
long sentSum = 0;
for (var metrics : weights) {
assertTrue(10 > Math.abs(metrics.sent() - 3333));
sentSum += metrics.sent();
}
assertEquals(9999, sentSum);
for (var metrics : weights) {
metrics.reset();
}
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
if (node.entry.getName().contains("1")) {
lb.received(node, false);
} else if (node.entry.getName().contains("2")) {
if ((i % 2) == 0) {
lb.received(node, false);
}
} else {
if ((i % 4) == 0) {
lb.received(node, false);
}
}
}
sentSum = 0;
long sumPending = 0;
for (var metrics : weights) {
System.out.println("m: s=" + metrics.sent() + " p=" + metrics.pending());
sentSum += metrics.sent();
sumPending += metrics.pending();
}
assertEquals(9999, sentSum);
assertTrue(200 > Math.abs(sumPending - 2700));
assertTrue( 100 > Math.abs(weights.get(0).sent() - 1780));
assertTrue( 200 > Math.abs(weights.get(1).sent() - 5500));
assertTrue( 100 > Math.abs(weights.get(2).sent() - 2650));
assertTrue( 100 > Math.abs(weights.get(0).pending() - 1340));
assertEquals( 0, weights.get(1).pending());
assertTrue( 100 > Math.abs(weights.get(2).pending() - 1340));
} | assertTrue( 100 > Math.abs(weights.get(0).sent() - 1780)); | public void testAdaptiveLoadBalancer() {
LoadBalancer lb = new AdaptiveLoadBalancer("foo", new Random(1));
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
}
long sentSum = 0;
for (var metrics : weights) {
assertTrue(10 > Math.abs(metrics.sent() - 3333));
sentSum += metrics.sent();
}
assertEquals(9999, sentSum);
for (var metrics : weights) {
metrics.reset();
}
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
if (node.entry.getName().contains("1")) {
lb.received(node, false);
} else if (node.entry.getName().contains("2")) {
if ((i % 2) == 0) {
lb.received(node, false);
}
} else {
if ((i % 4) == 0) {
lb.received(node, false);
}
}
}
sentSum = 0;
long sumPending = 0;
for (var metrics : weights) {
System.out.println("m: s=" + metrics.sent() + " p=" + metrics.pending());
sentSum += metrics.sent();
sumPending += metrics.pending();
}
assertEquals(9999, sentSum);
assertEquals(2039, sumPending);
assertEquals(1332, weights.get(0).sent());
assertEquals(6645, weights.get(1).sent());
assertEquals(2022, weights.get(2).sent());
assertEquals(1020, weights.get(0).pending());
assertEquals(0, weights.get(1).pending());
assertEquals(1019, weights.get(2).pending());
} | class LoadBalancerTestCase {
@Test
public void requireThatParseExceptionIsReadable() {
assertIllegalArgument("foo", "bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'bar'.");
assertIllegalArgument("foo", "foobar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foobar'.");
assertIllegalArgument("foo", "foo", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo'.");
assertIllegalArgument("foo", "foo/", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/'.");
assertIllegalArgument("foo", "foo/0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0'.");
assertIllegalArgument("foo", "foo/0.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.'.");
assertIllegalArgument("foo", "foo/0.bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.bar'.");
assertIllegalArgument("foo", "foo/bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar'.");
assertIllegalArgument("foo", "foo/bar.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.'.");
assertIllegalArgument("foo", "foo/bar.0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.0'.");
}
private static void assertIllegalArgument(String clusterName, String recipient, String expectedMessage) {
LegacyLoadBalancer policy = new LegacyLoadBalancer(clusterName);
try {
fail("Expected exception, got index " + policy.getIndex(recipient) + ".");
} catch (IllegalArgumentException e) {
assertEquals(expectedMessage, e.getMessage());
}
}
@Test
public void testLoadBalancerCreation() {
LoadBalancerPolicy lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=legacy");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=adaptive");
assertTrue(lbp.getLoadBalancer() instanceof AdaptiveLoadBalancer);
}
@Test
@Test
public void testLegacyLoadBalancer() {
LoadBalancer lb = new LegacyLoadBalancer("foo");
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
{
for (int i = 0; i < 99; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertEquals("foo/" + (i % 3) + "/default" , node.entry.getName());
}
assertEquals(33, weights.get(0).sent());
assertEquals(33, weights.get(1).sent());
assertEquals(33, weights.get(2).sent());
weights.get(0).reset();
weights.get(1).reset();
weights.get(2).reset();
}
{
for (int i = 0; i < 100; i++) {
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), false);
}
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(0)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(100, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(2)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
}
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/1/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
private void verifyLoadBalancerOneItemOnly(LoadBalancer lb) {
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1") );
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
@Test
public void testLoadBalancerOneItemOnly() {
verifyLoadBalancerOneItemOnly(new LegacyLoadBalancer("foo"));
verifyLoadBalancerOneItemOnly(new AdaptiveLoadBalancer("foo"));
}
} | class LoadBalancerTestCase {
@Test
public void requireThatParseExceptionIsReadable() {
assertIllegalArgument("foo", "bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'bar'.");
assertIllegalArgument("foo", "foobar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foobar'.");
assertIllegalArgument("foo", "foo", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo'.");
assertIllegalArgument("foo", "foo/", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/'.");
assertIllegalArgument("foo", "foo/0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0'.");
assertIllegalArgument("foo", "foo/0.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.'.");
assertIllegalArgument("foo", "foo/0.bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.bar'.");
assertIllegalArgument("foo", "foo/bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar'.");
assertIllegalArgument("foo", "foo/bar.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.'.");
assertIllegalArgument("foo", "foo/bar.0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.0'.");
}
private static void assertIllegalArgument(String clusterName, String recipient, String expectedMessage) {
LegacyLoadBalancer policy = new LegacyLoadBalancer(clusterName);
try {
fail("Expected exception, got index " + policy.getIndex(recipient) + ".");
} catch (IllegalArgumentException e) {
assertEquals(expectedMessage, e.getMessage());
}
}
@Test
public void testLoadBalancerCreation() {
LoadBalancerPolicy lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=legacy");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=adaptive");
assertTrue(lbp.getLoadBalancer() instanceof AdaptiveLoadBalancer);
}
@Test
@Test
public void testLegacyLoadBalancer() {
LoadBalancer lb = new LegacyLoadBalancer("foo");
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
{
for (int i = 0; i < 99; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertEquals("foo/" + (i % 3) + "/default" , node.entry.getName());
}
assertEquals(33, weights.get(0).sent());
assertEquals(33, weights.get(1).sent());
assertEquals(33, weights.get(2).sent());
weights.get(0).reset();
weights.get(1).reset();
weights.get(2).reset();
}
{
for (int i = 0; i < 100; i++) {
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), false);
}
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(0)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(100, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(2)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
}
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/1/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
private void verifyLoadBalancerOneItemOnly(LoadBalancer lb) {
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1") );
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
@Test
public void testLoadBalancerOneItemOnly() {
verifyLoadBalancerOneItemOnly(new LegacyLoadBalancer("foo"));
verifyLoadBalancerOneItemOnly(new AdaptiveLoadBalancer("foo"));
}
} |
Should use `equals()` instead of `==`. Also consider flipping argument order to implicitly handle `type == null` in case no balancer type is present. | private LoadBalancerPolicy(Map<String, String> params) {
super();
String cluster = params.get("cluster");
session = params.get("session");
if (cluster == null) {
throw new IllegalArgumentException("Required parameter 'cluster' not set");
}
if (session == null) {
throw new IllegalArgumentException("Required parameter 'session' not set");
}
pattern = cluster + "/*/" + session;
String type = params.get("type");
if (type == "adaptive") {
loadBalancer = new AdaptiveLoadBalancer(cluster);
} else if (type == "legacy") {
loadBalancer = new LegacyLoadBalancer(cluster);
} else {
loadBalancer = new LegacyLoadBalancer(cluster);
}
} | if (type == "adaptive") { | private LoadBalancerPolicy(Map<String, String> params) {
super();
String cluster = params.get("cluster");
session = params.get("session");
if (cluster == null) {
throw new IllegalArgumentException("Required parameter 'cluster' not set");
}
if (session == null) {
throw new IllegalArgumentException("Required parameter 'session' not set");
}
pattern = cluster + "/*/" + session;
String type = params.get("type");
if ("adaptive".equals(type)) {
loadBalancer = new AdaptiveLoadBalancer(cluster);
} else if ("legacy".equals(type)) {
loadBalancer = new LegacyLoadBalancer(cluster);
} else {
loadBalancer = new LegacyLoadBalancer(cluster);
}
} | class LoadBalancerPolicy extends SlobrokPolicy {
private final String session;
private final String pattern;
private final LoadBalancer loadBalancer;
LoadBalancerPolicy(String param) {
this(parse(param));
}
@Override
public void select(RoutingContext context) {
LegacyLoadBalancer.Node node = getRecipient(context);
if (node != null) {
context.setContext(node);
Route route = new Route(context.getRoute());
route.setHop(0, Hop.parse(node.entry.getSpecString() + "/" + session));
context.addChild(route);
} else {
context.setError(ErrorCode.NO_ADDRESS_FOR_SERVICE, "Could not resolve any nodes to send to in pattern " + pattern);
}
}
/**
Finds the TCP address of the target.
@return Returns a hop representing the TCP address of the target, or null if none could be found.
*/
private LegacyLoadBalancer.Node getRecipient(RoutingContext context) {
List<Mirror.Entry> lastLookup = lookup(context, pattern);
return loadBalancer.getRecipient(lastLookup);
}
public void merge(RoutingContext context) {
RoutingNodeIterator it = context.getChildIterator();
Reply reply = it.removeReply();
LegacyLoadBalancer.Node target = (LegacyLoadBalancer.Node)context.getContext();
boolean busy = false;
for (int i = 0; i < reply.getNumErrors(); i++) {
if (reply.getError(i).getCode() == ErrorCode.SESSION_BUSY) {
busy = true;
}
}
loadBalancer.received(target, busy);
context.setReply(reply);
}
@Override
public void destroy() {
}
} | class LoadBalancerPolicy extends SlobrokPolicy {
private final String session;
private final String pattern;
private final LoadBalancer loadBalancer;
LoadBalancerPolicy(String param) {
this(parse(param));
}
@Override
public void select(RoutingContext context) {
LegacyLoadBalancer.Node node = getRecipient(context);
if (node != null) {
context.setContext(node);
Route route = new Route(context.getRoute());
route.setHop(0, Hop.parse(node.entry.getSpecString() + "/" + session));
context.addChild(route);
} else {
context.setError(ErrorCode.NO_ADDRESS_FOR_SERVICE, "Could not resolve any nodes to send to in pattern " + pattern);
}
}
/**
Finds the TCP address of the target.
@return Returns a hop representing the TCP address of the target, or null if none could be found.
*/
private LegacyLoadBalancer.Node getRecipient(RoutingContext context) {
List<Mirror.Entry> lastLookup = lookup(context, pattern);
return loadBalancer.getRecipient(lastLookup);
}
public void merge(RoutingContext context) {
RoutingNodeIterator it = context.getChildIterator();
Reply reply = it.removeReply();
LegacyLoadBalancer.Node target = (LegacyLoadBalancer.Node)context.getContext();
boolean busy = false;
for (int i = 0; i < reply.getNumErrors(); i++) {
if (reply.getError(i).getCode() == ErrorCode.SESSION_BUSY) {
busy = true;
}
}
loadBalancer.received(target, busy);
context.setReply(reply);
}
@Override
public void destroy() {
}
LoadBalancer getLoadBalancer() { return loadBalancer; }
} |
Nevermind, I see this was fixed prior to me submitting this 🙂 | private LoadBalancerPolicy(Map<String, String> params) {
super();
String cluster = params.get("cluster");
session = params.get("session");
if (cluster == null) {
throw new IllegalArgumentException("Required parameter 'cluster' not set");
}
if (session == null) {
throw new IllegalArgumentException("Required parameter 'session' not set");
}
pattern = cluster + "/*/" + session;
String type = params.get("type");
if (type == "adaptive") {
loadBalancer = new AdaptiveLoadBalancer(cluster);
} else if (type == "legacy") {
loadBalancer = new LegacyLoadBalancer(cluster);
} else {
loadBalancer = new LegacyLoadBalancer(cluster);
}
} | if (type == "adaptive") { | private LoadBalancerPolicy(Map<String, String> params) {
super();
String cluster = params.get("cluster");
session = params.get("session");
if (cluster == null) {
throw new IllegalArgumentException("Required parameter 'cluster' not set");
}
if (session == null) {
throw new IllegalArgumentException("Required parameter 'session' not set");
}
pattern = cluster + "/*/" + session;
String type = params.get("type");
if ("adaptive".equals(type)) {
loadBalancer = new AdaptiveLoadBalancer(cluster);
} else if ("legacy".equals(type)) {
loadBalancer = new LegacyLoadBalancer(cluster);
} else {
loadBalancer = new LegacyLoadBalancer(cluster);
}
} | class LoadBalancerPolicy extends SlobrokPolicy {
private final String session;
private final String pattern;
private final LoadBalancer loadBalancer;
LoadBalancerPolicy(String param) {
this(parse(param));
}
@Override
public void select(RoutingContext context) {
LegacyLoadBalancer.Node node = getRecipient(context);
if (node != null) {
context.setContext(node);
Route route = new Route(context.getRoute());
route.setHop(0, Hop.parse(node.entry.getSpecString() + "/" + session));
context.addChild(route);
} else {
context.setError(ErrorCode.NO_ADDRESS_FOR_SERVICE, "Could not resolve any nodes to send to in pattern " + pattern);
}
}
/**
Finds the TCP address of the target.
@return Returns a hop representing the TCP address of the target, or null if none could be found.
*/
private LegacyLoadBalancer.Node getRecipient(RoutingContext context) {
List<Mirror.Entry> lastLookup = lookup(context, pattern);
return loadBalancer.getRecipient(lastLookup);
}
public void merge(RoutingContext context) {
RoutingNodeIterator it = context.getChildIterator();
Reply reply = it.removeReply();
LegacyLoadBalancer.Node target = (LegacyLoadBalancer.Node)context.getContext();
boolean busy = false;
for (int i = 0; i < reply.getNumErrors(); i++) {
if (reply.getError(i).getCode() == ErrorCode.SESSION_BUSY) {
busy = true;
}
}
loadBalancer.received(target, busy);
context.setReply(reply);
}
@Override
public void destroy() {
}
} | class LoadBalancerPolicy extends SlobrokPolicy {
private final String session;
private final String pattern;
private final LoadBalancer loadBalancer;
LoadBalancerPolicy(String param) {
this(parse(param));
}
@Override
public void select(RoutingContext context) {
LegacyLoadBalancer.Node node = getRecipient(context);
if (node != null) {
context.setContext(node);
Route route = new Route(context.getRoute());
route.setHop(0, Hop.parse(node.entry.getSpecString() + "/" + session));
context.addChild(route);
} else {
context.setError(ErrorCode.NO_ADDRESS_FOR_SERVICE, "Could not resolve any nodes to send to in pattern " + pattern);
}
}
/**
Finds the TCP address of the target.
@return Returns a hop representing the TCP address of the target, or null if none could be found.
*/
private LegacyLoadBalancer.Node getRecipient(RoutingContext context) {
List<Mirror.Entry> lastLookup = lookup(context, pattern);
return loadBalancer.getRecipient(lastLookup);
}
public void merge(RoutingContext context) {
RoutingNodeIterator it = context.getChildIterator();
Reply reply = it.removeReply();
LegacyLoadBalancer.Node target = (LegacyLoadBalancer.Node)context.getContext();
boolean busy = false;
for (int i = 0; i < reply.getNumErrors(); i++) {
if (reply.getError(i).getCode() == ErrorCode.SESSION_BUSY) {
busy = true;
}
}
loadBalancer.received(target, busy);
context.setReply(reply);
}
@Override
public void destroy() {
}
LoadBalancer getLoadBalancer() { return loadBalancer; }
} |
Fixed | public void testAdaptiveLoadBalancer() {
LoadBalancer lb = new AdaptiveLoadBalancer("foo");
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
}
long sentSum = 0;
for (var metrics : weights) {
assertTrue(10 > Math.abs(metrics.sent() - 3333));
sentSum += metrics.sent();
}
assertEquals(9999, sentSum);
for (var metrics : weights) {
metrics.reset();
}
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
if (node.entry.getName().contains("1")) {
lb.received(node, false);
} else if (node.entry.getName().contains("2")) {
if ((i % 2) == 0) {
lb.received(node, false);
}
} else {
if ((i % 4) == 0) {
lb.received(node, false);
}
}
}
sentSum = 0;
long sumPending = 0;
for (var metrics : weights) {
System.out.println("m: s=" + metrics.sent() + " p=" + metrics.pending());
sentSum += metrics.sent();
sumPending += metrics.pending();
}
assertEquals(9999, sentSum);
assertTrue(200 > Math.abs(sumPending - 2700));
assertTrue( 100 > Math.abs(weights.get(0).sent() - 1780));
assertTrue( 200 > Math.abs(weights.get(1).sent() - 5500));
assertTrue( 100 > Math.abs(weights.get(2).sent() - 2650));
assertTrue( 100 > Math.abs(weights.get(0).pending() - 1340));
assertEquals( 0, weights.get(1).pending());
assertTrue( 100 > Math.abs(weights.get(2).pending() - 1340));
} | assertTrue( 100 > Math.abs(weights.get(0).sent() - 1780)); | public void testAdaptiveLoadBalancer() {
LoadBalancer lb = new AdaptiveLoadBalancer("foo", new Random(1));
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
}
long sentSum = 0;
for (var metrics : weights) {
assertTrue(10 > Math.abs(metrics.sent() - 3333));
sentSum += metrics.sent();
}
assertEquals(9999, sentSum);
for (var metrics : weights) {
metrics.reset();
}
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
if (node.entry.getName().contains("1")) {
lb.received(node, false);
} else if (node.entry.getName().contains("2")) {
if ((i % 2) == 0) {
lb.received(node, false);
}
} else {
if ((i % 4) == 0) {
lb.received(node, false);
}
}
}
sentSum = 0;
long sumPending = 0;
for (var metrics : weights) {
System.out.println("m: s=" + metrics.sent() + " p=" + metrics.pending());
sentSum += metrics.sent();
sumPending += metrics.pending();
}
assertEquals(9999, sentSum);
assertEquals(2039, sumPending);
assertEquals(1332, weights.get(0).sent());
assertEquals(6645, weights.get(1).sent());
assertEquals(2022, weights.get(2).sent());
assertEquals(1020, weights.get(0).pending());
assertEquals(0, weights.get(1).pending());
assertEquals(1019, weights.get(2).pending());
} | class LoadBalancerTestCase {
@Test
public void requireThatParseExceptionIsReadable() {
assertIllegalArgument("foo", "bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'bar'.");
assertIllegalArgument("foo", "foobar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foobar'.");
assertIllegalArgument("foo", "foo", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo'.");
assertIllegalArgument("foo", "foo/", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/'.");
assertIllegalArgument("foo", "foo/0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0'.");
assertIllegalArgument("foo", "foo/0.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.'.");
assertIllegalArgument("foo", "foo/0.bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.bar'.");
assertIllegalArgument("foo", "foo/bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar'.");
assertIllegalArgument("foo", "foo/bar.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.'.");
assertIllegalArgument("foo", "foo/bar.0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.0'.");
}
private static void assertIllegalArgument(String clusterName, String recipient, String expectedMessage) {
LegacyLoadBalancer policy = new LegacyLoadBalancer(clusterName);
try {
fail("Expected exception, got index " + policy.getIndex(recipient) + ".");
} catch (IllegalArgumentException e) {
assertEquals(expectedMessage, e.getMessage());
}
}
@Test
public void testLoadBalancerCreation() {
LoadBalancerPolicy lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=legacy");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=adaptive");
assertTrue(lbp.getLoadBalancer() instanceof AdaptiveLoadBalancer);
}
@Test
@Test
public void testLegacyLoadBalancer() {
LoadBalancer lb = new LegacyLoadBalancer("foo");
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
{
for (int i = 0; i < 99; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertEquals("foo/" + (i % 3) + "/default" , node.entry.getName());
}
assertEquals(33, weights.get(0).sent());
assertEquals(33, weights.get(1).sent());
assertEquals(33, weights.get(2).sent());
weights.get(0).reset();
weights.get(1).reset();
weights.get(2).reset();
}
{
for (int i = 0; i < 100; i++) {
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), false);
}
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(0)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(100, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(2)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
}
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/1/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
private void verifyLoadBalancerOneItemOnly(LoadBalancer lb) {
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1") );
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
@Test
public void testLoadBalancerOneItemOnly() {
verifyLoadBalancerOneItemOnly(new LegacyLoadBalancer("foo"));
verifyLoadBalancerOneItemOnly(new AdaptiveLoadBalancer("foo"));
}
} | class LoadBalancerTestCase {
@Test
public void requireThatParseExceptionIsReadable() {
assertIllegalArgument("foo", "bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'bar'.");
assertIllegalArgument("foo", "foobar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foobar'.");
assertIllegalArgument("foo", "foo", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo'.");
assertIllegalArgument("foo", "foo/", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/'.");
assertIllegalArgument("foo", "foo/0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0'.");
assertIllegalArgument("foo", "foo/0.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.'.");
assertIllegalArgument("foo", "foo/0.bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.bar'.");
assertIllegalArgument("foo", "foo/bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar'.");
assertIllegalArgument("foo", "foo/bar.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.'.");
assertIllegalArgument("foo", "foo/bar.0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.0'.");
}
private static void assertIllegalArgument(String clusterName, String recipient, String expectedMessage) {
LegacyLoadBalancer policy = new LegacyLoadBalancer(clusterName);
try {
fail("Expected exception, got index " + policy.getIndex(recipient) + ".");
} catch (IllegalArgumentException e) {
assertEquals(expectedMessage, e.getMessage());
}
}
@Test
public void testLoadBalancerCreation() {
LoadBalancerPolicy lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=legacy");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=adaptive");
assertTrue(lbp.getLoadBalancer() instanceof AdaptiveLoadBalancer);
}
@Test
@Test
public void testLegacyLoadBalancer() {
LoadBalancer lb = new LegacyLoadBalancer("foo");
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
{
for (int i = 0; i < 99; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertEquals("foo/" + (i % 3) + "/default" , node.entry.getName());
}
assertEquals(33, weights.get(0).sent());
assertEquals(33, weights.get(1).sent());
assertEquals(33, weights.get(2).sent());
weights.get(0).reset();
weights.get(1).reset();
weights.get(2).reset();
}
{
for (int i = 0; i < 100; i++) {
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), false);
}
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(0)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(100, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(2)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
}
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/1/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
private void verifyLoadBalancerOneItemOnly(LoadBalancer lb) {
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1") );
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
@Test
public void testLoadBalancerOneItemOnly() {
verifyLoadBalancerOneItemOnly(new LegacyLoadBalancer("foo"));
verifyLoadBalancerOneItemOnly(new AdaptiveLoadBalancer("foo"));
}
} |
Fixed, I also changed the test to use equals as the results are repeatable. | public void testAdaptiveLoadBalancer() {
LoadBalancer lb = new AdaptiveLoadBalancer("foo");
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
}
long sentSum = 0;
for (var metrics : weights) {
assertTrue(10 > Math.abs(metrics.sent() - 3333));
sentSum += metrics.sent();
}
assertEquals(9999, sentSum);
for (var metrics : weights) {
metrics.reset();
}
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
if (node.entry.getName().contains("1")) {
lb.received(node, false);
} else if (node.entry.getName().contains("2")) {
if ((i % 2) == 0) {
lb.received(node, false);
}
} else {
if ((i % 4) == 0) {
lb.received(node, false);
}
}
}
sentSum = 0;
long sumPending = 0;
for (var metrics : weights) {
System.out.println("m: s=" + metrics.sent() + " p=" + metrics.pending());
sentSum += metrics.sent();
sumPending += metrics.pending();
}
assertEquals(9999, sentSum);
assertTrue(200 > Math.abs(sumPending - 2700));
assertTrue( 100 > Math.abs(weights.get(0).sent() - 1780));
assertTrue( 200 > Math.abs(weights.get(1).sent() - 5500));
assertTrue( 100 > Math.abs(weights.get(2).sent() - 2650));
assertTrue( 100 > Math.abs(weights.get(0).pending() - 1340));
assertEquals( 0, weights.get(1).pending());
assertTrue( 100 > Math.abs(weights.get(2).pending() - 1340));
} | assertTrue(10 > Math.abs(metrics.sent() - 3333)); | public void testAdaptiveLoadBalancer() {
LoadBalancer lb = new AdaptiveLoadBalancer("foo", new Random(1));
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
}
long sentSum = 0;
for (var metrics : weights) {
assertTrue(10 > Math.abs(metrics.sent() - 3333));
sentSum += metrics.sent();
}
assertEquals(9999, sentSum);
for (var metrics : weights) {
metrics.reset();
}
for (int i = 0; i < 9999; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertNotNull(node);
if (node.entry.getName().contains("1")) {
lb.received(node, false);
} else if (node.entry.getName().contains("2")) {
if ((i % 2) == 0) {
lb.received(node, false);
}
} else {
if ((i % 4) == 0) {
lb.received(node, false);
}
}
}
sentSum = 0;
long sumPending = 0;
for (var metrics : weights) {
System.out.println("m: s=" + metrics.sent() + " p=" + metrics.pending());
sentSum += metrics.sent();
sumPending += metrics.pending();
}
assertEquals(9999, sentSum);
assertEquals(2039, sumPending);
assertEquals(1332, weights.get(0).sent());
assertEquals(6645, weights.get(1).sent());
assertEquals(2022, weights.get(2).sent());
assertEquals(1020, weights.get(0).pending());
assertEquals(0, weights.get(1).pending());
assertEquals(1019, weights.get(2).pending());
} | class LoadBalancerTestCase {
@Test
public void requireThatParseExceptionIsReadable() {
assertIllegalArgument("foo", "bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'bar'.");
assertIllegalArgument("foo", "foobar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foobar'.");
assertIllegalArgument("foo", "foo", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo'.");
assertIllegalArgument("foo", "foo/", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/'.");
assertIllegalArgument("foo", "foo/0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0'.");
assertIllegalArgument("foo", "foo/0.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.'.");
assertIllegalArgument("foo", "foo/0.bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.bar'.");
assertIllegalArgument("foo", "foo/bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar'.");
assertIllegalArgument("foo", "foo/bar.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.'.");
assertIllegalArgument("foo", "foo/bar.0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.0'.");
}
private static void assertIllegalArgument(String clusterName, String recipient, String expectedMessage) {
LegacyLoadBalancer policy = new LegacyLoadBalancer(clusterName);
try {
fail("Expected exception, got index " + policy.getIndex(recipient) + ".");
} catch (IllegalArgumentException e) {
assertEquals(expectedMessage, e.getMessage());
}
}
@Test
public void testLoadBalancerCreation() {
LoadBalancerPolicy lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=legacy");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=adaptive");
assertTrue(lbp.getLoadBalancer() instanceof AdaptiveLoadBalancer);
}
@Test
@Test
public void testLegacyLoadBalancer() {
LoadBalancer lb = new LegacyLoadBalancer("foo");
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
{
for (int i = 0; i < 99; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertEquals("foo/" + (i % 3) + "/default" , node.entry.getName());
}
assertEquals(33, weights.get(0).sent());
assertEquals(33, weights.get(1).sent());
assertEquals(33, weights.get(2).sent());
weights.get(0).reset();
weights.get(1).reset();
weights.get(2).reset();
}
{
for (int i = 0; i < 100; i++) {
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), false);
}
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(0)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(100, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(2)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
}
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/1/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
private void verifyLoadBalancerOneItemOnly(LoadBalancer lb) {
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1") );
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
@Test
public void testLoadBalancerOneItemOnly() {
verifyLoadBalancerOneItemOnly(new LegacyLoadBalancer("foo"));
verifyLoadBalancerOneItemOnly(new AdaptiveLoadBalancer("foo"));
}
} | class LoadBalancerTestCase {
@Test
public void requireThatParseExceptionIsReadable() {
assertIllegalArgument("foo", "bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'bar'.");
assertIllegalArgument("foo", "foobar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foobar'.");
assertIllegalArgument("foo", "foo", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo'.");
assertIllegalArgument("foo", "foo/", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/'.");
assertIllegalArgument("foo", "foo/0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0'.");
assertIllegalArgument("foo", "foo/0.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.'.");
assertIllegalArgument("foo", "foo/0.bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/0.bar'.");
assertIllegalArgument("foo", "foo/bar", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar'.");
assertIllegalArgument("foo", "foo/bar.", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.'.");
assertIllegalArgument("foo", "foo/bar.0", "Expected recipient on the form 'foo/x/[y.]number/z', got 'foo/bar.0'.");
}
private static void assertIllegalArgument(String clusterName, String recipient, String expectedMessage) {
LegacyLoadBalancer policy = new LegacyLoadBalancer(clusterName);
try {
fail("Expected exception, got index " + policy.getIndex(recipient) + ".");
} catch (IllegalArgumentException e) {
assertEquals(expectedMessage, e.getMessage());
}
}
@Test
public void testLoadBalancerCreation() {
LoadBalancerPolicy lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=legacy");
assertTrue(lbp.getLoadBalancer() instanceof LegacyLoadBalancer);
lbp = new LoadBalancerPolicy("cluster=docproc/cluster.mobile.indexing;session=chain.mobile.indexing;type=adaptive");
assertTrue(lbp.getLoadBalancer() instanceof AdaptiveLoadBalancer);
}
@Test
@Test
public void testLegacyLoadBalancer() {
LoadBalancer lb = new LegacyLoadBalancer("foo");
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"),
new Mirror.Entry("foo/1/default", "tcp/bar:2"),
new Mirror.Entry("foo/2/default", "tcp/bar:3"));
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
{
for (int i = 0; i < 99; i++) {
LoadBalancer.Node node = lb.getRecipient(entries);
assertEquals("foo/" + (i % 3) + "/default" , node.entry.getName());
}
assertEquals(33, weights.get(0).sent());
assertEquals(33, weights.get(1).sent());
assertEquals(33, weights.get(2).sent());
weights.get(0).reset();
weights.get(1).reset();
weights.get(2).reset();
}
{
for (int i = 0; i < 100; i++) {
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/2/default", "tcp/bar:3"), weights.get(2)), false);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), true);
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/1/default", "tcp/bar:2"), weights.get(1)), false);
}
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(0)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(100, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
assertEquals(421, (int)(100 * ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(2)).weight / ((LegacyLoadBalancer.LegacyNodeMetrics)weights.get(1)).weight));
}
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/1/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/2/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
private void verifyLoadBalancerOneItemOnly(LoadBalancer lb) {
List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1") );
List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights();
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
lb.received(new LoadBalancer.Node(new Mirror.Entry("foo/0/default", "tcp/bar:1"), weights.get(0)), true);
assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName());
}
@Test
public void testLoadBalancerOneItemOnly() {
verifyLoadBalancerOneItemOnly(new LegacyLoadBalancer("foo"));
verifyLoadBalancerOneItemOnly(new AdaptiveLoadBalancer("foo"));
}
} |
You tell me, will it have any statistical impact, or will it just drown in randomness. | Node getRecipient(List<Mirror.Entry> choices) {
if (choices.isEmpty()) return null;
Mirror.Entry entry;
NodeMetrics metrics;
if (choices.size() == 1) {
entry = choices.get(0);
metrics = getNodeMetrics(entry);
} else {
int candidateA = 0;
int candidateB = 1;
if (choices.size() > 2) {
candidateA = random.nextInt(choices.size());
candidateB = random.nextInt(choices.size());
}
entry = choices.get(candidateA);
Mirror.Entry entryB = choices.get(candidateB);
metrics = getNodeMetrics(entry);
NodeMetrics metricsB = getNodeMetrics(entryB);
if (metrics.pending() > metricsB.pending()) {
entry = entryB;
metrics = metricsB;
}
}
metrics.incSend();
return new Node(entry, metrics);
} | } | Node getRecipient(List<Mirror.Entry> choices) {
if (choices.isEmpty()) return null;
Mirror.Entry entry;
NodeMetrics metrics;
if (choices.size() == 1) {
entry = choices.get(0);
metrics = getNodeMetrics(entry);
} else {
int candA = 0;
int candB = 1;
if (choices.size() > 2) {
candA = random.nextInt(choices.size());
candB = random.nextInt(choices.size());
while (candB == candA) {
candB = random.nextInt(choices.size());
}
}
entry = choices.get(candA);
Mirror.Entry entryB = choices.get(candB);
metrics = getNodeMetrics(entry);
NodeMetrics metricsB = getNodeMetrics(entryB);
if (metrics.pending() > metricsB.pending()) {
entry = entryB;
metrics = metricsB;
}
}
metrics.incSend();
return new Node(entry, metrics);
} | class AdaptiveLoadBalancer extends LoadBalancer {
private Random random = new Random();
AdaptiveLoadBalancer(String cluster) {
super(cluster);
}
@Override
@Override
void received(Node node, boolean busy) {
node.metrics.incReceived();
if (busy) {
node.metrics.incBusy();
}
}
} | class AdaptiveLoadBalancer extends LoadBalancer {
private final Random random;
AdaptiveLoadBalancer(String cluster) {
this(cluster, new Random());
}
AdaptiveLoadBalancer(String cluster, Random random) {
super(cluster);
this.random = random;
}
@Override
@Override
void received(Node node, boolean busy) {
node.metrics.incReceived();
if (busy) {
node.metrics.incBusy();
}
}
} |
Probably the latter, although I'm not smart enough to crunch the numbers on it 🙂 Easiest would be to measure it in practice in the unit test over a set of runs. If there is a measurable better distribution if the two candidates are forced to be unequal, it would make sense to include it. | Node getRecipient(List<Mirror.Entry> choices) {
if (choices.isEmpty()) return null;
Mirror.Entry entry;
NodeMetrics metrics;
if (choices.size() == 1) {
entry = choices.get(0);
metrics = getNodeMetrics(entry);
} else {
int candidateA = 0;
int candidateB = 1;
if (choices.size() > 2) {
candidateA = random.nextInt(choices.size());
candidateB = random.nextInt(choices.size());
}
entry = choices.get(candidateA);
Mirror.Entry entryB = choices.get(candidateB);
metrics = getNodeMetrics(entry);
NodeMetrics metricsB = getNodeMetrics(entryB);
if (metrics.pending() > metricsB.pending()) {
entry = entryB;
metrics = metricsB;
}
}
metrics.incSend();
return new Node(entry, metrics);
} | } | Node getRecipient(List<Mirror.Entry> choices) {
if (choices.isEmpty()) return null;
Mirror.Entry entry;
NodeMetrics metrics;
if (choices.size() == 1) {
entry = choices.get(0);
metrics = getNodeMetrics(entry);
} else {
int candA = 0;
int candB = 1;
if (choices.size() > 2) {
candA = random.nextInt(choices.size());
candB = random.nextInt(choices.size());
while (candB == candA) {
candB = random.nextInt(choices.size());
}
}
entry = choices.get(candA);
Mirror.Entry entryB = choices.get(candB);
metrics = getNodeMetrics(entry);
NodeMetrics metricsB = getNodeMetrics(entryB);
if (metrics.pending() > metricsB.pending()) {
entry = entryB;
metrics = metricsB;
}
}
metrics.incSend();
return new Node(entry, metrics);
} | class AdaptiveLoadBalancer extends LoadBalancer {
private Random random = new Random();
AdaptiveLoadBalancer(String cluster) {
super(cluster);
}
@Override
@Override
void received(Node node, boolean busy) {
node.metrics.incReceived();
if (busy) {
node.metrics.incBusy();
}
}
} | class AdaptiveLoadBalancer extends LoadBalancer {
private final Random random;
AdaptiveLoadBalancer(String cluster) {
this(cluster, new Random());
}
AdaptiveLoadBalancer(String cluster, Random random) {
super(cluster);
this.random = random;
}
@Override
@Override
void received(Node node, boolean busy) {
node.metrics.incReceived();
if (busy) {
node.metrics.incBusy();
}
}
} |
After a reading a bit on the algorithm I concluded that it would indeed be better to ensure 2 distinct candidates. The reason is that when same candidate is selected fro both A and B it is in-fact a degradation into pure random. Looking at the numbers made it a simple choice. | Node getRecipient(List<Mirror.Entry> choices) {
if (choices.isEmpty()) return null;
Mirror.Entry entry;
NodeMetrics metrics;
if (choices.size() == 1) {
entry = choices.get(0);
metrics = getNodeMetrics(entry);
} else {
int candidateA = 0;
int candidateB = 1;
if (choices.size() > 2) {
candidateA = random.nextInt(choices.size());
candidateB = random.nextInt(choices.size());
}
entry = choices.get(candidateA);
Mirror.Entry entryB = choices.get(candidateB);
metrics = getNodeMetrics(entry);
NodeMetrics metricsB = getNodeMetrics(entryB);
if (metrics.pending() > metricsB.pending()) {
entry = entryB;
metrics = metricsB;
}
}
metrics.incSend();
return new Node(entry, metrics);
} | } | Node getRecipient(List<Mirror.Entry> choices) {
if (choices.isEmpty()) return null;
Mirror.Entry entry;
NodeMetrics metrics;
if (choices.size() == 1) {
entry = choices.get(0);
metrics = getNodeMetrics(entry);
} else {
int candA = 0;
int candB = 1;
if (choices.size() > 2) {
candA = random.nextInt(choices.size());
candB = random.nextInt(choices.size());
while (candB == candA) {
candB = random.nextInt(choices.size());
}
}
entry = choices.get(candA);
Mirror.Entry entryB = choices.get(candB);
metrics = getNodeMetrics(entry);
NodeMetrics metricsB = getNodeMetrics(entryB);
if (metrics.pending() > metricsB.pending()) {
entry = entryB;
metrics = metricsB;
}
}
metrics.incSend();
return new Node(entry, metrics);
} | class AdaptiveLoadBalancer extends LoadBalancer {
private Random random = new Random();
AdaptiveLoadBalancer(String cluster) {
super(cluster);
}
@Override
@Override
void received(Node node, boolean busy) {
node.metrics.incReceived();
if (busy) {
node.metrics.incBusy();
}
}
} | class AdaptiveLoadBalancer extends LoadBalancer {
private final Random random;
AdaptiveLoadBalancer(String cluster) {
this(cluster, new Random());
}
AdaptiveLoadBalancer(String cluster, Random random) {
super(cluster);
this.random = random;
}
@Override
@Override
void received(Node node, boolean busy) {
node.metrics.incReceived();
if (busy) {
node.metrics.incBusy();
}
}
} |
So I'm guessing the JSON also has to specify `wantToRetire` before `wantToDeprovision`? I'm not sure if our clients do this, or even if there is a way to force certain order for some of them? | public void test_requests() throws Exception {
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertRestart(1, new Request("http:
new byte[0], Request.Method.POST));
assertRestart(2, new Request("http:
new byte[0], Request.Method.POST));
assertRestart(13, new Request("http:
new byte[0], Request.Method.POST));
tester.assertResponseContains(new Request("http:
"\"restartGeneration\":3");
assertReboot(14, new Request("http:
new byte[0], Request.Method.POST));
assertReboot(2, new Request("http:
new byte[0], Request.Method.POST));
assertReboot(19, new Request("http:
new byte[0], Request.Method.POST));
tester.assertResponseContains(new Request("http:
"\"rebootGeneration\":4");
assertResponse(new Request("http:
("[" + asNodeJson("host8.yahoo.com", "default", "127.0.8.1") + "," +
asNodeJson("host9.yahoo.com", "large-variant", "127.0.9.1", "::9:1") + "," +
asHostJson("parent2.yahoo.com", "large-variant", Optional.of(TenantName.from("myTenant")), "127.0.127.1", "::127:1") + "," +
asDockerNodeJson("host11.yahoo.com", "parent.host.yahoo.com", "::11") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 4 nodes to the provisioned state\"}");
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
tester.assertResponse(new Request("http:
("[" + asNodeJson("host8.yahoo.com", "default", "127.0.254.8") + "]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot add provisioned host host8.yahoo.com: A node with this name already exists\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Removed host9.yahoo.com\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to ready\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"ready\"");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to ready\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to failed\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"failed\"");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to active\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to parked\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"parked\"");
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Removed host8.yahoo.com\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved test-node-pool-102-2 to failed\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"failed\"");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved test-node-pool-102-2 to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved test-node-pool-102-2 to ready\"}");
tester.assertResponse(new Request("http:
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node with hostname 'test-node-pool-102-2'\"}");
assertResponse(new Request("http:
"{\"message\":\"Moved dockerhost1.yahoo.com, host4.yahoo.com to failed\"}");
assertResponse(new Request("http:
"{\"url\":\"http:
"{\"url\":\"http:
"{\"url\":\"http:
assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentRebootGeneration\": 1}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"flavor\": \"d-2-8-100\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentVespaVersion\": \"5.104.142\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"parentHostname\": \"parent.yahoo.com\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"ipAddresses\": [\"127.0.0.1\",\"::1\"]}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToRetire\": true}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentVespaVersion\": \"6.43.0\",\"currentDockerImage\": \"docker-registry.domain.tld:8080/dist/vespa:6.45.0\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"openStackId\": \"patched-openstackid\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"modelName\": \"foo\"}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToRetire\": true, \"wantToDeprovision\": true}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
tester.assertResponseContains(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"modelName\": null}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
tester.assertPartialResponse(new Request("http:
tester.container().handleRequest((new Request("http:
((OrchestratorMock) tester.container().components().getComponent(OrchestratorMock.class.getName()))
.suspend(new HostName("host4.yahoo.com"));
assertFile(new Request("http:
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Removed dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Permanently removed dockerhost1.yahoo.com\"}");
} | Utf8.toBytes("{\"wantToRetire\": true, \"wantToDeprovision\": true}"), Request.Method.PATCH), | public void test_requests() throws Exception {
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertRestart(1, new Request("http:
new byte[0], Request.Method.POST));
assertRestart(2, new Request("http:
new byte[0], Request.Method.POST));
assertRestart(13, new Request("http:
new byte[0], Request.Method.POST));
tester.assertResponseContains(new Request("http:
"\"restartGeneration\":3");
assertReboot(14, new Request("http:
new byte[0], Request.Method.POST));
assertReboot(2, new Request("http:
new byte[0], Request.Method.POST));
assertReboot(19, new Request("http:
new byte[0], Request.Method.POST));
tester.assertResponseContains(new Request("http:
"\"rebootGeneration\":4");
assertResponse(new Request("http:
("[" + asNodeJson("host8.yahoo.com", "default", "127.0.8.1") + "," +
asNodeJson("host9.yahoo.com", "large-variant", "127.0.9.1", "::9:1") + "," +
asHostJson("parent2.yahoo.com", "large-variant", Optional.of(TenantName.from("myTenant")), "127.0.127.1", "::127:1") + "," +
asDockerNodeJson("host11.yahoo.com", "parent.host.yahoo.com", "::11") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 4 nodes to the provisioned state\"}");
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
tester.assertResponse(new Request("http:
("[" + asNodeJson("host8.yahoo.com", "default", "127.0.254.8") + "]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot add provisioned host host8.yahoo.com: A node with this name already exists\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Removed host9.yahoo.com\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to ready\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"ready\"");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to ready\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to failed\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"failed\"");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to active\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to parked\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"parked\"");
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Removed host8.yahoo.com\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved test-node-pool-102-2 to failed\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"failed\"");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved test-node-pool-102-2 to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved test-node-pool-102-2 to ready\"}");
tester.assertResponse(new Request("http:
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node with hostname 'test-node-pool-102-2'\"}");
assertResponse(new Request("http:
"{\"message\":\"Moved dockerhost1.yahoo.com, host4.yahoo.com to failed\"}");
assertResponse(new Request("http:
"{\"url\":\"http:
"{\"url\":\"http:
"{\"url\":\"http:
assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentRebootGeneration\": 1}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"flavor\": \"d-2-8-100\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentVespaVersion\": \"5.104.142\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"parentHostname\": \"parent.yahoo.com\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"ipAddresses\": [\"127.0.0.1\",\"::1\"]}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToRetire\": true}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentVespaVersion\": \"6.43.0\",\"currentDockerImage\": \"docker-registry.domain.tld:8080/dist/vespa:6.45.0\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"openStackId\": \"patched-openstackid\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"modelName\": \"foo\"}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToRetire\": true}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToDeprovision\": true}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToDeprovision\": false, \"wantToRetire\": false}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToDeprovision\": true, \"wantToRetire\": true}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
tester.assertResponseContains(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"modelName\": null}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
tester.assertPartialResponse(new Request("http:
tester.container().handleRequest((new Request("http:
((OrchestratorMock) tester.container().components().getComponent(OrchestratorMock.class.getName()))
.suspend(new HostName("host4.yahoo.com"));
assertFile(new Request("http:
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Removed dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Permanently removed dockerhost1.yahoo.com\"}");
} | class NodesV2ApiTest {
private RestApiTester tester;
@Before
public void createTester() {
tester = new RestApiTester();
}
@After
public void closeTester() {
tester.close();
}
/** This test gives examples of the node requests that can be made to nodes/v2 */
@Test
@Test
public void test_application_requests() throws Exception {
assertFile(new Request("http:
assertFile(new Request("http:
"application1.json");
assertFile(new Request("http:
"application2.json");
}
@Test
public void maintenance_requests() throws Exception {
assertResponse(new Request("http:
new byte[0], Request.Method.POST),
"{\"message\":\"Deactivated job 'NodeFailer'\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Re-activated job 'NodeFailer'\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.POST),
"{\"message\":\"Executed job 'PeriodicApplicationMaintainer'\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.POST),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such job 'foo'\"}");
}
@Test
public void post_with_patch_method_override_in_header_is_handled_as_patch() throws Exception {
Request req = new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"), Request.Method.POST);
req.getHeaders().add("X-HTTP-Method-Override", "PATCH");
assertResponse(req, "{\"message\":\"Updated host4.yahoo.com\"}");
}
@Test
public void post_with_invalid_method_override_in_header_gives_sane_error_message() throws Exception {
Request req = new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"), Request.Method.POST);
req.getHeaders().add("X-HTTP-Method-Override", "GET");
tester.assertResponse(req, 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Illegal X-HTTP-Method-Override header for POST request. Accepts 'PATCH' but got 'GET'\"}");
}
@Test
public void post_node_with_ip_address() throws Exception {
assertResponse(new Request("http:
("[" + asNodeJson("ipv4-host.yahoo.com", "default","127.0.0.1") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
("[" + asNodeJson("ipv6-host.yahoo.com", "default", "::1") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
("[" + asNodeJson("dual-stack-host.yahoo.com", "default", "127.0.254.254", "::254:254") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
}
@Test
public void post_node_with_duplicate_ip_address() throws Exception {
Request req = new Request("http:
("[" + asNodeJson("host-with-ip.yahoo.com", "default", "foo") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST);
tester.assertResponse(req, 400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Found one or more invalid addresses in [foo]: 'foo' is not an IP string literal.\"}");
tester.assertResponse(new Request("http:
"[" + asNodeJson("tenant-node-foo.yahoo.com", "default", "127.0.1.1") + "]",
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot assign [127.0.1.1] to tenant-node-foo.yahoo.com: [127.0.1.1] already assigned to host1.yahoo.com\"}");
tester.assertResponse(new Request("http:
"{\"ipAddresses\": [\"127.0.2.1\"]}",
Request.Method.PATCH), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'ipAddresses': Cannot assign [127.0.2.1] to test-node-pool-102-2: [127.0.2.1] already assigned to host2.yahoo.com\"}");
tester.assertResponse(new Request("http:
"[" + asHostJson("host200.yahoo.com", "default", Optional.empty(), "127.0.2.1") + "]",
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot assign [127.0.2.1] to host200.yahoo.com: [127.0.2.1] already assigned to host2.yahoo.com\"}");
tester.assertResponse(new Request("http:
"{\"ipAddresses\": [\"::104:3\"]}",
Request.Method.PATCH), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'ipAddresses': Cannot assign [::100:4, ::100:3, ::100:2, ::104:3] to dockerhost1.yahoo.com: [::104:3] already assigned to dockerhost5.yahoo.com\"}");
tester.assertResponse(new Request("http:
"[" + asNodeJson("cfghost42.yahoo.com", NodeType.confighost, "default", Optional.empty(), "127.0.42.1") + "]",
Request.Method.POST), 200,
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponse(new Request("http:
"[" + asDockerNodeJson("cfg42.yahoo.com", NodeType.config, "cfghost42.yahoo.com", "127.0.42.1") + "]",
Request.Method.POST), 200,
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponse(new Request("http:
"[" + asDockerNodeJson("proxy42.yahoo.com", NodeType.proxy, "cfghost42.yahoo.com", "127.0.42.1") + "]",
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot assign [127.0.42.1] to proxy42.yahoo.com: [127.0.42.1] already assigned to cfg42.yahoo.com\"}");
tester.assertResponse(new Request("http:
"[" + asNodeJson("cfghost43.yahoo.com", NodeType.confighost, "default", Optional.empty(), "127.0.43.1") + "]",
Request.Method.POST), 200,
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponse(new Request("http:
"{\"ipAddresses\": [\"127.0.43.1\"]}",
Request.Method.PATCH), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'ipAddresses': Cannot assign [127.0.43.1] to cfg42.yahoo.com: [127.0.43.1] already assigned to cfghost43.yahoo.com\"}");
}
@Test
public void post_controller_node() throws Exception {
String data = "[{\"hostname\":\"controller1.yahoo.com\", \"openStackId\":\"fake-controller1.yahoo.com\"," +
createIpAddresses("127.0.0.1") +
"\"flavor\":\"default\"" +
", \"type\":\"controller\"}]";
assertResponse(new Request("http:
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertFile(new Request("http:
}
@Test
public void fails_to_ready_node_with_hard_fail() throws Exception {
assertResponse(new Request("http:
("[" + asNodeJson("host12.yahoo.com", "default") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
String msg = "Actual disk space (2TB) differs from spec (3TB)";
assertResponse(new Request("http:
Utf8.toBytes("{\"reports\":{\"diskSpace\":{\"createdMillis\":2,\"description\":\"" + msg + "\",\"type\": \"HARD_FAIL\"}}}"),
Request.Method.PATCH),
"{\"message\":\"Updated host12.yahoo.com\"}");
tester.assertResponse(new Request("http:
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"provisioned host host12.yahoo.com cannot be readied because it has " +
"hard failures: [diskSpace reported 1970-01-01T00:00:00.002Z: " + msg + "]\"}");
}
@Test
public void patching_dirty_node_does_not_increase_reboot_generation() throws Exception {
assertResponse(new Request("http:
("[" + asNodeJson("foo.yahoo.com", "default") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to failed\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to dirty\"}");
tester.assertResponseContains(new Request("http:
"\"rebootGeneration\":1");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentRebootGeneration\": 42}"), Request.Method.PATCH),
"{\"message\":\"Updated foo.yahoo.com\"}");
tester.assertResponseContains(new Request("http:
"\"rebootGeneration\":1");
}
@Test
public void acl_request_by_tenant_node() throws Exception {
String hostname = "foo.yahoo.com";
assertResponse(new Request("http:
("[" + asNodeJson(hostname, "default", "127.0.222.1") + "]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to ready\"}");
assertFile(new Request("http:
}
@Test
public void acl_request_by_config_server() throws Exception {
assertFile(new Request("http:
}
@Test
public void test_invalid_requests() throws Exception {
tester.assertResponse(new Request("http:
new byte[0], Request.Method.GET),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node with hostname 'node-does-not-exist'\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not move node-does-not-exist to failed: Node not found\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host1.yahoo.com to failed\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot make failed host host1.yahoo.com allocated to tenant1.application1.instance1 as 'container/id1/0/0' available for new allocation as it is not in state [dirty]\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host1.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host1.yahoo.com to ready\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to parked\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot make parked host host2.yahoo.com allocated to tenant2.application2.instance2 as 'content/id2/0/0' available for new allocation as it is not in state [dirty]\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to ready\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node with hostname 'host2.yahoo.com'\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"active child node host4.yahoo.com allocated to tenant3.application3.instance3 as 'content/id3/0/0' is currently allocated and cannot be removed\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": \"1\"}"), Request.Method.PATCH),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'currentRestartGeneration': Expected a LONG value, got a STRING\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"flavor\": 1}"), Request.Method.PATCH),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'flavor': Expected a STRING value, got a LONG\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT), 404,
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not move host2.yahoo.com to active: Node not found\"}");
tester.assertResponse(new Request("http:
("[" + asNodeJson("host8.yahoo.com", "default", "127.0.254.1", "::254:1") + "," +
asNodeJson("host8.yahoo.com", "large-variant", "127.0.253.1", "::253:1") + "]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot add nodes: provisioned host host8.yahoo.com is duplicated in the argument list\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"modelName\": \"foo\"}"), Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'modelName': A child node cannot have model name set\"}");
}
@Test
public void test_node_patching() throws Exception {
assertResponse(new Request("http:
Utf8.toBytes("{" +
"\"currentRestartGeneration\": 1," +
"\"currentRebootGeneration\": 3," +
"\"flavor\": \"medium-disk\"," +
"\"currentVespaVersion\": \"5.104.142\"," +
"\"failCount\": 0," +
"\"parentHostname\": \"parent.yahoo.com\"" +
"}"
),
Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"),
Request.Method.PATCH),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node found with hostname doesnotexist.yahoo.com\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'currentRestartGeneration': Node is not allocated\"}");
}
@Test
public void test_node_patch_to_remove_docker_ready_fields() throws Exception {
assertResponse(new Request("http:
Utf8.toBytes("{" +
"\"currentVespaVersion\": \"\"," +
"\"currentDockerImage\": \"\"" +
"}"
),
Request.Method.PATCH),
"{\"message\":\"Updated host5.yahoo.com\"}");
assertFile(new Request("http:
}
@Test
public void test_reports_patching() throws IOException {
assertResponse(new Request("http:
Utf8.toBytes("{" +
" \"reports\": {" +
" \"actualCpuCores\": {" +
" \"createdMillis\": 1, " +
" \"description\": \"Actual number of CPU cores (2) differs from spec (4)\"," +
" \"type\": \"HARD_FAIL\"," +
" \"value\":2" +
" }," +
" \"diskSpace\": {" +
" \"createdMillis\": 2, " +
" \"description\": \"Actual disk space (2TB) differs from spec (3TB)\"," +
" \"type\": \"HARD_FAIL\"," +
" \"details\": {" +
" \"inGib\": 3," +
" \"disks\": [\"/dev/sda1\", \"/dev/sdb3\"]" +
" }" +
" }" +
" }" +
"}"),
Request.Method.PATCH),
"{\"message\":\"Updated host6.yahoo.com\"}");
assertFile(new Request("http:
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"reports\": {}}"),
Request.Method.PATCH),
200,
"{\"message\":\"Updated host6.yahoo.com\"}");
assertFile(new Request("http:
tester.assertResponse(new Request("http:
Utf8.toBytes("{" +
" \"reports\": {" +
" \"actualCpuCores\": {" +
" \"createdMillis\": 3 " +
" }" +
" }" +
"}"),
Request.Method.PATCH),
200,
"{\"message\":\"Updated host6.yahoo.com\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"reports\": { \"diskSpace\": null } }"),
Request.Method.PATCH),
"{\"message\":\"Updated host6.yahoo.com\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"reports\": null }"),
Request.Method.PATCH),
"{\"message\":\"Updated host6.yahoo.com\"}");
assertFile(new Request("http:
}
@Test
public void test_upgrade() throws IOException {
assertResponse(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.456 for nodes of type config\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.456 for nodes of type confighost\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.456 for nodes of type controller\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"confighost\":\"6.123.456\",\"controller\":\"6.123.456\"},\"osVersions\":{},\"dockerImages\":{}}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Target version for type tenant is not allowed\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"At least one of 'version', 'osVersion' or 'dockerImage' must be set\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.1\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot downgrade version without setting 'force'. " +
"Current target version: 6.123.456, attempted to set target version: 6.123.1\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.1\",\"force\":true}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.1 for nodes of type confighost\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"confighost\":\"6.123.1\",\"controller\":\"6.123.456\"},\"osVersions\":{},\"dockerImages\":{}}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"version\": null}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot downgrade version without setting 'force'. Current target version: 6.123.1, attempted to set target version: 0.0.0\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": null, \"force\": true}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 0.0.0 for nodes of type confighost\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"controller\":\"6.123.456\"},\"osVersions\":{},\"dockerImages\":{}}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.5.2 for nodes of type confighost\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.5.2 for nodes of type host\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"controller\":\"6.123.456\"},\"osVersions\":{\"host\":\"7.5.2\",\"confighost\":\"7.5.2\"},\"dockerImages\":{}}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.124.42\", \"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.124.42, osVersion to 7.5.2 for nodes of type confighost\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Node type 'config' does not support OS upgrades\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.4.2\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot set target OS version to 7.4.2 without setting 'force', as it's lower than the current version: 7.5.2\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.4.2\", \"force\": true}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.4.2 for nodes of type confighost\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": null}"),
Request.Method.PATCH),
200,
"{\"message\":\"Set osVersion to null for nodes of type confighost\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"dockerImage\": \"my-repo.my-domain.example:1234/repo/tenant\"}"),
Request.Method.PATCH),
"{\"message\":\"Set docker image to my-repo.my-domain.example:1234/repo/tenant for nodes of type tenant\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"dockerImage\": \"my-repo.my-domain.example:1234/repo/image\"}"),
Request.Method.PATCH),
"{\"message\":\"Set docker image to my-repo.my-domain.example:1234/repo/image for nodes of type config\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"confighost\":\"6.124.42\",\"controller\":\"6.123.456\"},\"osVersions\":{\"host\":\"7.5.2\"},\"dockerImages\":{\"tenant\":\"my-repo.my-domain.example:1234/repo/tenant\",\"config\":\"my-repo.my-domain.example:1234/repo/image\"}}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"dockerImage\": \"my-repo.my-domain.example:1234/repo/image\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Setting docker image for confighost nodes is unsupported\"}");
}
@Test
public void test_os_version() throws Exception {
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.5.2 for nodes of type host\"}");
var nodeRepository = (NodeRepository)tester.container().components().getComponent(MockNodeRepository.class.getName());
var osUpgradeActivator = new OsUpgradeActivator(nodeRepository, Duration.ofDays(1));
osUpgradeActivator.run();
Response r = tester.container().handleRequest(new Request("http:
assertFalse("Response omits wantedOsVersions field", r.getBodyAsString().contains("wantedOsVersion"));
assertResponse(new Request("http:
Utf8.toBytes("{\"currentOsVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"currentOsVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost2.yahoo.com\"}");
assertResponse(new Request("http:
"{\"nodes\":[" +
"{\"url\":\"http:
"{\"url\":\"http:
"]}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.42.1\", \"upgradeBudget\": \"PT24H\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.42.1, upgradeBudget to PT24H for nodes of type host\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.42.1\", \"upgradeBudget\": \"foo\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid duration 'foo': Text cannot be parsed to a Duration\"}");
}
@Test
public void test_firmware_upgrades() throws IOException {
assertResponse(new Request("http:
Utf8.toBytes("{\"currentFirmwareCheck\":100}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
"{\"message\":\"Will request firmware checks on all hosts.\"}");
assertFile(new Request("http:
"dockerhost1-with-firmware-data.json");
assertFile(new Request("http:
"node1.json");
assertResponse(new Request("http:
"{\"message\":\"Cancelled outstanding requests for firmware checks\"}");
}
@Test
public void test_capacity() throws Exception {
assertFile(new Request("http:
assertFile(new Request("http:
List<String> hostsToRemove = List.of(
"dockerhost1.yahoo.com",
"dockerhost2.yahoo.com",
"dockerhost3.yahoo.com",
"dockerhost4.yahoo.com"
);
String requestUriTemplate = "http:
assertFile(new Request(String.format(requestUriTemplate,
String.join(",", hostsToRemove.subList(0, 3)))),
"capacity-hostremoval-possible.json");
assertFile(new Request(String.format(requestUriTemplate,
String.join(",", hostsToRemove))),
"capacity-hostremoval-impossible.json");
}
/** Tests the rendering of each node separately to make it easier to find errors */
@Test
public void test_single_node_rendering() throws Exception {
for (int i = 1; i <= 14; i++) {
if (i == 8 || i == 9 || i == 11 || i == 12) continue;
assertFile(new Request("http:
}
}
@Test
public void test_flavor_overrides() throws Exception {
String host = "parent2.yahoo.com";
tester.assertResponse(new Request("http:
("[{\"hostname\":\"" + host + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," +
"\"flavor\":\"large-variant\",\"resources\":{\"diskGb\":1234,\"memoryGb\":4321}}]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Can only override disk GB for configured flavor\"}");
assertResponse(new Request("http:
("[{\"hostname\":\"" + host + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," +
"\"flavor\":\"large-variant\",\"type\":\"host\",\"resources\":{\"diskGb\":1234}}]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponseContains(new Request("http:
"\"resources\":{\"vcpu\":64.0,\"memoryGb\":128.0,\"diskGb\":1234.0,\"bandwidthGbps\":15.0,\"diskSpeed\":\"fast\",\"storageType\":\"remote\"}");
String tenant = "node-1-3.yahoo.com";
String resources = "\"resources\":{\"vcpu\":64.0,\"memoryGb\":128.0,\"diskGb\":1234.0,\"bandwidthGbps\":15.0,\"diskSpeed\":\"slow\",\"storageType\":\"remote\"}";
assertResponse(new Request("http:
("[{\"hostname\":\"" + tenant + "\"," + createIpAddresses("::2") + "\"openStackId\":\"osid-124\"," +
"\"type\":\"tenant\"," + resources + "}]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponseContains(new Request("http:
tester.assertResponse(new Request("http:
"{\"minDiskAvailableGb\":5432,\"minMainMemoryAvailableGb\":2345}".getBytes(StandardCharsets.UTF_8),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'minMainMemoryAvailableGb': Can only override disk GB for configured flavor\"}");
assertResponse(new Request("http:
"{\"minDiskAvailableGb\":5432}".getBytes(StandardCharsets.UTF_8),
Request.Method.PATCH),
"{\"message\":\"Updated " + host + "\"}");
tester.assertResponseContains(new Request("http:
"\"resources\":{\"vcpu\":64.0,\"memoryGb\":128.0,\"diskGb\":5432.0,\"bandwidthGbps\":15.0,\"diskSpeed\":\"fast\",\"storageType\":\"remote\"}");
}
@Test
public void test_node_resources() throws Exception {
String hostname = "node123.yahoo.com";
String resources = "\"resources\":{\"vcpu\":5.0,\"memoryGb\":4321.0,\"diskGb\":1234.0,\"bandwidthGbps\":0.3,\"diskSpeed\":\"slow\",\"storageType\":\"local\"}";
tester.assertResponse(new Request("http:
("[{\"hostname\":\"" + hostname + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," +
resources.replace("\"memoryGb\":4321.0,", "") + "}]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Required field 'memoryGb' is missing\"}");
assertResponse(new Request("http:
("[{\"hostname\":\"" + hostname + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," + resources + "}]")
.getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponseContains(new Request("http:
assertResponse(new Request("http:
"{\"diskGb\":12,\"memoryGb\":34,\"vcpu\":56,\"fastDisk\":true,\"remoteStorage\":true,\"bandwidthGbps\":78.0}".getBytes(StandardCharsets.UTF_8),
Request.Method.PATCH),
"{\"message\":\"Updated " + hostname + "\"}");
tester.assertResponseContains(new Request("http:
"\"resources\":{\"vcpu\":56.0,\"memoryGb\":34.0,\"diskGb\":12.0,\"bandwidthGbps\":78.0,\"diskSpeed\":\"fast\",\"storageType\":\"remote\"}");
}
private static String asDockerNodeJson(String hostname, String parentHostname, String... ipAddress) {
return asDockerNodeJson(hostname, NodeType.tenant, parentHostname, ipAddress);
}
private static String asDockerNodeJson(String hostname, NodeType nodeType, String parentHostname, String... ipAddress) {
return "{\"hostname\":\"" + hostname + "\", \"parentHostname\":\"" + parentHostname + "\"," +
createIpAddresses(ipAddress) +
"\"openStackId\":\"" + hostname + "\",\"flavor\":\"d-1-1-100\"" +
(nodeType != NodeType.tenant ? ",\"type\":\"" + nodeType + "\"" : "") +
"}";
}
private static String asNodeJson(String hostname, String flavor, String... ipAddress) {
return "{\"hostname\":\"" + hostname + "\", \"openStackId\":\"" + hostname + "\"," +
createIpAddresses(ipAddress) +
"\"flavor\":\"" + flavor + "\"}";
}
private static String asHostJson(String hostname, String flavor, Optional<TenantName> reservedTo, String... ipAddress) {
return asNodeJson(hostname, NodeType.host, flavor, reservedTo, ipAddress);
}
private static String asNodeJson(String hostname, NodeType nodeType, String flavor, Optional<TenantName> reservedTo, String... ipAddress) {
return "{\"hostname\":\"" + hostname + "\", \"openStackId\":\"" + hostname + "\"," +
createIpAddresses(ipAddress) +
"\"flavor\":\"" + flavor + "\"" +
(reservedTo.isPresent() ? ", \"reservedTo\":\"" + reservedTo.get().value() + "\"" : "") +
", \"type\":\"" + nodeType + "\"}";
}
private static String createIpAddresses(String... ipAddress) {
return "\"ipAddresses\":[" +
Arrays.stream(ipAddress)
.map(ip -> "\"" + ip + "\"")
.collect(Collectors.joining(",")) +
"],";
}
private void assertRestart(int restartCount, Request request) throws IOException {
tester.assertResponse(request, 200, "{\"message\":\"Scheduled restart of " + restartCount + " matching nodes\"}");
}
private void assertReboot(int rebootCount, Request request) throws IOException {
tester.assertResponse(request, 200, "{\"message\":\"Scheduled reboot of " + rebootCount + " matching nodes\"}");
}
private void assertFile(Request request, String file) throws IOException {
tester.assertFile(request, file);
}
private void assertResponse(Request request, String file) throws IOException {
tester.assertResponse(request, file);
}
} | class NodesV2ApiTest {
private RestApiTester tester;
@Before
public void createTester() {
tester = new RestApiTester();
}
@After
public void closeTester() {
tester.close();
}
/** This test gives examples of the node requests that can be made to nodes/v2 */
@Test
@Test
public void test_application_requests() throws Exception {
assertFile(new Request("http:
assertFile(new Request("http:
"application1.json");
assertFile(new Request("http:
"application2.json");
}
@Test
public void maintenance_requests() throws Exception {
assertResponse(new Request("http:
new byte[0], Request.Method.POST),
"{\"message\":\"Deactivated job 'NodeFailer'\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Re-activated job 'NodeFailer'\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.POST),
"{\"message\":\"Executed job 'PeriodicApplicationMaintainer'\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.POST),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such job 'foo'\"}");
}
@Test
public void post_with_patch_method_override_in_header_is_handled_as_patch() throws Exception {
Request req = new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"), Request.Method.POST);
req.getHeaders().add("X-HTTP-Method-Override", "PATCH");
assertResponse(req, "{\"message\":\"Updated host4.yahoo.com\"}");
}
@Test
public void post_with_invalid_method_override_in_header_gives_sane_error_message() throws Exception {
Request req = new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"), Request.Method.POST);
req.getHeaders().add("X-HTTP-Method-Override", "GET");
tester.assertResponse(req, 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Illegal X-HTTP-Method-Override header for POST request. Accepts 'PATCH' but got 'GET'\"}");
}
@Test
public void post_node_with_ip_address() throws Exception {
assertResponse(new Request("http:
("[" + asNodeJson("ipv4-host.yahoo.com", "default","127.0.0.1") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
("[" + asNodeJson("ipv6-host.yahoo.com", "default", "::1") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
("[" + asNodeJson("dual-stack-host.yahoo.com", "default", "127.0.254.254", "::254:254") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
}
@Test
public void post_node_with_duplicate_ip_address() throws Exception {
Request req = new Request("http:
("[" + asNodeJson("host-with-ip.yahoo.com", "default", "foo") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST);
tester.assertResponse(req, 400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Found one or more invalid addresses in [foo]: 'foo' is not an IP string literal.\"}");
tester.assertResponse(new Request("http:
"[" + asNodeJson("tenant-node-foo.yahoo.com", "default", "127.0.1.1") + "]",
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot assign [127.0.1.1] to tenant-node-foo.yahoo.com: [127.0.1.1] already assigned to host1.yahoo.com\"}");
tester.assertResponse(new Request("http:
"{\"ipAddresses\": [\"127.0.2.1\"]}",
Request.Method.PATCH), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'ipAddresses': Cannot assign [127.0.2.1] to test-node-pool-102-2: [127.0.2.1] already assigned to host2.yahoo.com\"}");
tester.assertResponse(new Request("http:
"[" + asHostJson("host200.yahoo.com", "default", Optional.empty(), "127.0.2.1") + "]",
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot assign [127.0.2.1] to host200.yahoo.com: [127.0.2.1] already assigned to host2.yahoo.com\"}");
tester.assertResponse(new Request("http:
"{\"ipAddresses\": [\"::104:3\"]}",
Request.Method.PATCH), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'ipAddresses': Cannot assign [::100:4, ::100:3, ::100:2, ::104:3] to dockerhost1.yahoo.com: [::104:3] already assigned to dockerhost5.yahoo.com\"}");
tester.assertResponse(new Request("http:
"[" + asNodeJson("cfghost42.yahoo.com", NodeType.confighost, "default", Optional.empty(), "127.0.42.1") + "]",
Request.Method.POST), 200,
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponse(new Request("http:
"[" + asDockerNodeJson("cfg42.yahoo.com", NodeType.config, "cfghost42.yahoo.com", "127.0.42.1") + "]",
Request.Method.POST), 200,
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponse(new Request("http:
"[" + asDockerNodeJson("proxy42.yahoo.com", NodeType.proxy, "cfghost42.yahoo.com", "127.0.42.1") + "]",
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot assign [127.0.42.1] to proxy42.yahoo.com: [127.0.42.1] already assigned to cfg42.yahoo.com\"}");
tester.assertResponse(new Request("http:
"[" + asNodeJson("cfghost43.yahoo.com", NodeType.confighost, "default", Optional.empty(), "127.0.43.1") + "]",
Request.Method.POST), 200,
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponse(new Request("http:
"{\"ipAddresses\": [\"127.0.43.1\"]}",
Request.Method.PATCH), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'ipAddresses': Cannot assign [127.0.43.1] to cfg42.yahoo.com: [127.0.43.1] already assigned to cfghost43.yahoo.com\"}");
}
@Test
public void post_controller_node() throws Exception {
String data = "[{\"hostname\":\"controller1.yahoo.com\", \"openStackId\":\"fake-controller1.yahoo.com\"," +
createIpAddresses("127.0.0.1") +
"\"flavor\":\"default\"" +
", \"type\":\"controller\"}]";
assertResponse(new Request("http:
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertFile(new Request("http:
}
@Test
public void fails_to_ready_node_with_hard_fail() throws Exception {
assertResponse(new Request("http:
("[" + asHostJson("host12.yahoo.com", "default", Optional.empty()) + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
String msg = "Actual disk space (2TB) differs from spec (3TB)";
assertResponse(new Request("http:
Utf8.toBytes("{\"reports\":{\"diskSpace\":{\"createdMillis\":2,\"description\":\"" + msg + "\",\"type\": \"HARD_FAIL\"}}}"),
Request.Method.PATCH),
"{\"message\":\"Updated host12.yahoo.com\"}");
tester.assertResponse(new Request("http:
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"provisioned host host12.yahoo.com cannot be readied because it has " +
"hard failures: [diskSpace reported 1970-01-01T00:00:00.002Z: " + msg + "]\"}");
}
@Test
public void patching_dirty_node_does_not_increase_reboot_generation() throws Exception {
assertResponse(new Request("http:
("[" + asNodeJson("foo.yahoo.com", "default") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to failed\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to dirty\"}");
tester.assertResponseContains(new Request("http:
"\"rebootGeneration\":1");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentRebootGeneration\": 42}"), Request.Method.PATCH),
"{\"message\":\"Updated foo.yahoo.com\"}");
tester.assertResponseContains(new Request("http:
"\"rebootGeneration\":1");
}
@Test
public void acl_request_by_tenant_node() throws Exception {
String hostname = "foo.yahoo.com";
assertResponse(new Request("http:
("[" + asNodeJson(hostname, "default", "127.0.222.1") + "]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to ready\"}");
assertFile(new Request("http:
}
@Test
public void acl_request_by_config_server() throws Exception {
assertFile(new Request("http:
}
@Test
public void test_invalid_requests() throws Exception {
tester.assertResponse(new Request("http:
new byte[0], Request.Method.GET),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node with hostname 'node-does-not-exist'\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not move node-does-not-exist to failed: Node not found\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host1.yahoo.com to failed\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot make failed host host1.yahoo.com allocated to tenant1.application1.instance1 as 'container/id1/0/0' available for new allocation as it is not in state [dirty]\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host1.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host1.yahoo.com to ready\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to parked\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot make parked host host2.yahoo.com allocated to tenant2.application2.instance2 as 'content/id2/0/0' available for new allocation as it is not in state [dirty]\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to ready\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node with hostname 'host2.yahoo.com'\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"active child node host4.yahoo.com allocated to tenant3.application3.instance3 as 'content/id3/0/0' is currently allocated and cannot be removed\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": \"1\"}"), Request.Method.PATCH),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'currentRestartGeneration': Expected a LONG value, got a STRING\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"flavor\": 1}"), Request.Method.PATCH),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'flavor': Expected a STRING value, got a LONG\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT), 404,
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not move host2.yahoo.com to active: Node not found\"}");
tester.assertResponse(new Request("http:
("[" + asNodeJson("host8.yahoo.com", "default", "127.0.254.1", "::254:1") + "," +
asNodeJson("host8.yahoo.com", "large-variant", "127.0.253.1", "::253:1") + "]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot add nodes: provisioned host host8.yahoo.com is duplicated in the argument list\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"modelName\": \"foo\"}"), Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'modelName': A child node cannot have model name set\"}");
}
@Test
public void test_node_patching() throws Exception {
assertResponse(new Request("http:
Utf8.toBytes("{" +
"\"currentRestartGeneration\": 1," +
"\"currentRebootGeneration\": 3," +
"\"flavor\": \"medium-disk\"," +
"\"currentVespaVersion\": \"5.104.142\"," +
"\"failCount\": 0," +
"\"parentHostname\": \"parent.yahoo.com\"" +
"}"
),
Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"),
Request.Method.PATCH),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node found with hostname doesnotexist.yahoo.com\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'currentRestartGeneration': Node is not allocated\"}");
}
@Test
public void test_node_patch_to_remove_docker_ready_fields() throws Exception {
assertResponse(new Request("http:
Utf8.toBytes("{" +
"\"currentVespaVersion\": \"\"," +
"\"currentDockerImage\": \"\"" +
"}"
),
Request.Method.PATCH),
"{\"message\":\"Updated host5.yahoo.com\"}");
assertFile(new Request("http:
}
@Test
public void test_reports_patching() throws IOException {
assertResponse(new Request("http:
Utf8.toBytes("{" +
" \"reports\": {" +
" \"actualCpuCores\": {" +
" \"createdMillis\": 1, " +
" \"description\": \"Actual number of CPU cores (2) differs from spec (4)\"," +
" \"type\": \"HARD_FAIL\"," +
" \"value\":2" +
" }," +
" \"diskSpace\": {" +
" \"createdMillis\": 2, " +
" \"description\": \"Actual disk space (2TB) differs from spec (3TB)\"," +
" \"type\": \"HARD_FAIL\"," +
" \"details\": {" +
" \"inGib\": 3," +
" \"disks\": [\"/dev/sda1\", \"/dev/sdb3\"]" +
" }" +
" }" +
" }" +
"}"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"reports\": {}}"),
Request.Method.PATCH),
200,
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
tester.assertResponse(new Request("http:
Utf8.toBytes("{" +
" \"reports\": {" +
" \"actualCpuCores\": {" +
" \"createdMillis\": 3 " +
" }" +
" }" +
"}"),
Request.Method.PATCH),
200,
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"reports\": { \"diskSpace\": null } }"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"reports\": null }"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
}
@Test
public void test_upgrade() throws IOException {
assertResponse(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.456 for nodes of type config\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.456 for nodes of type confighost\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.456 for nodes of type controller\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"confighost\":\"6.123.456\",\"controller\":\"6.123.456\"},\"osVersions\":{},\"dockerImages\":{}}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Target version for type tenant is not allowed\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"At least one of 'version', 'osVersion' or 'dockerImage' must be set\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.1\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot downgrade version without setting 'force'. " +
"Current target version: 6.123.456, attempted to set target version: 6.123.1\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.1\",\"force\":true}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.1 for nodes of type confighost\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"confighost\":\"6.123.1\",\"controller\":\"6.123.456\"},\"osVersions\":{},\"dockerImages\":{}}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"version\": null}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot downgrade version without setting 'force'. Current target version: 6.123.1, attempted to set target version: 0.0.0\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": null, \"force\": true}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 0.0.0 for nodes of type confighost\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"controller\":\"6.123.456\"},\"osVersions\":{},\"dockerImages\":{}}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.5.2 for nodes of type confighost\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.5.2 for nodes of type host\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"controller\":\"6.123.456\"},\"osVersions\":{\"host\":\"7.5.2\",\"confighost\":\"7.5.2\"},\"dockerImages\":{}}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.124.42\", \"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.124.42, osVersion to 7.5.2 for nodes of type confighost\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Node type 'config' does not support OS upgrades\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.4.2\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot set target OS version to 7.4.2 without setting 'force', as it's lower than the current version: 7.5.2\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.4.2\", \"force\": true}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.4.2 for nodes of type confighost\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": null}"),
Request.Method.PATCH),
200,
"{\"message\":\"Set osVersion to null for nodes of type confighost\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"dockerImage\": \"my-repo.my-domain.example:1234/repo/tenant\"}"),
Request.Method.PATCH),
"{\"message\":\"Set docker image to my-repo.my-domain.example:1234/repo/tenant for nodes of type tenant\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"dockerImage\": \"my-repo.my-domain.example:1234/repo/image\"}"),
Request.Method.PATCH),
"{\"message\":\"Set docker image to my-repo.my-domain.example:1234/repo/image for nodes of type config\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"confighost\":\"6.124.42\",\"controller\":\"6.123.456\"},\"osVersions\":{\"host\":\"7.5.2\"},\"dockerImages\":{\"tenant\":\"my-repo.my-domain.example:1234/repo/tenant\",\"config\":\"my-repo.my-domain.example:1234/repo/image\"}}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"dockerImage\": \"my-repo.my-domain.example:1234/repo/image\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Setting docker image for confighost nodes is unsupported\"}");
}
@Test
public void test_os_version() throws Exception {
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.5.2 for nodes of type host\"}");
var nodeRepository = (NodeRepository)tester.container().components().getComponent(MockNodeRepository.class.getName());
var osUpgradeActivator = new OsUpgradeActivator(nodeRepository, Duration.ofDays(1));
osUpgradeActivator.run();
Response r = tester.container().handleRequest(new Request("http:
assertFalse("Response omits wantedOsVersions field", r.getBodyAsString().contains("wantedOsVersion"));
assertResponse(new Request("http:
Utf8.toBytes("{\"currentOsVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"currentOsVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost2.yahoo.com\"}");
assertResponse(new Request("http:
"{\"nodes\":[" +
"{\"url\":\"http:
"{\"url\":\"http:
"]}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.42.1\", \"upgradeBudget\": \"PT24H\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.42.1, upgradeBudget to PT24H for nodes of type host\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.42.1\", \"upgradeBudget\": \"foo\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid duration 'foo': Text cannot be parsed to a Duration\"}");
}
@Test
public void test_firmware_upgrades() throws IOException {
assertResponse(new Request("http:
Utf8.toBytes("{\"currentFirmwareCheck\":100}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
"{\"message\":\"Will request firmware checks on all hosts.\"}");
assertFile(new Request("http:
"dockerhost1-with-firmware-data.json");
assertFile(new Request("http:
"node1.json");
assertResponse(new Request("http:
"{\"message\":\"Cancelled outstanding requests for firmware checks\"}");
}
@Test
public void test_capacity() throws Exception {
assertFile(new Request("http:
assertFile(new Request("http:
List<String> hostsToRemove = List.of(
"dockerhost1.yahoo.com",
"dockerhost2.yahoo.com",
"dockerhost3.yahoo.com",
"dockerhost4.yahoo.com"
);
String requestUriTemplate = "http:
assertFile(new Request(String.format(requestUriTemplate,
String.join(",", hostsToRemove.subList(0, 3)))),
"capacity-hostremoval-possible.json");
assertFile(new Request(String.format(requestUriTemplate,
String.join(",", hostsToRemove))),
"capacity-hostremoval-impossible.json");
}
/** Tests the rendering of each node separately to make it easier to find errors */
@Test
public void test_single_node_rendering() throws Exception {
for (int i = 1; i <= 14; i++) {
if (i == 8 || i == 9 || i == 11 || i == 12) continue;
assertFile(new Request("http:
}
}
@Test
public void test_flavor_overrides() throws Exception {
String host = "parent2.yahoo.com";
tester.assertResponse(new Request("http:
("[{\"hostname\":\"" + host + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," +
"\"flavor\":\"large-variant\",\"resources\":{\"diskGb\":1234,\"memoryGb\":4321}}]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Can only override disk GB for configured flavor\"}");
assertResponse(new Request("http:
("[{\"hostname\":\"" + host + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," +
"\"flavor\":\"large-variant\",\"type\":\"host\",\"resources\":{\"diskGb\":1234}}]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponseContains(new Request("http:
"\"resources\":{\"vcpu\":64.0,\"memoryGb\":128.0,\"diskGb\":1234.0,\"bandwidthGbps\":15.0,\"diskSpeed\":\"fast\",\"storageType\":\"remote\"}");
String tenant = "node-1-3.yahoo.com";
String resources = "\"resources\":{\"vcpu\":64.0,\"memoryGb\":128.0,\"diskGb\":1234.0,\"bandwidthGbps\":15.0,\"diskSpeed\":\"slow\",\"storageType\":\"remote\"}";
assertResponse(new Request("http:
("[{\"hostname\":\"" + tenant + "\"," + createIpAddresses("::2") + "\"openStackId\":\"osid-124\"," +
"\"type\":\"tenant\"," + resources + "}]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponseContains(new Request("http:
tester.assertResponse(new Request("http:
"{\"minDiskAvailableGb\":5432,\"minMainMemoryAvailableGb\":2345}".getBytes(StandardCharsets.UTF_8),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'minMainMemoryAvailableGb': Can only override disk GB for configured flavor\"}");
assertResponse(new Request("http:
"{\"minDiskAvailableGb\":5432}".getBytes(StandardCharsets.UTF_8),
Request.Method.PATCH),
"{\"message\":\"Updated " + host + "\"}");
tester.assertResponseContains(new Request("http:
"\"resources\":{\"vcpu\":64.0,\"memoryGb\":128.0,\"diskGb\":5432.0,\"bandwidthGbps\":15.0,\"diskSpeed\":\"fast\",\"storageType\":\"remote\"}");
}
@Test
public void test_node_resources() throws Exception {
String hostname = "node123.yahoo.com";
String resources = "\"resources\":{\"vcpu\":5.0,\"memoryGb\":4321.0,\"diskGb\":1234.0,\"bandwidthGbps\":0.3,\"diskSpeed\":\"slow\",\"storageType\":\"local\"}";
tester.assertResponse(new Request("http:
("[{\"hostname\":\"" + hostname + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," +
resources.replace("\"memoryGb\":4321.0,", "") + "}]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Required field 'memoryGb' is missing\"}");
assertResponse(new Request("http:
("[{\"hostname\":\"" + hostname + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," + resources + "}]")
.getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponseContains(new Request("http:
assertResponse(new Request("http:
"{\"diskGb\":12,\"memoryGb\":34,\"vcpu\":56,\"fastDisk\":true,\"remoteStorage\":true,\"bandwidthGbps\":78.0}".getBytes(StandardCharsets.UTF_8),
Request.Method.PATCH),
"{\"message\":\"Updated " + hostname + "\"}");
tester.assertResponseContains(new Request("http:
"\"resources\":{\"vcpu\":56.0,\"memoryGb\":34.0,\"diskGb\":12.0,\"bandwidthGbps\":78.0,\"diskSpeed\":\"fast\",\"storageType\":\"remote\"}");
}
private static String asDockerNodeJson(String hostname, String parentHostname, String... ipAddress) {
return asDockerNodeJson(hostname, NodeType.tenant, parentHostname, ipAddress);
}
private static String asDockerNodeJson(String hostname, NodeType nodeType, String parentHostname, String... ipAddress) {
return "{\"hostname\":\"" + hostname + "\", \"parentHostname\":\"" + parentHostname + "\"," +
createIpAddresses(ipAddress) +
"\"openStackId\":\"" + hostname + "\",\"flavor\":\"d-1-1-100\"" +
(nodeType != NodeType.tenant ? ",\"type\":\"" + nodeType + "\"" : "") +
"}";
}
private static String asNodeJson(String hostname, String flavor, String... ipAddress) {
return "{\"hostname\":\"" + hostname + "\", \"openStackId\":\"" + hostname + "\"," +
createIpAddresses(ipAddress) +
"\"flavor\":\"" + flavor + "\"}";
}
private static String asHostJson(String hostname, String flavor, Optional<TenantName> reservedTo, String... ipAddress) {
return asNodeJson(hostname, NodeType.host, flavor, reservedTo, ipAddress);
}
private static String asNodeJson(String hostname, NodeType nodeType, String flavor, Optional<TenantName> reservedTo, String... ipAddress) {
return "{\"hostname\":\"" + hostname + "\", \"openStackId\":\"" + hostname + "\"," +
createIpAddresses(ipAddress) +
"\"flavor\":\"" + flavor + "\"" +
(reservedTo.isPresent() ? ", \"reservedTo\":\"" + reservedTo.get().value() + "\"" : "") +
", \"type\":\"" + nodeType + "\"}";
}
private static String createIpAddresses(String... ipAddress) {
return "\"ipAddresses\":[" +
Arrays.stream(ipAddress)
.map(ip -> "\"" + ip + "\"")
.collect(Collectors.joining(",")) +
"],";
}
private void assertRestart(int restartCount, Request request) throws IOException {
tester.assertResponse(request, 200, "{\"message\":\"Scheduled restart of " + restartCount + " matching nodes\"}");
}
private void assertReboot(int rebootCount, Request request) throws IOException {
tester.assertResponse(request, 200, "{\"message\":\"Scheduled reboot of " + rebootCount + " matching nodes\"}");
}
private void assertFile(Request request, String file) throws IOException {
tester.assertFile(request, file);
}
private void assertResponse(Request request, String file) throws IOException {
tester.assertResponse(request, file);
}
} |
Good point. PTAL | public void test_requests() throws Exception {
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertRestart(1, new Request("http:
new byte[0], Request.Method.POST));
assertRestart(2, new Request("http:
new byte[0], Request.Method.POST));
assertRestart(13, new Request("http:
new byte[0], Request.Method.POST));
tester.assertResponseContains(new Request("http:
"\"restartGeneration\":3");
assertReboot(14, new Request("http:
new byte[0], Request.Method.POST));
assertReboot(2, new Request("http:
new byte[0], Request.Method.POST));
assertReboot(19, new Request("http:
new byte[0], Request.Method.POST));
tester.assertResponseContains(new Request("http:
"\"rebootGeneration\":4");
assertResponse(new Request("http:
("[" + asNodeJson("host8.yahoo.com", "default", "127.0.8.1") + "," +
asNodeJson("host9.yahoo.com", "large-variant", "127.0.9.1", "::9:1") + "," +
asHostJson("parent2.yahoo.com", "large-variant", Optional.of(TenantName.from("myTenant")), "127.0.127.1", "::127:1") + "," +
asDockerNodeJson("host11.yahoo.com", "parent.host.yahoo.com", "::11") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 4 nodes to the provisioned state\"}");
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
tester.assertResponse(new Request("http:
("[" + asNodeJson("host8.yahoo.com", "default", "127.0.254.8") + "]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot add provisioned host host8.yahoo.com: A node with this name already exists\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Removed host9.yahoo.com\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to ready\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"ready\"");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to ready\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to failed\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"failed\"");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to active\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to parked\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"parked\"");
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Removed host8.yahoo.com\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved test-node-pool-102-2 to failed\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"failed\"");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved test-node-pool-102-2 to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved test-node-pool-102-2 to ready\"}");
tester.assertResponse(new Request("http:
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node with hostname 'test-node-pool-102-2'\"}");
assertResponse(new Request("http:
"{\"message\":\"Moved dockerhost1.yahoo.com, host4.yahoo.com to failed\"}");
assertResponse(new Request("http:
"{\"url\":\"http:
"{\"url\":\"http:
"{\"url\":\"http:
assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentRebootGeneration\": 1}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"flavor\": \"d-2-8-100\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentVespaVersion\": \"5.104.142\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"parentHostname\": \"parent.yahoo.com\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"ipAddresses\": [\"127.0.0.1\",\"::1\"]}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToRetire\": true}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentVespaVersion\": \"6.43.0\",\"currentDockerImage\": \"docker-registry.domain.tld:8080/dist/vespa:6.45.0\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"openStackId\": \"patched-openstackid\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"modelName\": \"foo\"}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToRetire\": true, \"wantToDeprovision\": true}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
tester.assertResponseContains(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"modelName\": null}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
tester.assertPartialResponse(new Request("http:
tester.container().handleRequest((new Request("http:
((OrchestratorMock) tester.container().components().getComponent(OrchestratorMock.class.getName()))
.suspend(new HostName("host4.yahoo.com"));
assertFile(new Request("http:
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Removed dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Permanently removed dockerhost1.yahoo.com\"}");
} | Utf8.toBytes("{\"wantToRetire\": true, \"wantToDeprovision\": true}"), Request.Method.PATCH), | public void test_requests() throws Exception {
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertRestart(1, new Request("http:
new byte[0], Request.Method.POST));
assertRestart(2, new Request("http:
new byte[0], Request.Method.POST));
assertRestart(13, new Request("http:
new byte[0], Request.Method.POST));
tester.assertResponseContains(new Request("http:
"\"restartGeneration\":3");
assertReboot(14, new Request("http:
new byte[0], Request.Method.POST));
assertReboot(2, new Request("http:
new byte[0], Request.Method.POST));
assertReboot(19, new Request("http:
new byte[0], Request.Method.POST));
tester.assertResponseContains(new Request("http:
"\"rebootGeneration\":4");
assertResponse(new Request("http:
("[" + asNodeJson("host8.yahoo.com", "default", "127.0.8.1") + "," +
asNodeJson("host9.yahoo.com", "large-variant", "127.0.9.1", "::9:1") + "," +
asHostJson("parent2.yahoo.com", "large-variant", Optional.of(TenantName.from("myTenant")), "127.0.127.1", "::127:1") + "," +
asDockerNodeJson("host11.yahoo.com", "parent.host.yahoo.com", "::11") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 4 nodes to the provisioned state\"}");
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
assertFile(new Request("http:
tester.assertResponse(new Request("http:
("[" + asNodeJson("host8.yahoo.com", "default", "127.0.254.8") + "]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot add provisioned host host8.yahoo.com: A node with this name already exists\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Removed host9.yahoo.com\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to ready\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"ready\"");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to ready\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to failed\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"failed\"");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to active\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host8.yahoo.com to parked\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"parked\"");
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Removed host8.yahoo.com\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved test-node-pool-102-2 to failed\"}");
tester.assertResponseContains(new Request("http:
"\"state\":\"failed\"");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved test-node-pool-102-2 to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved test-node-pool-102-2 to ready\"}");
tester.assertResponse(new Request("http:
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node with hostname 'test-node-pool-102-2'\"}");
assertResponse(new Request("http:
"{\"message\":\"Moved dockerhost1.yahoo.com, host4.yahoo.com to failed\"}");
assertResponse(new Request("http:
"{\"url\":\"http:
"{\"url\":\"http:
"{\"url\":\"http:
assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentRebootGeneration\": 1}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"flavor\": \"d-2-8-100\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentVespaVersion\": \"5.104.142\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"parentHostname\": \"parent.yahoo.com\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"ipAddresses\": [\"127.0.0.1\",\"::1\"]}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToRetire\": true}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentVespaVersion\": \"6.43.0\",\"currentDockerImage\": \"docker-registry.domain.tld:8080/dist/vespa:6.45.0\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"openStackId\": \"patched-openstackid\"}"), Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"modelName\": \"foo\"}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToRetire\": true}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToDeprovision\": true}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToDeprovision\": false, \"wantToRetire\": false}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"wantToDeprovision\": true, \"wantToRetire\": true}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
tester.assertResponseContains(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"modelName\": null}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
tester.assertPartialResponse(new Request("http:
tester.container().handleRequest((new Request("http:
((OrchestratorMock) tester.container().components().getComponent(OrchestratorMock.class.getName()))
.suspend(new HostName("host4.yahoo.com"));
assertFile(new Request("http:
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Removed dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Permanently removed dockerhost1.yahoo.com\"}");
} | class NodesV2ApiTest {
private RestApiTester tester;
@Before
public void createTester() {
tester = new RestApiTester();
}
@After
public void closeTester() {
tester.close();
}
/** This test gives examples of the node requests that can be made to nodes/v2 */
@Test
@Test
public void test_application_requests() throws Exception {
assertFile(new Request("http:
assertFile(new Request("http:
"application1.json");
assertFile(new Request("http:
"application2.json");
}
@Test
public void maintenance_requests() throws Exception {
assertResponse(new Request("http:
new byte[0], Request.Method.POST),
"{\"message\":\"Deactivated job 'NodeFailer'\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Re-activated job 'NodeFailer'\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.POST),
"{\"message\":\"Executed job 'PeriodicApplicationMaintainer'\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.POST),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such job 'foo'\"}");
}
@Test
public void post_with_patch_method_override_in_header_is_handled_as_patch() throws Exception {
Request req = new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"), Request.Method.POST);
req.getHeaders().add("X-HTTP-Method-Override", "PATCH");
assertResponse(req, "{\"message\":\"Updated host4.yahoo.com\"}");
}
@Test
public void post_with_invalid_method_override_in_header_gives_sane_error_message() throws Exception {
Request req = new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"), Request.Method.POST);
req.getHeaders().add("X-HTTP-Method-Override", "GET");
tester.assertResponse(req, 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Illegal X-HTTP-Method-Override header for POST request. Accepts 'PATCH' but got 'GET'\"}");
}
@Test
public void post_node_with_ip_address() throws Exception {
assertResponse(new Request("http:
("[" + asNodeJson("ipv4-host.yahoo.com", "default","127.0.0.1") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
("[" + asNodeJson("ipv6-host.yahoo.com", "default", "::1") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
("[" + asNodeJson("dual-stack-host.yahoo.com", "default", "127.0.254.254", "::254:254") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
}
@Test
public void post_node_with_duplicate_ip_address() throws Exception {
Request req = new Request("http:
("[" + asNodeJson("host-with-ip.yahoo.com", "default", "foo") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST);
tester.assertResponse(req, 400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Found one or more invalid addresses in [foo]: 'foo' is not an IP string literal.\"}");
tester.assertResponse(new Request("http:
"[" + asNodeJson("tenant-node-foo.yahoo.com", "default", "127.0.1.1") + "]",
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot assign [127.0.1.1] to tenant-node-foo.yahoo.com: [127.0.1.1] already assigned to host1.yahoo.com\"}");
tester.assertResponse(new Request("http:
"{\"ipAddresses\": [\"127.0.2.1\"]}",
Request.Method.PATCH), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'ipAddresses': Cannot assign [127.0.2.1] to test-node-pool-102-2: [127.0.2.1] already assigned to host2.yahoo.com\"}");
tester.assertResponse(new Request("http:
"[" + asHostJson("host200.yahoo.com", "default", Optional.empty(), "127.0.2.1") + "]",
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot assign [127.0.2.1] to host200.yahoo.com: [127.0.2.1] already assigned to host2.yahoo.com\"}");
tester.assertResponse(new Request("http:
"{\"ipAddresses\": [\"::104:3\"]}",
Request.Method.PATCH), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'ipAddresses': Cannot assign [::100:4, ::100:3, ::100:2, ::104:3] to dockerhost1.yahoo.com: [::104:3] already assigned to dockerhost5.yahoo.com\"}");
tester.assertResponse(new Request("http:
"[" + asNodeJson("cfghost42.yahoo.com", NodeType.confighost, "default", Optional.empty(), "127.0.42.1") + "]",
Request.Method.POST), 200,
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponse(new Request("http:
"[" + asDockerNodeJson("cfg42.yahoo.com", NodeType.config, "cfghost42.yahoo.com", "127.0.42.1") + "]",
Request.Method.POST), 200,
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponse(new Request("http:
"[" + asDockerNodeJson("proxy42.yahoo.com", NodeType.proxy, "cfghost42.yahoo.com", "127.0.42.1") + "]",
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot assign [127.0.42.1] to proxy42.yahoo.com: [127.0.42.1] already assigned to cfg42.yahoo.com\"}");
tester.assertResponse(new Request("http:
"[" + asNodeJson("cfghost43.yahoo.com", NodeType.confighost, "default", Optional.empty(), "127.0.43.1") + "]",
Request.Method.POST), 200,
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponse(new Request("http:
"{\"ipAddresses\": [\"127.0.43.1\"]}",
Request.Method.PATCH), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'ipAddresses': Cannot assign [127.0.43.1] to cfg42.yahoo.com: [127.0.43.1] already assigned to cfghost43.yahoo.com\"}");
}
@Test
public void post_controller_node() throws Exception {
String data = "[{\"hostname\":\"controller1.yahoo.com\", \"openStackId\":\"fake-controller1.yahoo.com\"," +
createIpAddresses("127.0.0.1") +
"\"flavor\":\"default\"" +
", \"type\":\"controller\"}]";
assertResponse(new Request("http:
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertFile(new Request("http:
}
@Test
public void fails_to_ready_node_with_hard_fail() throws Exception {
assertResponse(new Request("http:
("[" + asNodeJson("host12.yahoo.com", "default") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
String msg = "Actual disk space (2TB) differs from spec (3TB)";
assertResponse(new Request("http:
Utf8.toBytes("{\"reports\":{\"diskSpace\":{\"createdMillis\":2,\"description\":\"" + msg + "\",\"type\": \"HARD_FAIL\"}}}"),
Request.Method.PATCH),
"{\"message\":\"Updated host12.yahoo.com\"}");
tester.assertResponse(new Request("http:
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"provisioned host host12.yahoo.com cannot be readied because it has " +
"hard failures: [diskSpace reported 1970-01-01T00:00:00.002Z: " + msg + "]\"}");
}
@Test
public void patching_dirty_node_does_not_increase_reboot_generation() throws Exception {
assertResponse(new Request("http:
("[" + asNodeJson("foo.yahoo.com", "default") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to failed\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to dirty\"}");
tester.assertResponseContains(new Request("http:
"\"rebootGeneration\":1");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentRebootGeneration\": 42}"), Request.Method.PATCH),
"{\"message\":\"Updated foo.yahoo.com\"}");
tester.assertResponseContains(new Request("http:
"\"rebootGeneration\":1");
}
@Test
public void acl_request_by_tenant_node() throws Exception {
String hostname = "foo.yahoo.com";
assertResponse(new Request("http:
("[" + asNodeJson(hostname, "default", "127.0.222.1") + "]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to ready\"}");
assertFile(new Request("http:
}
@Test
public void acl_request_by_config_server() throws Exception {
assertFile(new Request("http:
}
@Test
public void test_invalid_requests() throws Exception {
tester.assertResponse(new Request("http:
new byte[0], Request.Method.GET),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node with hostname 'node-does-not-exist'\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not move node-does-not-exist to failed: Node not found\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host1.yahoo.com to failed\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot make failed host host1.yahoo.com allocated to tenant1.application1.instance1 as 'container/id1/0/0' available for new allocation as it is not in state [dirty]\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host1.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host1.yahoo.com to ready\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to parked\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot make parked host host2.yahoo.com allocated to tenant2.application2.instance2 as 'content/id2/0/0' available for new allocation as it is not in state [dirty]\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to ready\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node with hostname 'host2.yahoo.com'\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"active child node host4.yahoo.com allocated to tenant3.application3.instance3 as 'content/id3/0/0' is currently allocated and cannot be removed\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": \"1\"}"), Request.Method.PATCH),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'currentRestartGeneration': Expected a LONG value, got a STRING\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"flavor\": 1}"), Request.Method.PATCH),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'flavor': Expected a STRING value, got a LONG\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT), 404,
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not move host2.yahoo.com to active: Node not found\"}");
tester.assertResponse(new Request("http:
("[" + asNodeJson("host8.yahoo.com", "default", "127.0.254.1", "::254:1") + "," +
asNodeJson("host8.yahoo.com", "large-variant", "127.0.253.1", "::253:1") + "]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot add nodes: provisioned host host8.yahoo.com is duplicated in the argument list\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"modelName\": \"foo\"}"), Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'modelName': A child node cannot have model name set\"}");
}
@Test
public void test_node_patching() throws Exception {
assertResponse(new Request("http:
Utf8.toBytes("{" +
"\"currentRestartGeneration\": 1," +
"\"currentRebootGeneration\": 3," +
"\"flavor\": \"medium-disk\"," +
"\"currentVespaVersion\": \"5.104.142\"," +
"\"failCount\": 0," +
"\"parentHostname\": \"parent.yahoo.com\"" +
"}"
),
Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"),
Request.Method.PATCH),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node found with hostname doesnotexist.yahoo.com\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'currentRestartGeneration': Node is not allocated\"}");
}
@Test
public void test_node_patch_to_remove_docker_ready_fields() throws Exception {
assertResponse(new Request("http:
Utf8.toBytes("{" +
"\"currentVespaVersion\": \"\"," +
"\"currentDockerImage\": \"\"" +
"}"
),
Request.Method.PATCH),
"{\"message\":\"Updated host5.yahoo.com\"}");
assertFile(new Request("http:
}
@Test
public void test_reports_patching() throws IOException {
assertResponse(new Request("http:
Utf8.toBytes("{" +
" \"reports\": {" +
" \"actualCpuCores\": {" +
" \"createdMillis\": 1, " +
" \"description\": \"Actual number of CPU cores (2) differs from spec (4)\"," +
" \"type\": \"HARD_FAIL\"," +
" \"value\":2" +
" }," +
" \"diskSpace\": {" +
" \"createdMillis\": 2, " +
" \"description\": \"Actual disk space (2TB) differs from spec (3TB)\"," +
" \"type\": \"HARD_FAIL\"," +
" \"details\": {" +
" \"inGib\": 3," +
" \"disks\": [\"/dev/sda1\", \"/dev/sdb3\"]" +
" }" +
" }" +
" }" +
"}"),
Request.Method.PATCH),
"{\"message\":\"Updated host6.yahoo.com\"}");
assertFile(new Request("http:
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"reports\": {}}"),
Request.Method.PATCH),
200,
"{\"message\":\"Updated host6.yahoo.com\"}");
assertFile(new Request("http:
tester.assertResponse(new Request("http:
Utf8.toBytes("{" +
" \"reports\": {" +
" \"actualCpuCores\": {" +
" \"createdMillis\": 3 " +
" }" +
" }" +
"}"),
Request.Method.PATCH),
200,
"{\"message\":\"Updated host6.yahoo.com\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"reports\": { \"diskSpace\": null } }"),
Request.Method.PATCH),
"{\"message\":\"Updated host6.yahoo.com\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"reports\": null }"),
Request.Method.PATCH),
"{\"message\":\"Updated host6.yahoo.com\"}");
assertFile(new Request("http:
}
@Test
public void test_upgrade() throws IOException {
assertResponse(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.456 for nodes of type config\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.456 for nodes of type confighost\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.456 for nodes of type controller\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"confighost\":\"6.123.456\",\"controller\":\"6.123.456\"},\"osVersions\":{},\"dockerImages\":{}}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Target version for type tenant is not allowed\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"At least one of 'version', 'osVersion' or 'dockerImage' must be set\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.1\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot downgrade version without setting 'force'. " +
"Current target version: 6.123.456, attempted to set target version: 6.123.1\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.1\",\"force\":true}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.1 for nodes of type confighost\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"confighost\":\"6.123.1\",\"controller\":\"6.123.456\"},\"osVersions\":{},\"dockerImages\":{}}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"version\": null}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot downgrade version without setting 'force'. Current target version: 6.123.1, attempted to set target version: 0.0.0\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": null, \"force\": true}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 0.0.0 for nodes of type confighost\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"controller\":\"6.123.456\"},\"osVersions\":{},\"dockerImages\":{}}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.5.2 for nodes of type confighost\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.5.2 for nodes of type host\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"controller\":\"6.123.456\"},\"osVersions\":{\"host\":\"7.5.2\",\"confighost\":\"7.5.2\"},\"dockerImages\":{}}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.124.42\", \"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.124.42, osVersion to 7.5.2 for nodes of type confighost\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Node type 'config' does not support OS upgrades\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.4.2\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot set target OS version to 7.4.2 without setting 'force', as it's lower than the current version: 7.5.2\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.4.2\", \"force\": true}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.4.2 for nodes of type confighost\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": null}"),
Request.Method.PATCH),
200,
"{\"message\":\"Set osVersion to null for nodes of type confighost\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"dockerImage\": \"my-repo.my-domain.example:1234/repo/tenant\"}"),
Request.Method.PATCH),
"{\"message\":\"Set docker image to my-repo.my-domain.example:1234/repo/tenant for nodes of type tenant\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"dockerImage\": \"my-repo.my-domain.example:1234/repo/image\"}"),
Request.Method.PATCH),
"{\"message\":\"Set docker image to my-repo.my-domain.example:1234/repo/image for nodes of type config\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"confighost\":\"6.124.42\",\"controller\":\"6.123.456\"},\"osVersions\":{\"host\":\"7.5.2\"},\"dockerImages\":{\"tenant\":\"my-repo.my-domain.example:1234/repo/tenant\",\"config\":\"my-repo.my-domain.example:1234/repo/image\"}}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"dockerImage\": \"my-repo.my-domain.example:1234/repo/image\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Setting docker image for confighost nodes is unsupported\"}");
}
@Test
public void test_os_version() throws Exception {
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.5.2 for nodes of type host\"}");
var nodeRepository = (NodeRepository)tester.container().components().getComponent(MockNodeRepository.class.getName());
var osUpgradeActivator = new OsUpgradeActivator(nodeRepository, Duration.ofDays(1));
osUpgradeActivator.run();
Response r = tester.container().handleRequest(new Request("http:
assertFalse("Response omits wantedOsVersions field", r.getBodyAsString().contains("wantedOsVersion"));
assertResponse(new Request("http:
Utf8.toBytes("{\"currentOsVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"currentOsVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost2.yahoo.com\"}");
assertResponse(new Request("http:
"{\"nodes\":[" +
"{\"url\":\"http:
"{\"url\":\"http:
"]}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.42.1\", \"upgradeBudget\": \"PT24H\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.42.1, upgradeBudget to PT24H for nodes of type host\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.42.1\", \"upgradeBudget\": \"foo\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid duration 'foo': Text cannot be parsed to a Duration\"}");
}
@Test
public void test_firmware_upgrades() throws IOException {
assertResponse(new Request("http:
Utf8.toBytes("{\"currentFirmwareCheck\":100}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
"{\"message\":\"Will request firmware checks on all hosts.\"}");
assertFile(new Request("http:
"dockerhost1-with-firmware-data.json");
assertFile(new Request("http:
"node1.json");
assertResponse(new Request("http:
"{\"message\":\"Cancelled outstanding requests for firmware checks\"}");
}
@Test
public void test_capacity() throws Exception {
assertFile(new Request("http:
assertFile(new Request("http:
List<String> hostsToRemove = List.of(
"dockerhost1.yahoo.com",
"dockerhost2.yahoo.com",
"dockerhost3.yahoo.com",
"dockerhost4.yahoo.com"
);
String requestUriTemplate = "http:
assertFile(new Request(String.format(requestUriTemplate,
String.join(",", hostsToRemove.subList(0, 3)))),
"capacity-hostremoval-possible.json");
assertFile(new Request(String.format(requestUriTemplate,
String.join(",", hostsToRemove))),
"capacity-hostremoval-impossible.json");
}
/** Tests the rendering of each node separately to make it easier to find errors */
@Test
public void test_single_node_rendering() throws Exception {
for (int i = 1; i <= 14; i++) {
if (i == 8 || i == 9 || i == 11 || i == 12) continue;
assertFile(new Request("http:
}
}
@Test
public void test_flavor_overrides() throws Exception {
String host = "parent2.yahoo.com";
tester.assertResponse(new Request("http:
("[{\"hostname\":\"" + host + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," +
"\"flavor\":\"large-variant\",\"resources\":{\"diskGb\":1234,\"memoryGb\":4321}}]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Can only override disk GB for configured flavor\"}");
assertResponse(new Request("http:
("[{\"hostname\":\"" + host + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," +
"\"flavor\":\"large-variant\",\"type\":\"host\",\"resources\":{\"diskGb\":1234}}]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponseContains(new Request("http:
"\"resources\":{\"vcpu\":64.0,\"memoryGb\":128.0,\"diskGb\":1234.0,\"bandwidthGbps\":15.0,\"diskSpeed\":\"fast\",\"storageType\":\"remote\"}");
String tenant = "node-1-3.yahoo.com";
String resources = "\"resources\":{\"vcpu\":64.0,\"memoryGb\":128.0,\"diskGb\":1234.0,\"bandwidthGbps\":15.0,\"diskSpeed\":\"slow\",\"storageType\":\"remote\"}";
assertResponse(new Request("http:
("[{\"hostname\":\"" + tenant + "\"," + createIpAddresses("::2") + "\"openStackId\":\"osid-124\"," +
"\"type\":\"tenant\"," + resources + "}]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponseContains(new Request("http:
tester.assertResponse(new Request("http:
"{\"minDiskAvailableGb\":5432,\"minMainMemoryAvailableGb\":2345}".getBytes(StandardCharsets.UTF_8),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'minMainMemoryAvailableGb': Can only override disk GB for configured flavor\"}");
assertResponse(new Request("http:
"{\"minDiskAvailableGb\":5432}".getBytes(StandardCharsets.UTF_8),
Request.Method.PATCH),
"{\"message\":\"Updated " + host + "\"}");
tester.assertResponseContains(new Request("http:
"\"resources\":{\"vcpu\":64.0,\"memoryGb\":128.0,\"diskGb\":5432.0,\"bandwidthGbps\":15.0,\"diskSpeed\":\"fast\",\"storageType\":\"remote\"}");
}
@Test
public void test_node_resources() throws Exception {
String hostname = "node123.yahoo.com";
String resources = "\"resources\":{\"vcpu\":5.0,\"memoryGb\":4321.0,\"diskGb\":1234.0,\"bandwidthGbps\":0.3,\"diskSpeed\":\"slow\",\"storageType\":\"local\"}";
tester.assertResponse(new Request("http:
("[{\"hostname\":\"" + hostname + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," +
resources.replace("\"memoryGb\":4321.0,", "") + "}]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Required field 'memoryGb' is missing\"}");
assertResponse(new Request("http:
("[{\"hostname\":\"" + hostname + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," + resources + "}]")
.getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponseContains(new Request("http:
assertResponse(new Request("http:
"{\"diskGb\":12,\"memoryGb\":34,\"vcpu\":56,\"fastDisk\":true,\"remoteStorage\":true,\"bandwidthGbps\":78.0}".getBytes(StandardCharsets.UTF_8),
Request.Method.PATCH),
"{\"message\":\"Updated " + hostname + "\"}");
tester.assertResponseContains(new Request("http:
"\"resources\":{\"vcpu\":56.0,\"memoryGb\":34.0,\"diskGb\":12.0,\"bandwidthGbps\":78.0,\"diskSpeed\":\"fast\",\"storageType\":\"remote\"}");
}
private static String asDockerNodeJson(String hostname, String parentHostname, String... ipAddress) {
return asDockerNodeJson(hostname, NodeType.tenant, parentHostname, ipAddress);
}
private static String asDockerNodeJson(String hostname, NodeType nodeType, String parentHostname, String... ipAddress) {
return "{\"hostname\":\"" + hostname + "\", \"parentHostname\":\"" + parentHostname + "\"," +
createIpAddresses(ipAddress) +
"\"openStackId\":\"" + hostname + "\",\"flavor\":\"d-1-1-100\"" +
(nodeType != NodeType.tenant ? ",\"type\":\"" + nodeType + "\"" : "") +
"}";
}
private static String asNodeJson(String hostname, String flavor, String... ipAddress) {
return "{\"hostname\":\"" + hostname + "\", \"openStackId\":\"" + hostname + "\"," +
createIpAddresses(ipAddress) +
"\"flavor\":\"" + flavor + "\"}";
}
private static String asHostJson(String hostname, String flavor, Optional<TenantName> reservedTo, String... ipAddress) {
return asNodeJson(hostname, NodeType.host, flavor, reservedTo, ipAddress);
}
private static String asNodeJson(String hostname, NodeType nodeType, String flavor, Optional<TenantName> reservedTo, String... ipAddress) {
return "{\"hostname\":\"" + hostname + "\", \"openStackId\":\"" + hostname + "\"," +
createIpAddresses(ipAddress) +
"\"flavor\":\"" + flavor + "\"" +
(reservedTo.isPresent() ? ", \"reservedTo\":\"" + reservedTo.get().value() + "\"" : "") +
", \"type\":\"" + nodeType + "\"}";
}
private static String createIpAddresses(String... ipAddress) {
return "\"ipAddresses\":[" +
Arrays.stream(ipAddress)
.map(ip -> "\"" + ip + "\"")
.collect(Collectors.joining(",")) +
"],";
}
private void assertRestart(int restartCount, Request request) throws IOException {
tester.assertResponse(request, 200, "{\"message\":\"Scheduled restart of " + restartCount + " matching nodes\"}");
}
private void assertReboot(int rebootCount, Request request) throws IOException {
tester.assertResponse(request, 200, "{\"message\":\"Scheduled reboot of " + rebootCount + " matching nodes\"}");
}
private void assertFile(Request request, String file) throws IOException {
tester.assertFile(request, file);
}
private void assertResponse(Request request, String file) throws IOException {
tester.assertResponse(request, file);
}
} | class NodesV2ApiTest {
private RestApiTester tester;
@Before
public void createTester() {
tester = new RestApiTester();
}
@After
public void closeTester() {
tester.close();
}
/** This test gives examples of the node requests that can be made to nodes/v2 */
@Test
@Test
public void test_application_requests() throws Exception {
assertFile(new Request("http:
assertFile(new Request("http:
"application1.json");
assertFile(new Request("http:
"application2.json");
}
@Test
public void maintenance_requests() throws Exception {
assertResponse(new Request("http:
new byte[0], Request.Method.POST),
"{\"message\":\"Deactivated job 'NodeFailer'\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
"{\"message\":\"Re-activated job 'NodeFailer'\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.POST),
"{\"message\":\"Executed job 'PeriodicApplicationMaintainer'\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.POST),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such job 'foo'\"}");
}
@Test
public void post_with_patch_method_override_in_header_is_handled_as_patch() throws Exception {
Request req = new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"), Request.Method.POST);
req.getHeaders().add("X-HTTP-Method-Override", "PATCH");
assertResponse(req, "{\"message\":\"Updated host4.yahoo.com\"}");
}
@Test
public void post_with_invalid_method_override_in_header_gives_sane_error_message() throws Exception {
Request req = new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"), Request.Method.POST);
req.getHeaders().add("X-HTTP-Method-Override", "GET");
tester.assertResponse(req, 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Illegal X-HTTP-Method-Override header for POST request. Accepts 'PATCH' but got 'GET'\"}");
}
@Test
public void post_node_with_ip_address() throws Exception {
assertResponse(new Request("http:
("[" + asNodeJson("ipv4-host.yahoo.com", "default","127.0.0.1") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
("[" + asNodeJson("ipv6-host.yahoo.com", "default", "::1") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
("[" + asNodeJson("dual-stack-host.yahoo.com", "default", "127.0.254.254", "::254:254") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
}
@Test
public void post_node_with_duplicate_ip_address() throws Exception {
Request req = new Request("http:
("[" + asNodeJson("host-with-ip.yahoo.com", "default", "foo") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST);
tester.assertResponse(req, 400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Found one or more invalid addresses in [foo]: 'foo' is not an IP string literal.\"}");
tester.assertResponse(new Request("http:
"[" + asNodeJson("tenant-node-foo.yahoo.com", "default", "127.0.1.1") + "]",
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot assign [127.0.1.1] to tenant-node-foo.yahoo.com: [127.0.1.1] already assigned to host1.yahoo.com\"}");
tester.assertResponse(new Request("http:
"{\"ipAddresses\": [\"127.0.2.1\"]}",
Request.Method.PATCH), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'ipAddresses': Cannot assign [127.0.2.1] to test-node-pool-102-2: [127.0.2.1] already assigned to host2.yahoo.com\"}");
tester.assertResponse(new Request("http:
"[" + asHostJson("host200.yahoo.com", "default", Optional.empty(), "127.0.2.1") + "]",
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot assign [127.0.2.1] to host200.yahoo.com: [127.0.2.1] already assigned to host2.yahoo.com\"}");
tester.assertResponse(new Request("http:
"{\"ipAddresses\": [\"::104:3\"]}",
Request.Method.PATCH), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'ipAddresses': Cannot assign [::100:4, ::100:3, ::100:2, ::104:3] to dockerhost1.yahoo.com: [::104:3] already assigned to dockerhost5.yahoo.com\"}");
tester.assertResponse(new Request("http:
"[" + asNodeJson("cfghost42.yahoo.com", NodeType.confighost, "default", Optional.empty(), "127.0.42.1") + "]",
Request.Method.POST), 200,
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponse(new Request("http:
"[" + asDockerNodeJson("cfg42.yahoo.com", NodeType.config, "cfghost42.yahoo.com", "127.0.42.1") + "]",
Request.Method.POST), 200,
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponse(new Request("http:
"[" + asDockerNodeJson("proxy42.yahoo.com", NodeType.proxy, "cfghost42.yahoo.com", "127.0.42.1") + "]",
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot assign [127.0.42.1] to proxy42.yahoo.com: [127.0.42.1] already assigned to cfg42.yahoo.com\"}");
tester.assertResponse(new Request("http:
"[" + asNodeJson("cfghost43.yahoo.com", NodeType.confighost, "default", Optional.empty(), "127.0.43.1") + "]",
Request.Method.POST), 200,
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponse(new Request("http:
"{\"ipAddresses\": [\"127.0.43.1\"]}",
Request.Method.PATCH), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'ipAddresses': Cannot assign [127.0.43.1] to cfg42.yahoo.com: [127.0.43.1] already assigned to cfghost43.yahoo.com\"}");
}
@Test
public void post_controller_node() throws Exception {
String data = "[{\"hostname\":\"controller1.yahoo.com\", \"openStackId\":\"fake-controller1.yahoo.com\"," +
createIpAddresses("127.0.0.1") +
"\"flavor\":\"default\"" +
", \"type\":\"controller\"}]";
assertResponse(new Request("http:
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertFile(new Request("http:
}
@Test
public void fails_to_ready_node_with_hard_fail() throws Exception {
assertResponse(new Request("http:
("[" + asHostJson("host12.yahoo.com", "default", Optional.empty()) + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
String msg = "Actual disk space (2TB) differs from spec (3TB)";
assertResponse(new Request("http:
Utf8.toBytes("{\"reports\":{\"diskSpace\":{\"createdMillis\":2,\"description\":\"" + msg + "\",\"type\": \"HARD_FAIL\"}}}"),
Request.Method.PATCH),
"{\"message\":\"Updated host12.yahoo.com\"}");
tester.assertResponse(new Request("http:
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"provisioned host host12.yahoo.com cannot be readied because it has " +
"hard failures: [diskSpace reported 1970-01-01T00:00:00.002Z: " + msg + "]\"}");
}
@Test
public void patching_dirty_node_does_not_increase_reboot_generation() throws Exception {
assertResponse(new Request("http:
("[" + asNodeJson("foo.yahoo.com", "default") + "]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to failed\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to dirty\"}");
tester.assertResponseContains(new Request("http:
"\"rebootGeneration\":1");
assertResponse(new Request("http:
Utf8.toBytes("{\"currentRebootGeneration\": 42}"), Request.Method.PATCH),
"{\"message\":\"Updated foo.yahoo.com\"}");
tester.assertResponseContains(new Request("http:
"\"rebootGeneration\":1");
}
@Test
public void acl_request_by_tenant_node() throws Exception {
String hostname = "foo.yahoo.com";
assertResponse(new Request("http:
("[" + asNodeJson(hostname, "default", "127.0.222.1") + "]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved foo.yahoo.com to ready\"}");
assertFile(new Request("http:
}
@Test
public void acl_request_by_config_server() throws Exception {
assertFile(new Request("http:
}
@Test
public void test_invalid_requests() throws Exception {
tester.assertResponse(new Request("http:
new byte[0], Request.Method.GET),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node with hostname 'node-does-not-exist'\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not move node-does-not-exist to failed: Node not found\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host1.yahoo.com to failed\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot make failed host host1.yahoo.com allocated to tenant1.application1.instance1 as 'container/id1/0/0' available for new allocation as it is not in state [dirty]\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host1.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host1.yahoo.com to ready\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to parked\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot make parked host host2.yahoo.com allocated to tenant2.application2.instance2 as 'content/id2/0/0' available for new allocation as it is not in state [dirty]\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to dirty\"}");
assertResponse(new Request("http:
new byte[0], Request.Method.PUT),
"{\"message\":\"Moved host2.yahoo.com to ready\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node with hostname 'host2.yahoo.com'\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.DELETE),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"active child node host4.yahoo.com allocated to tenant3.application3.instance3 as 'content/id3/0/0' is currently allocated and cannot be removed\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": \"1\"}"), Request.Method.PATCH),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'currentRestartGeneration': Expected a LONG value, got a STRING\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"flavor\": 1}"), Request.Method.PATCH),
400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'flavor': Expected a STRING value, got a LONG\"}");
tester.assertResponse(new Request("http:
new byte[0], Request.Method.PUT), 404,
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not move host2.yahoo.com to active: Node not found\"}");
tester.assertResponse(new Request("http:
("[" + asNodeJson("host8.yahoo.com", "default", "127.0.254.1", "::254:1") + "," +
asNodeJson("host8.yahoo.com", "large-variant", "127.0.253.1", "::253:1") + "]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST), 400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot add nodes: provisioned host host8.yahoo.com is duplicated in the argument list\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"modelName\": \"foo\"}"), Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'modelName': A child node cannot have model name set\"}");
}
@Test
public void test_node_patching() throws Exception {
assertResponse(new Request("http:
Utf8.toBytes("{" +
"\"currentRestartGeneration\": 1," +
"\"currentRebootGeneration\": 3," +
"\"flavor\": \"medium-disk\"," +
"\"currentVespaVersion\": \"5.104.142\"," +
"\"failCount\": 0," +
"\"parentHostname\": \"parent.yahoo.com\"" +
"}"
),
Request.Method.PATCH),
"{\"message\":\"Updated host4.yahoo.com\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"),
Request.Method.PATCH),
404, "{\"error-code\":\"NOT_FOUND\",\"message\":\"No node found with hostname doesnotexist.yahoo.com\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"currentRestartGeneration\": 1}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'currentRestartGeneration': Node is not allocated\"}");
}
@Test
public void test_node_patch_to_remove_docker_ready_fields() throws Exception {
assertResponse(new Request("http:
Utf8.toBytes("{" +
"\"currentVespaVersion\": \"\"," +
"\"currentDockerImage\": \"\"" +
"}"
),
Request.Method.PATCH),
"{\"message\":\"Updated host5.yahoo.com\"}");
assertFile(new Request("http:
}
@Test
public void test_reports_patching() throws IOException {
assertResponse(new Request("http:
Utf8.toBytes("{" +
" \"reports\": {" +
" \"actualCpuCores\": {" +
" \"createdMillis\": 1, " +
" \"description\": \"Actual number of CPU cores (2) differs from spec (4)\"," +
" \"type\": \"HARD_FAIL\"," +
" \"value\":2" +
" }," +
" \"diskSpace\": {" +
" \"createdMillis\": 2, " +
" \"description\": \"Actual disk space (2TB) differs from spec (3TB)\"," +
" \"type\": \"HARD_FAIL\"," +
" \"details\": {" +
" \"inGib\": 3," +
" \"disks\": [\"/dev/sda1\", \"/dev/sdb3\"]" +
" }" +
" }" +
" }" +
"}"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"reports\": {}}"),
Request.Method.PATCH),
200,
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
tester.assertResponse(new Request("http:
Utf8.toBytes("{" +
" \"reports\": {" +
" \"actualCpuCores\": {" +
" \"createdMillis\": 3 " +
" }" +
" }" +
"}"),
Request.Method.PATCH),
200,
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"reports\": { \"diskSpace\": null } }"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"reports\": null }"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
}
@Test
public void test_upgrade() throws IOException {
assertResponse(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.456 for nodes of type config\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.456 for nodes of type confighost\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.456 for nodes of type controller\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"confighost\":\"6.123.456\",\"controller\":\"6.123.456\"},\"osVersions\":{},\"dockerImages\":{}}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.456\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Target version for type tenant is not allowed\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"At least one of 'version', 'osVersion' or 'dockerImage' must be set\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.1\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot downgrade version without setting 'force'. " +
"Current target version: 6.123.456, attempted to set target version: 6.123.1\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.123.1\",\"force\":true}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.123.1 for nodes of type confighost\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"confighost\":\"6.123.1\",\"controller\":\"6.123.456\"},\"osVersions\":{},\"dockerImages\":{}}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"version\": null}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot downgrade version without setting 'force'. Current target version: 6.123.1, attempted to set target version: 0.0.0\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": null, \"force\": true}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 0.0.0 for nodes of type confighost\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"controller\":\"6.123.456\"},\"osVersions\":{},\"dockerImages\":{}}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.5.2 for nodes of type confighost\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.5.2 for nodes of type host\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"controller\":\"6.123.456\"},\"osVersions\":{\"host\":\"7.5.2\",\"confighost\":\"7.5.2\"},\"dockerImages\":{}}");
assertResponse(new Request("http:
Utf8.toBytes("{\"version\": \"6.124.42\", \"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set version to 6.124.42, osVersion to 7.5.2 for nodes of type confighost\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Node type 'config' does not support OS upgrades\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.4.2\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot set target OS version to 7.4.2 without setting 'force', as it's lower than the current version: 7.5.2\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.4.2\", \"force\": true}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.4.2 for nodes of type confighost\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": null}"),
Request.Method.PATCH),
200,
"{\"message\":\"Set osVersion to null for nodes of type confighost\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"dockerImage\": \"my-repo.my-domain.example:1234/repo/tenant\"}"),
Request.Method.PATCH),
"{\"message\":\"Set docker image to my-repo.my-domain.example:1234/repo/tenant for nodes of type tenant\"}");
assertResponse(new Request("http:
Utf8.toBytes("{\"dockerImage\": \"my-repo.my-domain.example:1234/repo/image\"}"),
Request.Method.PATCH),
"{\"message\":\"Set docker image to my-repo.my-domain.example:1234/repo/image for nodes of type config\"}");
assertResponse(new Request("http:
"{\"versions\":{\"config\":\"6.123.456\",\"confighost\":\"6.124.42\",\"controller\":\"6.123.456\"},\"osVersions\":{\"host\":\"7.5.2\"},\"dockerImages\":{\"tenant\":\"my-repo.my-domain.example:1234/repo/tenant\",\"config\":\"my-repo.my-domain.example:1234/repo/image\"}}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"dockerImage\": \"my-repo.my-domain.example:1234/repo/image\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Setting docker image for confighost nodes is unsupported\"}");
}
@Test
public void test_os_version() throws Exception {
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.5.2 for nodes of type host\"}");
var nodeRepository = (NodeRepository)tester.container().components().getComponent(MockNodeRepository.class.getName());
var osUpgradeActivator = new OsUpgradeActivator(nodeRepository, Duration.ofDays(1));
osUpgradeActivator.run();
Response r = tester.container().handleRequest(new Request("http:
assertFalse("Response omits wantedOsVersions field", r.getBodyAsString().contains("wantedOsVersion"));
assertResponse(new Request("http:
Utf8.toBytes("{\"currentOsVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertFile(new Request("http:
assertResponse(new Request("http:
Utf8.toBytes("{\"currentOsVersion\": \"7.5.2\"}"),
Request.Method.PATCH),
"{\"message\":\"Updated dockerhost2.yahoo.com\"}");
assertResponse(new Request("http:
"{\"nodes\":[" +
"{\"url\":\"http:
"{\"url\":\"http:
"]}");
assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.42.1\", \"upgradeBudget\": \"PT24H\"}"),
Request.Method.PATCH),
"{\"message\":\"Set osVersion to 7.42.1, upgradeBudget to PT24H for nodes of type host\"}");
tester.assertResponse(new Request("http:
Utf8.toBytes("{\"osVersion\": \"7.42.1\", \"upgradeBudget\": \"foo\"}"),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid duration 'foo': Text cannot be parsed to a Duration\"}");
}
@Test
public void test_firmware_upgrades() throws IOException {
assertResponse(new Request("http:
Utf8.toBytes("{\"currentFirmwareCheck\":100}"), Request.Method.PATCH),
"{\"message\":\"Updated dockerhost1.yahoo.com\"}");
assertResponse(new Request("http:
"{\"message\":\"Will request firmware checks on all hosts.\"}");
assertFile(new Request("http:
"dockerhost1-with-firmware-data.json");
assertFile(new Request("http:
"node1.json");
assertResponse(new Request("http:
"{\"message\":\"Cancelled outstanding requests for firmware checks\"}");
}
@Test
public void test_capacity() throws Exception {
assertFile(new Request("http:
assertFile(new Request("http:
List<String> hostsToRemove = List.of(
"dockerhost1.yahoo.com",
"dockerhost2.yahoo.com",
"dockerhost3.yahoo.com",
"dockerhost4.yahoo.com"
);
String requestUriTemplate = "http:
assertFile(new Request(String.format(requestUriTemplate,
String.join(",", hostsToRemove.subList(0, 3)))),
"capacity-hostremoval-possible.json");
assertFile(new Request(String.format(requestUriTemplate,
String.join(",", hostsToRemove))),
"capacity-hostremoval-impossible.json");
}
/** Tests the rendering of each node separately to make it easier to find errors */
@Test
public void test_single_node_rendering() throws Exception {
for (int i = 1; i <= 14; i++) {
if (i == 8 || i == 9 || i == 11 || i == 12) continue;
assertFile(new Request("http:
}
}
@Test
public void test_flavor_overrides() throws Exception {
String host = "parent2.yahoo.com";
tester.assertResponse(new Request("http:
("[{\"hostname\":\"" + host + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," +
"\"flavor\":\"large-variant\",\"resources\":{\"diskGb\":1234,\"memoryGb\":4321}}]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Can only override disk GB for configured flavor\"}");
assertResponse(new Request("http:
("[{\"hostname\":\"" + host + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," +
"\"flavor\":\"large-variant\",\"type\":\"host\",\"resources\":{\"diskGb\":1234}}]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponseContains(new Request("http:
"\"resources\":{\"vcpu\":64.0,\"memoryGb\":128.0,\"diskGb\":1234.0,\"bandwidthGbps\":15.0,\"diskSpeed\":\"fast\",\"storageType\":\"remote\"}");
String tenant = "node-1-3.yahoo.com";
String resources = "\"resources\":{\"vcpu\":64.0,\"memoryGb\":128.0,\"diskGb\":1234.0,\"bandwidthGbps\":15.0,\"diskSpeed\":\"slow\",\"storageType\":\"remote\"}";
assertResponse(new Request("http:
("[{\"hostname\":\"" + tenant + "\"," + createIpAddresses("::2") + "\"openStackId\":\"osid-124\"," +
"\"type\":\"tenant\"," + resources + "}]").
getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponseContains(new Request("http:
tester.assertResponse(new Request("http:
"{\"minDiskAvailableGb\":5432,\"minMainMemoryAvailableGb\":2345}".getBytes(StandardCharsets.UTF_8),
Request.Method.PATCH),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not set field 'minMainMemoryAvailableGb': Can only override disk GB for configured flavor\"}");
assertResponse(new Request("http:
"{\"minDiskAvailableGb\":5432}".getBytes(StandardCharsets.UTF_8),
Request.Method.PATCH),
"{\"message\":\"Updated " + host + "\"}");
tester.assertResponseContains(new Request("http:
"\"resources\":{\"vcpu\":64.0,\"memoryGb\":128.0,\"diskGb\":5432.0,\"bandwidthGbps\":15.0,\"diskSpeed\":\"fast\",\"storageType\":\"remote\"}");
}
@Test
public void test_node_resources() throws Exception {
String hostname = "node123.yahoo.com";
String resources = "\"resources\":{\"vcpu\":5.0,\"memoryGb\":4321.0,\"diskGb\":1234.0,\"bandwidthGbps\":0.3,\"diskSpeed\":\"slow\",\"storageType\":\"local\"}";
tester.assertResponse(new Request("http:
("[{\"hostname\":\"" + hostname + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," +
resources.replace("\"memoryGb\":4321.0,", "") + "}]").getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
400,
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Required field 'memoryGb' is missing\"}");
assertResponse(new Request("http:
("[{\"hostname\":\"" + hostname + "\"," + createIpAddresses("::1") + "\"openStackId\":\"osid-123\"," + resources + "}]")
.getBytes(StandardCharsets.UTF_8),
Request.Method.POST),
"{\"message\":\"Added 1 nodes to the provisioned state\"}");
tester.assertResponseContains(new Request("http:
assertResponse(new Request("http:
"{\"diskGb\":12,\"memoryGb\":34,\"vcpu\":56,\"fastDisk\":true,\"remoteStorage\":true,\"bandwidthGbps\":78.0}".getBytes(StandardCharsets.UTF_8),
Request.Method.PATCH),
"{\"message\":\"Updated " + hostname + "\"}");
tester.assertResponseContains(new Request("http:
"\"resources\":{\"vcpu\":56.0,\"memoryGb\":34.0,\"diskGb\":12.0,\"bandwidthGbps\":78.0,\"diskSpeed\":\"fast\",\"storageType\":\"remote\"}");
}
private static String asDockerNodeJson(String hostname, String parentHostname, String... ipAddress) {
return asDockerNodeJson(hostname, NodeType.tenant, parentHostname, ipAddress);
}
private static String asDockerNodeJson(String hostname, NodeType nodeType, String parentHostname, String... ipAddress) {
return "{\"hostname\":\"" + hostname + "\", \"parentHostname\":\"" + parentHostname + "\"," +
createIpAddresses(ipAddress) +
"\"openStackId\":\"" + hostname + "\",\"flavor\":\"d-1-1-100\"" +
(nodeType != NodeType.tenant ? ",\"type\":\"" + nodeType + "\"" : "") +
"}";
}
private static String asNodeJson(String hostname, String flavor, String... ipAddress) {
return "{\"hostname\":\"" + hostname + "\", \"openStackId\":\"" + hostname + "\"," +
createIpAddresses(ipAddress) +
"\"flavor\":\"" + flavor + "\"}";
}
private static String asHostJson(String hostname, String flavor, Optional<TenantName> reservedTo, String... ipAddress) {
return asNodeJson(hostname, NodeType.host, flavor, reservedTo, ipAddress);
}
private static String asNodeJson(String hostname, NodeType nodeType, String flavor, Optional<TenantName> reservedTo, String... ipAddress) {
return "{\"hostname\":\"" + hostname + "\", \"openStackId\":\"" + hostname + "\"," +
createIpAddresses(ipAddress) +
"\"flavor\":\"" + flavor + "\"" +
(reservedTo.isPresent() ? ", \"reservedTo\":\"" + reservedTo.get().value() + "\"" : "") +
", \"type\":\"" + nodeType + "\"}";
}
private static String createIpAddresses(String... ipAddress) {
return "\"ipAddresses\":[" +
Arrays.stream(ipAddress)
.map(ip -> "\"" + ip + "\"")
.collect(Collectors.joining(",")) +
"],";
}
private void assertRestart(int restartCount, Request request) throws IOException {
tester.assertResponse(request, 200, "{\"message\":\"Scheduled restart of " + restartCount + " matching nodes\"}");
}
private void assertReboot(int rebootCount, Request request) throws IOException {
tester.assertResponse(request, 200, "{\"message\":\"Scheduled reboot of " + rebootCount + " matching nodes\"}");
}
private void assertFile(Request request, String file) throws IOException {
tester.assertFile(request, file);
}
private void assertResponse(Request request, String file) throws IOException {
tester.assertResponse(request, file);
}
} |
Yes! | public void deleteTenant(TenantName tenant, Credentials credentials) {
for (TenantRole role : Roles.tenantRoles(tenant))
userManagement.deleteRole(role);
} | public void deleteTenant(TenantName tenant, Credentials credentials) {
for (TenantRole role : Roles.tenantRoles(tenant))
userManagement.deleteRole(role);
} | class CloudAccessControl implements AccessControl {
private static final BillingInfo defaultBillingInfo = new BillingInfo("customer", "Vespa");
private final UserManagement userManagement;
private final BooleanFlag enablePublicSignup;
@Inject
public CloudAccessControl(UserManagement userManagement, FlagSource flagSource) {
this.userManagement = userManagement;
this.enablePublicSignup = Flags.ENABLE_PUBLIC_SIGNUP_FLOW.bindTo(flagSource);
}
@Override
public CloudTenant createTenant(TenantSpec tenantSpec, Credentials credentials, List<Tenant> existing) {
requireTenantCreationAllowed((Auth0Credentials) credentials);
CloudTenantSpec spec = (CloudTenantSpec) tenantSpec;
CloudTenant tenant = CloudTenant.create(spec.tenant(), defaultBillingInfo);
for (Role role : Roles.tenantRoles(spec.tenant())) {
userManagement.createRole(role);
}
var userId = List.of(new UserId(credentials.user().getName()));
userManagement.addUsers(Role.administrator(spec.tenant()), userId);
userManagement.addUsers(Role.developer(spec.tenant()), userId);
userManagement.addUsers(Role.reader(spec.tenant()), userId);
return tenant;
}
private void requireTenantCreationAllowed(Auth0Credentials auth0Credentials) {
if (allowedByPrivilegedRole(auth0Credentials)) return;
if (!allowedByFeatureFlag(auth0Credentials)) {
throw new ForbiddenException("You are not currently permitted to create tenants. Please contact the Vespa team to request access.");
}
if(administeredTenants(auth0Credentials) >= 3) {
throw new ForbiddenException("You are already administering 3 tenants. If you need more, please contact the Vespa team.");
}
}
private boolean allowedByPrivilegedRole(Auth0Credentials auth0Credentials) {
return auth0Credentials.getRoles().stream()
.map(Role::definition)
.anyMatch(rd -> rd == hostedOperator || rd == hostedSupporter);
}
private boolean allowedByFeatureFlag(Auth0Credentials auth0Credentials) {
return enablePublicSignup.with(FetchVector.Dimension.CONSOLE_USER_EMAIL, auth0Credentials.user().getName()).value();
}
private long administeredTenants(Auth0Credentials auth0Credentials) {
return auth0Credentials.getRoles().stream()
.map(Role::definition)
.filter(rd -> rd == administrator)
.count();
}
@Override
public Tenant updateTenant(TenantSpec tenantSpec, Credentials credentials, List<Tenant> existing, List<Application> applications) {
throw new UnsupportedOperationException("Update is not supported here, as it would entail changing the tenant name.");
}
@Override
@Override
public void createApplication(TenantAndApplicationId id, Credentials credentials) {
for (Role role : Roles.applicationRoles(id.tenant(), id.application()))
userManagement.createRole(role);
}
@Override
public void deleteApplication(TenantAndApplicationId id, Credentials credentials) {
for (ApplicationRole role : Roles.applicationRoles(id.tenant(), id.application()))
userManagement.deleteRole(role);
}
} | class CloudAccessControl implements AccessControl {
private static final BillingInfo defaultBillingInfo = new BillingInfo("customer", "Vespa");
private final UserManagement userManagement;
private final BooleanFlag enablePublicSignup;
@Inject
public CloudAccessControl(UserManagement userManagement, FlagSource flagSource) {
this.userManagement = userManagement;
this.enablePublicSignup = Flags.ENABLE_PUBLIC_SIGNUP_FLOW.bindTo(flagSource);
}
@Override
public CloudTenant createTenant(TenantSpec tenantSpec, Credentials credentials, List<Tenant> existing) {
requireTenantCreationAllowed((Auth0Credentials) credentials);
CloudTenantSpec spec = (CloudTenantSpec) tenantSpec;
CloudTenant tenant = CloudTenant.create(spec.tenant(), defaultBillingInfo);
for (Role role : Roles.tenantRoles(spec.tenant())) {
userManagement.createRole(role);
}
var userId = List.of(new UserId(credentials.user().getName()));
userManagement.addUsers(Role.administrator(spec.tenant()), userId);
userManagement.addUsers(Role.developer(spec.tenant()), userId);
userManagement.addUsers(Role.reader(spec.tenant()), userId);
return tenant;
}
private void requireTenantCreationAllowed(Auth0Credentials auth0Credentials) {
if (allowedByPrivilegedRole(auth0Credentials)) return;
if (!allowedByFeatureFlag(auth0Credentials)) {
throw new ForbiddenException("You are not currently permitted to create tenants. Please contact the Vespa team to request access.");
}
if(administeredTenants(auth0Credentials) >= 3) {
throw new ForbiddenException("You are already administering 3 tenants. If you need more, please contact the Vespa team.");
}
}
private boolean allowedByPrivilegedRole(Auth0Credentials auth0Credentials) {
return auth0Credentials.getRoles().stream()
.map(Role::definition)
.anyMatch(rd -> rd == hostedOperator || rd == hostedSupporter);
}
private boolean allowedByFeatureFlag(Auth0Credentials auth0Credentials) {
return enablePublicSignup.with(FetchVector.Dimension.CONSOLE_USER_EMAIL, auth0Credentials.user().getName()).value();
}
private long administeredTenants(Auth0Credentials auth0Credentials) {
return auth0Credentials.getRoles().stream()
.map(Role::definition)
.filter(rd -> rd == administrator)
.count();
}
@Override
public Tenant updateTenant(TenantSpec tenantSpec, Credentials credentials, List<Tenant> existing, List<Application> applications) {
throw new UnsupportedOperationException("Update is not supported here, as it would entail changing the tenant name.");
}
@Override
@Override
public void createApplication(TenantAndApplicationId id, Credentials credentials) {
for (Role role : Roles.applicationRoles(id.tenant(), id.application()))
userManagement.createRole(role);
}
@Override
public void deleteApplication(TenantAndApplicationId id, Credentials credentials) {
for (ApplicationRole role : Roles.applicationRoles(id.tenant(), id.application()))
userManagement.deleteRole(role);
}
} | |
Perhaps we should consider to stop using 'generation' if it really is the sessionId. | public void redeploy() {
PrepareResult result = deployApp(testApp);
long firstSessionId = result.sessionId();
PrepareResult result2 = deployApp(testApp);
long secondSessionId = result2.sessionId();
assertNotEquals(firstSessionId, secondSessionId);
TenantName tenantName = applicationId().tenant();
Tenant tenant = tenantRepository.getTenant(tenantName);
LocalSession session = tenant.getLocalSessionRepo().getSession(
tenant.getApplicationRepo().requireActiveSessionOf(applicationId()));
assertEquals(firstSessionId, session.getMetaData().getPreviousActiveGeneration());
} | assertEquals(firstSessionId, session.getMetaData().getPreviousActiveGeneration()); | public void redeploy() {
PrepareResult result = deployApp(testApp);
long firstSessionId = result.sessionId();
PrepareResult result2 = deployApp(testApp);
long secondSessionId = result2.sessionId();
assertNotEquals(firstSessionId, secondSessionId);
TenantName tenantName = applicationId().tenant();
Tenant tenant = tenantRepository.getTenant(tenantName);
LocalSession session = tenant.getLocalSessionRepo().getSession(
tenant.getApplicationRepo().requireActiveSessionOf(applicationId()));
assertEquals(firstSessionId, session.getMetaData().getPreviousActiveGeneration());
} | class ApplicationRepositoryTest {
private final static File testApp = new File("src/test/apps/app");
private final static File testAppJdiscOnly = new File("src/test/apps/app-jdisc-only");
private final static File testAppJdiscOnlyRestart = new File("src/test/apps/app-jdisc-only-restart");
private final static File testAppLogServerWithContainer = new File("src/test/apps/app-logserver-with-container");
private final static TenantName tenant1 = TenantName.from("test1");
private final static TenantName tenant2 = TenantName.from("test2");
private final static TenantName tenant3 = TenantName.from("test3");
private final static Clock clock = Clock.systemUTC();
private ApplicationRepository applicationRepository;
private TenantRepository tenantRepository;
private SessionHandlerTest.MockProvisioner provisioner;
private OrchestratorMock orchestrator;
private TimeoutBudget timeoutBudget;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Before
public void setup() {
Curator curator = new MockCurator();
tenantRepository = new TenantRepository(new TestComponentRegistry.Builder()
.curator(curator)
.build());
tenantRepository.addTenant(TenantRepository.HOSTED_VESPA_TENANT);
tenantRepository.addTenant(tenant1);
tenantRepository.addTenant(tenant2);
tenantRepository.addTenant(tenant3);
orchestrator = new OrchestratorMock();
provisioner = new SessionHandlerTest.MockProvisioner();
applicationRepository = new ApplicationRepository(tenantRepository,
provisioner,
orchestrator,
clock);
timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(60));
}
@Test
public void prepareAndActivate() {
PrepareResult result = prepareAndActivate(testApp);
assertTrue(result.configChangeActions().getRefeedActions().isEmpty());
assertTrue(result.configChangeActions().getRestartActions().isEmpty());
TenantName tenantName = applicationId().tenant();
Tenant tenant = tenantRepository.getTenant(tenantName);
LocalSession session = tenant.getLocalSessionRepo().getSession(tenant.getApplicationRepo()
.requireActiveSessionOf(applicationId()));
session.getAllocatedHosts();
}
@Test
public void prepareAndActivateWithRestart() {
prepareAndActivate(testAppJdiscOnly);
PrepareResult result = prepareAndActivate(testAppJdiscOnlyRestart);
assertTrue(result.configChangeActions().getRefeedActions().isEmpty());
assertFalse(result.configChangeActions().getRestartActions().isEmpty());
}
@Test
public void createAndPrepareAndActivate() {
PrepareResult result = deployApp(testApp);
assertTrue(result.configChangeActions().getRefeedActions().isEmpty());
assertTrue(result.configChangeActions().getRestartActions().isEmpty());
}
@Test
@Test
public void createFromActiveSession() {
PrepareResult result = deployApp(testApp);
long sessionId = applicationRepository.createSessionFromExisting(applicationId(),
new SilentDeployLogger(),
false,
timeoutBudget);
long originalSessionId = result.sessionId();
ApplicationMetaData originalApplicationMetaData = getApplicationMetaData(applicationId(), originalSessionId);
ApplicationMetaData applicationMetaData = getApplicationMetaData(applicationId(), sessionId);
assertNotEquals(sessionId, originalSessionId);
assertEquals(originalApplicationMetaData.getApplicationId(), applicationMetaData.getApplicationId());
assertEquals(originalApplicationMetaData.getGeneration().longValue(), applicationMetaData.getPreviousActiveGeneration());
assertNotEquals(originalApplicationMetaData.getGeneration(), applicationMetaData.getGeneration());
assertEquals(originalApplicationMetaData.getDeployedByUser(), applicationMetaData.getDeployedByUser());
}
@Test
public void testSuspension() {
deployApp(testApp);
assertFalse(applicationRepository.isSuspended(applicationId()));
orchestrator.suspend(applicationId());
assertTrue(applicationRepository.isSuspended(applicationId()));
}
@Test
public void getLogs() {
applicationRepository = createApplicationRepository();
deployApp(testAppLogServerWithContainer);
HttpResponse response = applicationRepository.getLogs(applicationId(), Optional.empty(), "");
assertEquals(200, response.getStatus());
}
@Test
public void getLogsForHostname() {
applicationRepository = createApplicationRepository();
ApplicationId applicationId = ApplicationId.from("hosted-vespa", "tenant-host", "default");
deployApp(testAppLogServerWithContainer, new PrepareParams.Builder().applicationId(applicationId).build());
HttpResponse response = applicationRepository.getLogs(applicationId, Optional.of("localhost"), "");
assertEquals(200, response.getStatus());
}
@Test(expected = IllegalArgumentException.class)
public void refuseToGetLogsFromHostnameNotInApplication() {
applicationRepository = createApplicationRepository();
deployApp(testAppLogServerWithContainer);
HttpResponse response = applicationRepository.getLogs(applicationId(), Optional.of("host123.fake.yahoo.com"), "");
assertEquals(200, response.getStatus());
}
@Test
public void deleteUnusedTenants() {
Instant now = ManualClock.at("1970-01-01T01:00:00");
deployApp(testApp);
deployApp(testApp, new PrepareParams.Builder().applicationId(applicationId(tenant2)).build());
Duration ttlForUnusedTenant = Duration.ofHours(1);
assertTrue(applicationRepository.deleteUnusedTenants(ttlForUnusedTenant, now).isEmpty());
ttlForUnusedTenant = Duration.ofMillis(1);
assertEquals(tenant3, applicationRepository.deleteUnusedTenants(ttlForUnusedTenant, now).iterator().next());
applicationRepository.delete(applicationId());
Set<TenantName> tenantsDeleted = applicationRepository.deleteUnusedTenants(Duration.ofMillis(1), now);
assertTrue(tenantsDeleted.contains(tenant1));
assertFalse(tenantsDeleted.contains(tenant2));
}
@Test
public void deleteUnusedFileReferences() throws IOException {
File fileReferencesDir = temporaryFolder.newFolder();
File filereferenceDir = createFilereferenceOnDisk(new File(fileReferencesDir, "foo"), Instant.now().minus(Duration.ofDays(15)));
File filereferenceDir2 = createFilereferenceOnDisk(new File(fileReferencesDir, "baz"), Instant.now());
tenantRepository.addTenant(tenant1);
Provisioner provisioner = new SessionHandlerTest.MockProvisioner();
applicationRepository = new ApplicationRepository(tenantRepository, provisioner, orchestrator, clock);
timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(60));
PrepareParams prepareParams = new PrepareParams.Builder().applicationId(applicationId()).ignoreValidationErrors(true).build();
deployApp(new File("src/test/apps/app"), prepareParams);
Set<String> toBeDeleted = applicationRepository.deleteUnusedFiledistributionReferences(fileReferencesDir, Duration.ofHours(48));
assertEquals(Collections.singleton("foo"), toBeDeleted);
assertFalse(filereferenceDir.exists());
assertTrue(filereferenceDir2.exists());
}
private File createFilereferenceOnDisk(File filereferenceDir, Instant lastModifiedTime) {
assertTrue(filereferenceDir.mkdir());
File bar = new File(filereferenceDir, "file");
IOUtils.writeFile(bar, Utf8.toBytes("test"));
assertTrue(filereferenceDir.setLastModified(lastModifiedTime.toEpochMilli()));
return filereferenceDir;
}
@Test
public void delete() {
{
PrepareResult result = deployApp(testApp);
long sessionId = result.sessionId();
Tenant tenant = tenantRepository.getTenant(applicationId().tenant());
LocalSession applicationData = tenant.getLocalSessionRepo().getSession(sessionId);
assertNotNull(applicationData);
assertNotNull(applicationData.getApplicationId());
assertNotNull(tenant.getRemoteSessionRepo().getSession(sessionId));
assertNotNull(applicationRepository.getActiveSession(applicationId()));
assertTrue(applicationRepository.delete(applicationId()));
assertNull(applicationRepository.getActiveSession(applicationId()));
assertNull(tenant.getLocalSessionRepo().getSession(sessionId));
assertNull(tenant.getRemoteSessionRepo().getSession(sessionId));
assertTrue(provisioner.removed);
assertEquals(tenant.getName(), provisioner.lastApplicationId.tenant());
assertEquals(applicationId(), provisioner.lastApplicationId);
assertFalse(applicationRepository.delete(applicationId()));
}
{
deployApp(testApp);
assertTrue(applicationRepository.delete(applicationId()));
deployApp(testApp);
ApplicationId fooId = applicationId(tenant2);
PrepareParams prepareParams2 = new PrepareParams.Builder().applicationId(fooId).build();
deployApp(testApp, prepareParams2);
assertNotNull(applicationRepository.getActiveSession(fooId));
assertTrue(applicationRepository.delete(fooId));
assertEquals(fooId, provisioner.lastApplicationId);
assertNotNull(applicationRepository.getActiveSession(applicationId()));
assertTrue(applicationRepository.delete(applicationId()));
}
{
PrepareResult prepareResult = deployApp(testApp);
try {
applicationRepository.delete(applicationId(), Duration.ZERO);
fail("Should have gotten an exception");
} catch (InternalServerException e) {
assertEquals("test1.testapp was not deleted (waited PT0S), session " + prepareResult.sessionId(), e.getMessage());
}
RemoteSession activeSession = applicationRepository.getActiveSession(applicationId());
assertNull(activeSession);
Tenant tenant = tenantRepository.getTenant(applicationId().tenant());
assertNull(tenant.getRemoteSessionRepo().getSession(prepareResult.sessionId()));
assertTrue(applicationRepository.delete(applicationId()));
}
}
@Test
public void testDeletingInactiveSessions() throws IOException {
ManualClock clock = new ManualClock(Instant.now());
ConfigserverConfig configserverConfig =
new ConfigserverConfig(new ConfigserverConfig.Builder()
.configServerDBDir(temporaryFolder.newFolder("serverdb").getAbsolutePath())
.configDefinitionsDir(temporaryFolder.newFolder("configdefinitions").getAbsolutePath())
.sessionLifetime(60));
DeployTester tester = new DeployTester(configserverConfig, clock);
tester.deployApp("src/test/apps/app", clock.instant());
clock.advance(Duration.ofSeconds(10));
Optional<Deployment> deployment2 = tester.redeployFromLocalActive();
assertTrue(deployment2.isPresent());
deployment2.get().activate();
long activeSessionId = tester.tenant().getApplicationRepo().requireActiveSessionOf(tester.applicationId());
clock.advance(Duration.ofSeconds(10));
Optional<com.yahoo.config.provision.Deployment> deployment3 = tester.redeployFromLocalActive();
assertTrue(deployment3.isPresent());
deployment3.get().prepare();
LocalSession deployment3session = ((com.yahoo.vespa.config.server.deploy.Deployment) deployment3.get()).session();
assertNotEquals(activeSessionId, deployment3session);
assertEquals(activeSessionId, tester.tenant().getApplicationRepo().requireActiveSessionOf(tester.applicationId()));
LocalSessionRepo localSessionRepo = tester.tenant().getLocalSessionRepo();
assertEquals(3, localSessionRepo.getSessions().size());
clock.advance(Duration.ofHours(1));
tester.applicationRepository().deleteExpiredLocalSessions();
Collection<LocalSession> sessions = localSessionRepo.getSessions();
assertEquals(1, sessions.size());
ArrayList<LocalSession> localSessions = new ArrayList<>(sessions);
LocalSession localSession = localSessions.get(0);
assertEquals(3, localSession.getSessionId());
assertEquals(0, tester.applicationRepository().deleteExpiredRemoteSessions(clock, Duration.ofSeconds(0)));
Optional<com.yahoo.config.provision.Deployment> deployment4 = tester.redeployFromLocalActive();
assertTrue(deployment4.isPresent());
deployment4.get().prepare();
assertEquals(2, localSessionRepo.getSessions().size());
localSessionRepo.deleteSession(localSession);
assertEquals(1, localSessionRepo.getSessions().size());
tester.applicationRepository().deleteExpiredLocalSessions();
}
@Test
public void testMetrics() {
MockMetric actual = new MockMetric();
applicationRepository = new ApplicationRepository(tenantRepository,
provisioner,
orchestrator,
new ConfigserverConfig(new ConfigserverConfig.Builder()),
new MockLogRetriever(),
new ManualClock(),
new MockTesterClient(),
actual);
deployApp(testAppLogServerWithContainer);
Map<String, ?> context = Map.of("applicationId", "test1.testapp.default",
"tenantName", "test1",
"app", "testapp.default",
"zone", "prod.default");
MockMetric expected = new MockMetric();
expected.set("deployment.prepareMillis", 0L, expected.createContext(context));
expected.set("deployment.activateMillis", 0L, expected.createContext(context));
assertEquals(expected.values, actual.values);
}
@Test
public void deletesApplicationRoles() {
var tenant = tenantRepository.getTenant(tenant1);
var applicationId = applicationId(tenant1);
var prepareParams = new PrepareParams.Builder().applicationId(applicationId)
.applicationRoles(ApplicationRoles.fromString("hostRole","containerRole")).build();
deployApp(testApp, prepareParams);
var approlesStore = new ApplicationRolesStore(tenant.getCurator(), tenant.getPath());
var appRoles = approlesStore.readApplicationRoles(applicationId);
assertTrue(appRoles.isPresent());
assertEquals("hostRole", appRoles.get().applicationHostRole());
assertEquals("containerRole", appRoles.get().applicationContainerRole());
assertTrue(applicationRepository.delete(applicationId));
assertTrue(approlesStore.readApplicationRoles(applicationId).isEmpty());
}
@Test
public void require_that_provision_info_can_be_read() {
prepareAndActivate(testAppJdiscOnly);
TenantName tenantName = applicationId().tenant();
Tenant tenant = tenantRepository.getTenant(tenantName);
LocalSession session = tenant.getLocalSessionRepo().getSession(tenant.getApplicationRepo().requireActiveSessionOf(applicationId()));
List<NetworkPorts.Allocation> list = new ArrayList<>();
list.add(new NetworkPorts.Allocation(8080, "container", "container/container.0", "http"));
list.add(new NetworkPorts.Allocation(19070, "configserver", "admin/configservers/configserver.0", "rpc"));
list.add(new NetworkPorts.Allocation(19071, "configserver", "admin/configservers/configserver.0", "http"));
list.add(new NetworkPorts.Allocation(19080, "logserver", "admin/logserver", "rpc"));
list.add(new NetworkPorts.Allocation(19081, "logserver", "admin/logserver", "unused/1"));
list.add(new NetworkPorts.Allocation(19082, "logserver", "admin/logserver", "unused/2"));
list.add(new NetworkPorts.Allocation(19083, "logserver", "admin/logserver", "unused/3"));
list.add(new NetworkPorts.Allocation(19089, "logd", "hosts/mytesthost/logd", "http"));
list.add(new NetworkPorts.Allocation(19090, "configproxy", "hosts/mytesthost/configproxy", "rpc"));
list.add(new NetworkPorts.Allocation(19092, "metricsproxy-container", "admin/metrics/mytesthost", "http"));
list.add(new NetworkPorts.Allocation(19093, "metricsproxy-container", "admin/metrics/mytesthost", "http/1"));
list.add(new NetworkPorts.Allocation(19094, "metricsproxy-container", "admin/metrics/mytesthost", "rpc/admin"));
list.add(new NetworkPorts.Allocation(19095, "metricsproxy-container", "admin/metrics/mytesthost", "rpc/metrics"));
list.add(new NetworkPorts.Allocation(19097, "config-sentinel", "hosts/mytesthost/sentinel", "rpc"));
list.add(new NetworkPorts.Allocation(19098, "config-sentinel", "hosts/mytesthost/sentinel", "http"));
list.add(new NetworkPorts.Allocation(19099, "slobrok", "admin/slobrok.0", "rpc"));
list.add(new NetworkPorts.Allocation(19100, "container", "container/container.0", "http/1"));
list.add(new NetworkPorts.Allocation(19101, "container", "container/container.0", "messaging"));
list.add(new NetworkPorts.Allocation(19102, "container", "container/container.0", "rpc/admin"));
list.add(new NetworkPorts.Allocation(19103, "slobrok", "admin/slobrok.0", "http"));
AllocatedHosts info = session.getAllocatedHosts();
assertNotNull(info);
assertThat(info.getHosts().size(), is(1));
assertTrue(info.getHosts().contains(new HostSpec("mytesthost",
Collections.emptyList(),
Optional.empty())));
Optional<NetworkPorts> portsCopy = info.getHosts().iterator().next().networkPorts();
assertTrue(portsCopy.isPresent());
assertThat(portsCopy.get().allocations(), is(list));
}
@Test
public void testActivationOfUnpreparedSession() {
PrepareResult result = deployApp(testApp);
long firstSession = result.sessionId();
TimeoutBudget timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(10));
long sessionId = applicationRepository.createSession(applicationId(), timeoutBudget, testAppJdiscOnly);
exceptionRule.expect(IllegalStateException.class);
exceptionRule.expectMessage(containsString("tenant:test1 Session 3 is not prepared"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId, timeoutBudget, false);
RemoteSession activeSession = applicationRepository.getActiveSession(applicationId());
assertEquals(firstSession, activeSession.getSessionId());
assertEquals(Session.Status.ACTIVATE, activeSession.getStatus());
}
@Test
public void testActivationTimesOut() {
PrepareResult result = deployApp(testAppJdiscOnly);
long firstSession = result.sessionId();
long sessionId = applicationRepository.createSession(applicationId(), timeoutBudget, testAppJdiscOnly);
applicationRepository.prepare(tenantRepository.getTenant(tenant1), sessionId, prepareParams(), clock.instant());
exceptionRule.expect(RuntimeException.class);
exceptionRule.expectMessage(containsString("Timeout exceeded when trying to activate 'test1.testapp'"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId, new TimeoutBudget(clock, Duration.ofSeconds(0)), false);
RemoteSession activeSession = applicationRepository.getActiveSession(applicationId());
assertEquals(firstSession, activeSession.getSessionId());
assertEquals(Session.Status.ACTIVATE, activeSession.getStatus());
}
@Test
public void testActivationOfSessionCreatedFromNoLongerActiveSessionFails() {
TimeoutBudget timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(10));
PrepareResult result1 = deployApp(testAppJdiscOnly);
result1.sessionId();
long sessionId2 = applicationRepository.createSessionFromExisting(applicationId(),
new BaseDeployLogger(),
false,
timeoutBudget);
PrepareResult result2 = deployApp(testAppJdiscOnly);
result2.sessionId();
applicationRepository.prepare(tenantRepository.getTenant(tenant1), sessionId2, prepareParams(), clock.instant());
exceptionRule.expect(ActivationConflictException.class);
exceptionRule.expectMessage(containsString("tenant:test1 app:testapp:default Cannot activate session 3 because the currently active session (4) has changed since session 3 was created (was 2 at creation time)"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId2, timeoutBudget, false);
}
@Test
public void testPrepareAndActivateAlreadyActivatedSession() {
PrepareResult result = deployApp(testAppJdiscOnly);
long sessionId = result.sessionId();
exceptionRule.expect(IllegalStateException.class);
exceptionRule.expectMessage(containsString("Session is active: 2"));
applicationRepository.prepare(tenantRepository.getTenant(tenant1), sessionId, prepareParams(), clock.instant());
exceptionRule.expect(IllegalStateException.class);
exceptionRule.expectMessage(containsString("tenant:test1 app:testapp:default Session 2 is already active"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId, timeoutBudget, false);
}
@Test
public void testThatPreviousSessionIsDeactivated() {
deployApp(testAppJdiscOnly);
Session firstSession = applicationRepository.getActiveSession(applicationId());
deployApp(testAppJdiscOnly);
assertEquals(Session.Status.DEACTIVATE, firstSession.getStatus());
}
private ApplicationRepository createApplicationRepository() {
return new ApplicationRepository(tenantRepository,
provisioner,
orchestrator,
new ConfigserverConfig(new ConfigserverConfig.Builder()),
new MockLogRetriever(),
clock,
new MockTesterClient(),
new NullMetric());
}
private PrepareResult prepareAndActivate(File application) {
return applicationRepository.deploy(application, prepareParams(), false, Instant.now());
}
private PrepareResult deployApp(File applicationPackage) {
return deployApp(applicationPackage, prepareParams());
}
private PrepareResult deployApp(File applicationPackage, PrepareParams prepareParams) {
return applicationRepository.deploy(applicationPackage, prepareParams);
}
private PrepareParams prepareParams() {
return new PrepareParams.Builder().applicationId(applicationId()).build();
}
private ApplicationId applicationId() {
return ApplicationId.from(tenant1, ApplicationName.from("testapp"), InstanceName.defaultName());
}
private ApplicationId applicationId(TenantName tenantName) {
return ApplicationId.from(tenantName, ApplicationName.from("testapp"), InstanceName.defaultName());
}
private ApplicationMetaData getApplicationMetaData(ApplicationId applicationId, long sessionId) {
Tenant tenant = tenantRepository.getTenant(applicationId.tenant());
return applicationRepository.getMetadataFromLocalSession(tenant, sessionId);
}
/** Stores all added or set values for each metric and context. */
static class MockMetric implements Metric {
final Map<String, Map<Map<String, ?>, Number>> values = new HashMap<>();
@Override
public void set(String key, Number val, Metric.Context ctx) {
values.putIfAbsent(key, new HashMap<>());
values.get(key).put(((Context) ctx).point, val);
}
@Override
public void add(String key, Number val, Metric.Context ctx) {
throw new UnsupportedOperationException();
}
@Override
public Context createContext(Map<String, ?> properties) {
return new Context(properties);
}
private static class Context implements Metric.Context {
private final Map<String, ?> point;
public Context(Map<String, ?> point) {
this.point = Map.copyOf(point);
}
}
}
} | class ApplicationRepositoryTest {
private final static File testApp = new File("src/test/apps/app");
private final static File testAppJdiscOnly = new File("src/test/apps/app-jdisc-only");
private final static File testAppJdiscOnlyRestart = new File("src/test/apps/app-jdisc-only-restart");
private final static File testAppLogServerWithContainer = new File("src/test/apps/app-logserver-with-container");
private final static TenantName tenant1 = TenantName.from("test1");
private final static TenantName tenant2 = TenantName.from("test2");
private final static TenantName tenant3 = TenantName.from("test3");
private final static Clock clock = Clock.systemUTC();
private ApplicationRepository applicationRepository;
private TenantRepository tenantRepository;
private SessionHandlerTest.MockProvisioner provisioner;
private OrchestratorMock orchestrator;
private TimeoutBudget timeoutBudget;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Before
public void setup() {
Curator curator = new MockCurator();
tenantRepository = new TenantRepository(new TestComponentRegistry.Builder()
.curator(curator)
.build());
tenantRepository.addTenant(TenantRepository.HOSTED_VESPA_TENANT);
tenantRepository.addTenant(tenant1);
tenantRepository.addTenant(tenant2);
tenantRepository.addTenant(tenant3);
orchestrator = new OrchestratorMock();
provisioner = new SessionHandlerTest.MockProvisioner();
applicationRepository = new ApplicationRepository(tenantRepository,
provisioner,
orchestrator,
clock);
timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(60));
}
@Test
public void prepareAndActivate() {
PrepareResult result = prepareAndActivate(testApp);
assertTrue(result.configChangeActions().getRefeedActions().isEmpty());
assertTrue(result.configChangeActions().getRestartActions().isEmpty());
TenantName tenantName = applicationId().tenant();
Tenant tenant = tenantRepository.getTenant(tenantName);
LocalSession session = tenant.getLocalSessionRepo().getSession(tenant.getApplicationRepo()
.requireActiveSessionOf(applicationId()));
session.getAllocatedHosts();
}
@Test
public void prepareAndActivateWithRestart() {
prepareAndActivate(testAppJdiscOnly);
PrepareResult result = prepareAndActivate(testAppJdiscOnlyRestart);
assertTrue(result.configChangeActions().getRefeedActions().isEmpty());
assertFalse(result.configChangeActions().getRestartActions().isEmpty());
}
@Test
public void createAndPrepareAndActivate() {
PrepareResult result = deployApp(testApp);
assertTrue(result.configChangeActions().getRefeedActions().isEmpty());
assertTrue(result.configChangeActions().getRestartActions().isEmpty());
}
@Test
@Test
public void createFromActiveSession() {
PrepareResult result = deployApp(testApp);
long sessionId = applicationRepository.createSessionFromExisting(applicationId(),
new SilentDeployLogger(),
false,
timeoutBudget);
long originalSessionId = result.sessionId();
ApplicationMetaData originalApplicationMetaData = getApplicationMetaData(applicationId(), originalSessionId);
ApplicationMetaData applicationMetaData = getApplicationMetaData(applicationId(), sessionId);
assertNotEquals(sessionId, originalSessionId);
assertEquals(originalApplicationMetaData.getApplicationId(), applicationMetaData.getApplicationId());
assertEquals(originalApplicationMetaData.getGeneration().longValue(), applicationMetaData.getPreviousActiveGeneration());
assertNotEquals(originalApplicationMetaData.getGeneration(), applicationMetaData.getGeneration());
assertEquals(originalApplicationMetaData.getDeployedByUser(), applicationMetaData.getDeployedByUser());
}
@Test
public void testSuspension() {
deployApp(testApp);
assertFalse(applicationRepository.isSuspended(applicationId()));
orchestrator.suspend(applicationId());
assertTrue(applicationRepository.isSuspended(applicationId()));
}
@Test
public void getLogs() {
applicationRepository = createApplicationRepository();
deployApp(testAppLogServerWithContainer);
HttpResponse response = applicationRepository.getLogs(applicationId(), Optional.empty(), "");
assertEquals(200, response.getStatus());
}
@Test
public void getLogsForHostname() {
applicationRepository = createApplicationRepository();
ApplicationId applicationId = ApplicationId.from("hosted-vespa", "tenant-host", "default");
deployApp(testAppLogServerWithContainer, new PrepareParams.Builder().applicationId(applicationId).build());
HttpResponse response = applicationRepository.getLogs(applicationId, Optional.of("localhost"), "");
assertEquals(200, response.getStatus());
}
@Test(expected = IllegalArgumentException.class)
public void refuseToGetLogsFromHostnameNotInApplication() {
applicationRepository = createApplicationRepository();
deployApp(testAppLogServerWithContainer);
HttpResponse response = applicationRepository.getLogs(applicationId(), Optional.of("host123.fake.yahoo.com"), "");
assertEquals(200, response.getStatus());
}
@Test
public void deleteUnusedTenants() {
Instant now = ManualClock.at("1970-01-01T01:00:00");
deployApp(testApp);
deployApp(testApp, new PrepareParams.Builder().applicationId(applicationId(tenant2)).build());
Duration ttlForUnusedTenant = Duration.ofHours(1);
assertTrue(applicationRepository.deleteUnusedTenants(ttlForUnusedTenant, now).isEmpty());
ttlForUnusedTenant = Duration.ofMillis(1);
assertEquals(tenant3, applicationRepository.deleteUnusedTenants(ttlForUnusedTenant, now).iterator().next());
applicationRepository.delete(applicationId());
Set<TenantName> tenantsDeleted = applicationRepository.deleteUnusedTenants(Duration.ofMillis(1), now);
assertTrue(tenantsDeleted.contains(tenant1));
assertFalse(tenantsDeleted.contains(tenant2));
}
@Test
public void deleteUnusedFileReferences() throws IOException {
File fileReferencesDir = temporaryFolder.newFolder();
File filereferenceDir = createFilereferenceOnDisk(new File(fileReferencesDir, "foo"), Instant.now().minus(Duration.ofDays(15)));
File filereferenceDir2 = createFilereferenceOnDisk(new File(fileReferencesDir, "baz"), Instant.now());
tenantRepository.addTenant(tenant1);
Provisioner provisioner = new SessionHandlerTest.MockProvisioner();
applicationRepository = new ApplicationRepository(tenantRepository, provisioner, orchestrator, clock);
timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(60));
PrepareParams prepareParams = new PrepareParams.Builder().applicationId(applicationId()).ignoreValidationErrors(true).build();
deployApp(new File("src/test/apps/app"), prepareParams);
Set<String> toBeDeleted = applicationRepository.deleteUnusedFiledistributionReferences(fileReferencesDir, Duration.ofHours(48));
assertEquals(Collections.singleton("foo"), toBeDeleted);
assertFalse(filereferenceDir.exists());
assertTrue(filereferenceDir2.exists());
}
private File createFilereferenceOnDisk(File filereferenceDir, Instant lastModifiedTime) {
assertTrue(filereferenceDir.mkdir());
File bar = new File(filereferenceDir, "file");
IOUtils.writeFile(bar, Utf8.toBytes("test"));
assertTrue(filereferenceDir.setLastModified(lastModifiedTime.toEpochMilli()));
return filereferenceDir;
}
@Test
public void delete() {
{
PrepareResult result = deployApp(testApp);
long sessionId = result.sessionId();
Tenant tenant = tenantRepository.getTenant(applicationId().tenant());
LocalSession applicationData = tenant.getLocalSessionRepo().getSession(sessionId);
assertNotNull(applicationData);
assertNotNull(applicationData.getApplicationId());
assertNotNull(tenant.getRemoteSessionRepo().getSession(sessionId));
assertNotNull(applicationRepository.getActiveSession(applicationId()));
assertTrue(applicationRepository.delete(applicationId()));
assertNull(applicationRepository.getActiveSession(applicationId()));
assertNull(tenant.getLocalSessionRepo().getSession(sessionId));
assertNull(tenant.getRemoteSessionRepo().getSession(sessionId));
assertTrue(provisioner.removed);
assertEquals(tenant.getName(), provisioner.lastApplicationId.tenant());
assertEquals(applicationId(), provisioner.lastApplicationId);
assertFalse(applicationRepository.delete(applicationId()));
}
{
deployApp(testApp);
assertTrue(applicationRepository.delete(applicationId()));
deployApp(testApp);
ApplicationId fooId = applicationId(tenant2);
PrepareParams prepareParams2 = new PrepareParams.Builder().applicationId(fooId).build();
deployApp(testApp, prepareParams2);
assertNotNull(applicationRepository.getActiveSession(fooId));
assertTrue(applicationRepository.delete(fooId));
assertEquals(fooId, provisioner.lastApplicationId);
assertNotNull(applicationRepository.getActiveSession(applicationId()));
assertTrue(applicationRepository.delete(applicationId()));
}
{
PrepareResult prepareResult = deployApp(testApp);
try {
applicationRepository.delete(applicationId(), Duration.ZERO);
fail("Should have gotten an exception");
} catch (InternalServerException e) {
assertEquals("test1.testapp was not deleted (waited PT0S), session " + prepareResult.sessionId(), e.getMessage());
}
RemoteSession activeSession = applicationRepository.getActiveSession(applicationId());
assertNull(activeSession);
Tenant tenant = tenantRepository.getTenant(applicationId().tenant());
assertNull(tenant.getRemoteSessionRepo().getSession(prepareResult.sessionId()));
assertTrue(applicationRepository.delete(applicationId()));
}
}
@Test
public void testDeletingInactiveSessions() throws IOException {
ManualClock clock = new ManualClock(Instant.now());
ConfigserverConfig configserverConfig =
new ConfigserverConfig(new ConfigserverConfig.Builder()
.configServerDBDir(temporaryFolder.newFolder("serverdb").getAbsolutePath())
.configDefinitionsDir(temporaryFolder.newFolder("configdefinitions").getAbsolutePath())
.sessionLifetime(60));
DeployTester tester = new DeployTester(configserverConfig, clock);
tester.deployApp("src/test/apps/app", clock.instant());
clock.advance(Duration.ofSeconds(10));
Optional<Deployment> deployment2 = tester.redeployFromLocalActive();
assertTrue(deployment2.isPresent());
deployment2.get().activate();
long activeSessionId = tester.tenant().getApplicationRepo().requireActiveSessionOf(tester.applicationId());
clock.advance(Duration.ofSeconds(10));
Optional<com.yahoo.config.provision.Deployment> deployment3 = tester.redeployFromLocalActive();
assertTrue(deployment3.isPresent());
deployment3.get().prepare();
LocalSession deployment3session = ((com.yahoo.vespa.config.server.deploy.Deployment) deployment3.get()).session();
assertNotEquals(activeSessionId, deployment3session);
assertEquals(activeSessionId, tester.tenant().getApplicationRepo().requireActiveSessionOf(tester.applicationId()));
LocalSessionRepo localSessionRepo = tester.tenant().getLocalSessionRepo();
assertEquals(3, localSessionRepo.getSessions().size());
clock.advance(Duration.ofHours(1));
tester.applicationRepository().deleteExpiredLocalSessions();
Collection<LocalSession> sessions = localSessionRepo.getSessions();
assertEquals(1, sessions.size());
ArrayList<LocalSession> localSessions = new ArrayList<>(sessions);
LocalSession localSession = localSessions.get(0);
assertEquals(3, localSession.getSessionId());
assertEquals(0, tester.applicationRepository().deleteExpiredRemoteSessions(clock, Duration.ofSeconds(0)));
Optional<com.yahoo.config.provision.Deployment> deployment4 = tester.redeployFromLocalActive();
assertTrue(deployment4.isPresent());
deployment4.get().prepare();
assertEquals(2, localSessionRepo.getSessions().size());
localSessionRepo.deleteSession(localSession);
assertEquals(1, localSessionRepo.getSessions().size());
tester.applicationRepository().deleteExpiredLocalSessions();
}
@Test
public void testMetrics() {
MockMetric actual = new MockMetric();
applicationRepository = new ApplicationRepository(tenantRepository,
provisioner,
orchestrator,
new ConfigserverConfig(new ConfigserverConfig.Builder()),
new MockLogRetriever(),
new ManualClock(),
new MockTesterClient(),
actual);
deployApp(testAppLogServerWithContainer);
Map<String, ?> context = Map.of("applicationId", "test1.testapp.default",
"tenantName", "test1",
"app", "testapp.default",
"zone", "prod.default");
MockMetric expected = new MockMetric();
expected.set("deployment.prepareMillis", 0L, expected.createContext(context));
expected.set("deployment.activateMillis", 0L, expected.createContext(context));
assertEquals(expected.values, actual.values);
}
@Test
public void deletesApplicationRoles() {
var tenant = tenantRepository.getTenant(tenant1);
var applicationId = applicationId(tenant1);
var prepareParams = new PrepareParams.Builder().applicationId(applicationId)
.applicationRoles(ApplicationRoles.fromString("hostRole","containerRole")).build();
deployApp(testApp, prepareParams);
var approlesStore = new ApplicationRolesStore(tenant.getCurator(), tenant.getPath());
var appRoles = approlesStore.readApplicationRoles(applicationId);
assertTrue(appRoles.isPresent());
assertEquals("hostRole", appRoles.get().applicationHostRole());
assertEquals("containerRole", appRoles.get().applicationContainerRole());
assertTrue(applicationRepository.delete(applicationId));
assertTrue(approlesStore.readApplicationRoles(applicationId).isEmpty());
}
@Test
public void require_that_provision_info_can_be_read() {
prepareAndActivate(testAppJdiscOnly);
TenantName tenantName = applicationId().tenant();
Tenant tenant = tenantRepository.getTenant(tenantName);
LocalSession session = tenant.getLocalSessionRepo().getSession(tenant.getApplicationRepo().requireActiveSessionOf(applicationId()));
List<NetworkPorts.Allocation> list = new ArrayList<>();
list.add(new NetworkPorts.Allocation(8080, "container", "container/container.0", "http"));
list.add(new NetworkPorts.Allocation(19070, "configserver", "admin/configservers/configserver.0", "rpc"));
list.add(new NetworkPorts.Allocation(19071, "configserver", "admin/configservers/configserver.0", "http"));
list.add(new NetworkPorts.Allocation(19080, "logserver", "admin/logserver", "rpc"));
list.add(new NetworkPorts.Allocation(19081, "logserver", "admin/logserver", "unused/1"));
list.add(new NetworkPorts.Allocation(19082, "logserver", "admin/logserver", "unused/2"));
list.add(new NetworkPorts.Allocation(19083, "logserver", "admin/logserver", "unused/3"));
list.add(new NetworkPorts.Allocation(19089, "logd", "hosts/mytesthost/logd", "http"));
list.add(new NetworkPorts.Allocation(19090, "configproxy", "hosts/mytesthost/configproxy", "rpc"));
list.add(new NetworkPorts.Allocation(19092, "metricsproxy-container", "admin/metrics/mytesthost", "http"));
list.add(new NetworkPorts.Allocation(19093, "metricsproxy-container", "admin/metrics/mytesthost", "http/1"));
list.add(new NetworkPorts.Allocation(19094, "metricsproxy-container", "admin/metrics/mytesthost", "rpc/admin"));
list.add(new NetworkPorts.Allocation(19095, "metricsproxy-container", "admin/metrics/mytesthost", "rpc/metrics"));
list.add(new NetworkPorts.Allocation(19097, "config-sentinel", "hosts/mytesthost/sentinel", "rpc"));
list.add(new NetworkPorts.Allocation(19098, "config-sentinel", "hosts/mytesthost/sentinel", "http"));
list.add(new NetworkPorts.Allocation(19099, "slobrok", "admin/slobrok.0", "rpc"));
list.add(new NetworkPorts.Allocation(19100, "container", "container/container.0", "http/1"));
list.add(new NetworkPorts.Allocation(19101, "container", "container/container.0", "messaging"));
list.add(new NetworkPorts.Allocation(19102, "container", "container/container.0", "rpc/admin"));
list.add(new NetworkPorts.Allocation(19103, "slobrok", "admin/slobrok.0", "http"));
AllocatedHosts info = session.getAllocatedHosts();
assertNotNull(info);
assertThat(info.getHosts().size(), is(1));
assertTrue(info.getHosts().contains(new HostSpec("mytesthost",
Collections.emptyList(),
Optional.empty())));
Optional<NetworkPorts> portsCopy = info.getHosts().iterator().next().networkPorts();
assertTrue(portsCopy.isPresent());
assertThat(portsCopy.get().allocations(), is(list));
}
@Test
public void testActivationOfUnpreparedSession() {
PrepareResult result = deployApp(testApp);
long firstSession = result.sessionId();
TimeoutBudget timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(10));
long sessionId = applicationRepository.createSession(applicationId(), timeoutBudget, testAppJdiscOnly);
exceptionRule.expect(IllegalStateException.class);
exceptionRule.expectMessage(containsString("tenant:test1 Session 3 is not prepared"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId, timeoutBudget, false);
RemoteSession activeSession = applicationRepository.getActiveSession(applicationId());
assertEquals(firstSession, activeSession.getSessionId());
assertEquals(Session.Status.ACTIVATE, activeSession.getStatus());
}
@Test
public void testActivationTimesOut() {
PrepareResult result = deployApp(testAppJdiscOnly);
long firstSession = result.sessionId();
long sessionId = applicationRepository.createSession(applicationId(), timeoutBudget, testAppJdiscOnly);
applicationRepository.prepare(tenantRepository.getTenant(tenant1), sessionId, prepareParams(), clock.instant());
exceptionRule.expect(RuntimeException.class);
exceptionRule.expectMessage(containsString("Timeout exceeded when trying to activate 'test1.testapp'"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId, new TimeoutBudget(clock, Duration.ofSeconds(0)), false);
RemoteSession activeSession = applicationRepository.getActiveSession(applicationId());
assertEquals(firstSession, activeSession.getSessionId());
assertEquals(Session.Status.ACTIVATE, activeSession.getStatus());
}
@Test
public void testActivationOfSessionCreatedFromNoLongerActiveSessionFails() {
TimeoutBudget timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(10));
PrepareResult result1 = deployApp(testAppJdiscOnly);
result1.sessionId();
long sessionId2 = applicationRepository.createSessionFromExisting(applicationId(),
new BaseDeployLogger(),
false,
timeoutBudget);
PrepareResult result2 = deployApp(testAppJdiscOnly);
result2.sessionId();
applicationRepository.prepare(tenantRepository.getTenant(tenant1), sessionId2, prepareParams(), clock.instant());
exceptionRule.expect(ActivationConflictException.class);
exceptionRule.expectMessage(containsString("tenant:test1 app:testapp:default Cannot activate session 3 because the currently active session (4) has changed since session 3 was created (was 2 at creation time)"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId2, timeoutBudget, false);
}
@Test
public void testPrepareAndActivateAlreadyActivatedSession() {
PrepareResult result = deployApp(testAppJdiscOnly);
long sessionId = result.sessionId();
exceptionRule.expect(IllegalStateException.class);
exceptionRule.expectMessage(containsString("Session is active: 2"));
applicationRepository.prepare(tenantRepository.getTenant(tenant1), sessionId, prepareParams(), clock.instant());
exceptionRule.expect(IllegalStateException.class);
exceptionRule.expectMessage(containsString("tenant:test1 app:testapp:default Session 2 is already active"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId, timeoutBudget, false);
}
@Test
public void testThatPreviousSessionIsDeactivated() {
deployApp(testAppJdiscOnly);
Session firstSession = applicationRepository.getActiveSession(applicationId());
deployApp(testAppJdiscOnly);
assertEquals(Session.Status.DEACTIVATE, firstSession.getStatus());
}
private ApplicationRepository createApplicationRepository() {
return new ApplicationRepository(tenantRepository,
provisioner,
orchestrator,
new ConfigserverConfig(new ConfigserverConfig.Builder()),
new MockLogRetriever(),
clock,
new MockTesterClient(),
new NullMetric());
}
private PrepareResult prepareAndActivate(File application) {
return applicationRepository.deploy(application, prepareParams(), false, Instant.now());
}
private PrepareResult deployApp(File applicationPackage) {
return deployApp(applicationPackage, prepareParams());
}
private PrepareResult deployApp(File applicationPackage, PrepareParams prepareParams) {
return applicationRepository.deploy(applicationPackage, prepareParams);
}
private PrepareParams prepareParams() {
return new PrepareParams.Builder().applicationId(applicationId()).build();
}
private ApplicationId applicationId() {
return ApplicationId.from(tenant1, ApplicationName.from("testapp"), InstanceName.defaultName());
}
private ApplicationId applicationId(TenantName tenantName) {
return ApplicationId.from(tenantName, ApplicationName.from("testapp"), InstanceName.defaultName());
}
private ApplicationMetaData getApplicationMetaData(ApplicationId applicationId, long sessionId) {
Tenant tenant = tenantRepository.getTenant(applicationId.tenant());
return applicationRepository.getMetadataFromLocalSession(tenant, sessionId);
}
/** Stores all added or set values for each metric and context. */
static class MockMetric implements Metric {
final Map<String, Map<Map<String, ?>, Number>> values = new HashMap<>();
@Override
public void set(String key, Number val, Metric.Context ctx) {
values.putIfAbsent(key, new HashMap<>());
values.get(key).put(((Context) ctx).point, val);
}
@Override
public void add(String key, Number val, Metric.Context ctx) {
throw new UnsupportedOperationException();
}
@Override
public Context createContext(Map<String, ?> properties) {
return new Context(properties);
}
private static class Context implements Metric.Context {
private final Map<String, ?> point;
public Context(Map<String, ?> point) {
this.point = Map.copyOf(point);
}
}
}
} |
Agreed, it's just an implementation detail that they are equal. I'll try to improve this in a later PR. | public void redeploy() {
PrepareResult result = deployApp(testApp);
long firstSessionId = result.sessionId();
PrepareResult result2 = deployApp(testApp);
long secondSessionId = result2.sessionId();
assertNotEquals(firstSessionId, secondSessionId);
TenantName tenantName = applicationId().tenant();
Tenant tenant = tenantRepository.getTenant(tenantName);
LocalSession session = tenant.getLocalSessionRepo().getSession(
tenant.getApplicationRepo().requireActiveSessionOf(applicationId()));
assertEquals(firstSessionId, session.getMetaData().getPreviousActiveGeneration());
} | assertEquals(firstSessionId, session.getMetaData().getPreviousActiveGeneration()); | public void redeploy() {
PrepareResult result = deployApp(testApp);
long firstSessionId = result.sessionId();
PrepareResult result2 = deployApp(testApp);
long secondSessionId = result2.sessionId();
assertNotEquals(firstSessionId, secondSessionId);
TenantName tenantName = applicationId().tenant();
Tenant tenant = tenantRepository.getTenant(tenantName);
LocalSession session = tenant.getLocalSessionRepo().getSession(
tenant.getApplicationRepo().requireActiveSessionOf(applicationId()));
assertEquals(firstSessionId, session.getMetaData().getPreviousActiveGeneration());
} | class ApplicationRepositoryTest {
private final static File testApp = new File("src/test/apps/app");
private final static File testAppJdiscOnly = new File("src/test/apps/app-jdisc-only");
private final static File testAppJdiscOnlyRestart = new File("src/test/apps/app-jdisc-only-restart");
private final static File testAppLogServerWithContainer = new File("src/test/apps/app-logserver-with-container");
private final static TenantName tenant1 = TenantName.from("test1");
private final static TenantName tenant2 = TenantName.from("test2");
private final static TenantName tenant3 = TenantName.from("test3");
private final static Clock clock = Clock.systemUTC();
private ApplicationRepository applicationRepository;
private TenantRepository tenantRepository;
private SessionHandlerTest.MockProvisioner provisioner;
private OrchestratorMock orchestrator;
private TimeoutBudget timeoutBudget;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Before
public void setup() {
Curator curator = new MockCurator();
tenantRepository = new TenantRepository(new TestComponentRegistry.Builder()
.curator(curator)
.build());
tenantRepository.addTenant(TenantRepository.HOSTED_VESPA_TENANT);
tenantRepository.addTenant(tenant1);
tenantRepository.addTenant(tenant2);
tenantRepository.addTenant(tenant3);
orchestrator = new OrchestratorMock();
provisioner = new SessionHandlerTest.MockProvisioner();
applicationRepository = new ApplicationRepository(tenantRepository,
provisioner,
orchestrator,
clock);
timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(60));
}
@Test
public void prepareAndActivate() {
PrepareResult result = prepareAndActivate(testApp);
assertTrue(result.configChangeActions().getRefeedActions().isEmpty());
assertTrue(result.configChangeActions().getRestartActions().isEmpty());
TenantName tenantName = applicationId().tenant();
Tenant tenant = tenantRepository.getTenant(tenantName);
LocalSession session = tenant.getLocalSessionRepo().getSession(tenant.getApplicationRepo()
.requireActiveSessionOf(applicationId()));
session.getAllocatedHosts();
}
@Test
public void prepareAndActivateWithRestart() {
prepareAndActivate(testAppJdiscOnly);
PrepareResult result = prepareAndActivate(testAppJdiscOnlyRestart);
assertTrue(result.configChangeActions().getRefeedActions().isEmpty());
assertFalse(result.configChangeActions().getRestartActions().isEmpty());
}
@Test
public void createAndPrepareAndActivate() {
PrepareResult result = deployApp(testApp);
assertTrue(result.configChangeActions().getRefeedActions().isEmpty());
assertTrue(result.configChangeActions().getRestartActions().isEmpty());
}
@Test
@Test
public void createFromActiveSession() {
PrepareResult result = deployApp(testApp);
long sessionId = applicationRepository.createSessionFromExisting(applicationId(),
new SilentDeployLogger(),
false,
timeoutBudget);
long originalSessionId = result.sessionId();
ApplicationMetaData originalApplicationMetaData = getApplicationMetaData(applicationId(), originalSessionId);
ApplicationMetaData applicationMetaData = getApplicationMetaData(applicationId(), sessionId);
assertNotEquals(sessionId, originalSessionId);
assertEquals(originalApplicationMetaData.getApplicationId(), applicationMetaData.getApplicationId());
assertEquals(originalApplicationMetaData.getGeneration().longValue(), applicationMetaData.getPreviousActiveGeneration());
assertNotEquals(originalApplicationMetaData.getGeneration(), applicationMetaData.getGeneration());
assertEquals(originalApplicationMetaData.getDeployedByUser(), applicationMetaData.getDeployedByUser());
}
@Test
public void testSuspension() {
deployApp(testApp);
assertFalse(applicationRepository.isSuspended(applicationId()));
orchestrator.suspend(applicationId());
assertTrue(applicationRepository.isSuspended(applicationId()));
}
@Test
public void getLogs() {
applicationRepository = createApplicationRepository();
deployApp(testAppLogServerWithContainer);
HttpResponse response = applicationRepository.getLogs(applicationId(), Optional.empty(), "");
assertEquals(200, response.getStatus());
}
@Test
public void getLogsForHostname() {
applicationRepository = createApplicationRepository();
ApplicationId applicationId = ApplicationId.from("hosted-vespa", "tenant-host", "default");
deployApp(testAppLogServerWithContainer, new PrepareParams.Builder().applicationId(applicationId).build());
HttpResponse response = applicationRepository.getLogs(applicationId, Optional.of("localhost"), "");
assertEquals(200, response.getStatus());
}
@Test(expected = IllegalArgumentException.class)
public void refuseToGetLogsFromHostnameNotInApplication() {
applicationRepository = createApplicationRepository();
deployApp(testAppLogServerWithContainer);
HttpResponse response = applicationRepository.getLogs(applicationId(), Optional.of("host123.fake.yahoo.com"), "");
assertEquals(200, response.getStatus());
}
@Test
public void deleteUnusedTenants() {
Instant now = ManualClock.at("1970-01-01T01:00:00");
deployApp(testApp);
deployApp(testApp, new PrepareParams.Builder().applicationId(applicationId(tenant2)).build());
Duration ttlForUnusedTenant = Duration.ofHours(1);
assertTrue(applicationRepository.deleteUnusedTenants(ttlForUnusedTenant, now).isEmpty());
ttlForUnusedTenant = Duration.ofMillis(1);
assertEquals(tenant3, applicationRepository.deleteUnusedTenants(ttlForUnusedTenant, now).iterator().next());
applicationRepository.delete(applicationId());
Set<TenantName> tenantsDeleted = applicationRepository.deleteUnusedTenants(Duration.ofMillis(1), now);
assertTrue(tenantsDeleted.contains(tenant1));
assertFalse(tenantsDeleted.contains(tenant2));
}
@Test
public void deleteUnusedFileReferences() throws IOException {
File fileReferencesDir = temporaryFolder.newFolder();
File filereferenceDir = createFilereferenceOnDisk(new File(fileReferencesDir, "foo"), Instant.now().minus(Duration.ofDays(15)));
File filereferenceDir2 = createFilereferenceOnDisk(new File(fileReferencesDir, "baz"), Instant.now());
tenantRepository.addTenant(tenant1);
Provisioner provisioner = new SessionHandlerTest.MockProvisioner();
applicationRepository = new ApplicationRepository(tenantRepository, provisioner, orchestrator, clock);
timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(60));
PrepareParams prepareParams = new PrepareParams.Builder().applicationId(applicationId()).ignoreValidationErrors(true).build();
deployApp(new File("src/test/apps/app"), prepareParams);
Set<String> toBeDeleted = applicationRepository.deleteUnusedFiledistributionReferences(fileReferencesDir, Duration.ofHours(48));
assertEquals(Collections.singleton("foo"), toBeDeleted);
assertFalse(filereferenceDir.exists());
assertTrue(filereferenceDir2.exists());
}
private File createFilereferenceOnDisk(File filereferenceDir, Instant lastModifiedTime) {
assertTrue(filereferenceDir.mkdir());
File bar = new File(filereferenceDir, "file");
IOUtils.writeFile(bar, Utf8.toBytes("test"));
assertTrue(filereferenceDir.setLastModified(lastModifiedTime.toEpochMilli()));
return filereferenceDir;
}
@Test
public void delete() {
{
PrepareResult result = deployApp(testApp);
long sessionId = result.sessionId();
Tenant tenant = tenantRepository.getTenant(applicationId().tenant());
LocalSession applicationData = tenant.getLocalSessionRepo().getSession(sessionId);
assertNotNull(applicationData);
assertNotNull(applicationData.getApplicationId());
assertNotNull(tenant.getRemoteSessionRepo().getSession(sessionId));
assertNotNull(applicationRepository.getActiveSession(applicationId()));
assertTrue(applicationRepository.delete(applicationId()));
assertNull(applicationRepository.getActiveSession(applicationId()));
assertNull(tenant.getLocalSessionRepo().getSession(sessionId));
assertNull(tenant.getRemoteSessionRepo().getSession(sessionId));
assertTrue(provisioner.removed);
assertEquals(tenant.getName(), provisioner.lastApplicationId.tenant());
assertEquals(applicationId(), provisioner.lastApplicationId);
assertFalse(applicationRepository.delete(applicationId()));
}
{
deployApp(testApp);
assertTrue(applicationRepository.delete(applicationId()));
deployApp(testApp);
ApplicationId fooId = applicationId(tenant2);
PrepareParams prepareParams2 = new PrepareParams.Builder().applicationId(fooId).build();
deployApp(testApp, prepareParams2);
assertNotNull(applicationRepository.getActiveSession(fooId));
assertTrue(applicationRepository.delete(fooId));
assertEquals(fooId, provisioner.lastApplicationId);
assertNotNull(applicationRepository.getActiveSession(applicationId()));
assertTrue(applicationRepository.delete(applicationId()));
}
{
PrepareResult prepareResult = deployApp(testApp);
try {
applicationRepository.delete(applicationId(), Duration.ZERO);
fail("Should have gotten an exception");
} catch (InternalServerException e) {
assertEquals("test1.testapp was not deleted (waited PT0S), session " + prepareResult.sessionId(), e.getMessage());
}
RemoteSession activeSession = applicationRepository.getActiveSession(applicationId());
assertNull(activeSession);
Tenant tenant = tenantRepository.getTenant(applicationId().tenant());
assertNull(tenant.getRemoteSessionRepo().getSession(prepareResult.sessionId()));
assertTrue(applicationRepository.delete(applicationId()));
}
}
@Test
public void testDeletingInactiveSessions() throws IOException {
ManualClock clock = new ManualClock(Instant.now());
ConfigserverConfig configserverConfig =
new ConfigserverConfig(new ConfigserverConfig.Builder()
.configServerDBDir(temporaryFolder.newFolder("serverdb").getAbsolutePath())
.configDefinitionsDir(temporaryFolder.newFolder("configdefinitions").getAbsolutePath())
.sessionLifetime(60));
DeployTester tester = new DeployTester(configserverConfig, clock);
tester.deployApp("src/test/apps/app", clock.instant());
clock.advance(Duration.ofSeconds(10));
Optional<Deployment> deployment2 = tester.redeployFromLocalActive();
assertTrue(deployment2.isPresent());
deployment2.get().activate();
long activeSessionId = tester.tenant().getApplicationRepo().requireActiveSessionOf(tester.applicationId());
clock.advance(Duration.ofSeconds(10));
Optional<com.yahoo.config.provision.Deployment> deployment3 = tester.redeployFromLocalActive();
assertTrue(deployment3.isPresent());
deployment3.get().prepare();
LocalSession deployment3session = ((com.yahoo.vespa.config.server.deploy.Deployment) deployment3.get()).session();
assertNotEquals(activeSessionId, deployment3session);
assertEquals(activeSessionId, tester.tenant().getApplicationRepo().requireActiveSessionOf(tester.applicationId()));
LocalSessionRepo localSessionRepo = tester.tenant().getLocalSessionRepo();
assertEquals(3, localSessionRepo.getSessions().size());
clock.advance(Duration.ofHours(1));
tester.applicationRepository().deleteExpiredLocalSessions();
Collection<LocalSession> sessions = localSessionRepo.getSessions();
assertEquals(1, sessions.size());
ArrayList<LocalSession> localSessions = new ArrayList<>(sessions);
LocalSession localSession = localSessions.get(0);
assertEquals(3, localSession.getSessionId());
assertEquals(0, tester.applicationRepository().deleteExpiredRemoteSessions(clock, Duration.ofSeconds(0)));
Optional<com.yahoo.config.provision.Deployment> deployment4 = tester.redeployFromLocalActive();
assertTrue(deployment4.isPresent());
deployment4.get().prepare();
assertEquals(2, localSessionRepo.getSessions().size());
localSessionRepo.deleteSession(localSession);
assertEquals(1, localSessionRepo.getSessions().size());
tester.applicationRepository().deleteExpiredLocalSessions();
}
@Test
public void testMetrics() {
MockMetric actual = new MockMetric();
applicationRepository = new ApplicationRepository(tenantRepository,
provisioner,
orchestrator,
new ConfigserverConfig(new ConfigserverConfig.Builder()),
new MockLogRetriever(),
new ManualClock(),
new MockTesterClient(),
actual);
deployApp(testAppLogServerWithContainer);
Map<String, ?> context = Map.of("applicationId", "test1.testapp.default",
"tenantName", "test1",
"app", "testapp.default",
"zone", "prod.default");
MockMetric expected = new MockMetric();
expected.set("deployment.prepareMillis", 0L, expected.createContext(context));
expected.set("deployment.activateMillis", 0L, expected.createContext(context));
assertEquals(expected.values, actual.values);
}
@Test
public void deletesApplicationRoles() {
var tenant = tenantRepository.getTenant(tenant1);
var applicationId = applicationId(tenant1);
var prepareParams = new PrepareParams.Builder().applicationId(applicationId)
.applicationRoles(ApplicationRoles.fromString("hostRole","containerRole")).build();
deployApp(testApp, prepareParams);
var approlesStore = new ApplicationRolesStore(tenant.getCurator(), tenant.getPath());
var appRoles = approlesStore.readApplicationRoles(applicationId);
assertTrue(appRoles.isPresent());
assertEquals("hostRole", appRoles.get().applicationHostRole());
assertEquals("containerRole", appRoles.get().applicationContainerRole());
assertTrue(applicationRepository.delete(applicationId));
assertTrue(approlesStore.readApplicationRoles(applicationId).isEmpty());
}
@Test
public void require_that_provision_info_can_be_read() {
prepareAndActivate(testAppJdiscOnly);
TenantName tenantName = applicationId().tenant();
Tenant tenant = tenantRepository.getTenant(tenantName);
LocalSession session = tenant.getLocalSessionRepo().getSession(tenant.getApplicationRepo().requireActiveSessionOf(applicationId()));
List<NetworkPorts.Allocation> list = new ArrayList<>();
list.add(new NetworkPorts.Allocation(8080, "container", "container/container.0", "http"));
list.add(new NetworkPorts.Allocation(19070, "configserver", "admin/configservers/configserver.0", "rpc"));
list.add(new NetworkPorts.Allocation(19071, "configserver", "admin/configservers/configserver.0", "http"));
list.add(new NetworkPorts.Allocation(19080, "logserver", "admin/logserver", "rpc"));
list.add(new NetworkPorts.Allocation(19081, "logserver", "admin/logserver", "unused/1"));
list.add(new NetworkPorts.Allocation(19082, "logserver", "admin/logserver", "unused/2"));
list.add(new NetworkPorts.Allocation(19083, "logserver", "admin/logserver", "unused/3"));
list.add(new NetworkPorts.Allocation(19089, "logd", "hosts/mytesthost/logd", "http"));
list.add(new NetworkPorts.Allocation(19090, "configproxy", "hosts/mytesthost/configproxy", "rpc"));
list.add(new NetworkPorts.Allocation(19092, "metricsproxy-container", "admin/metrics/mytesthost", "http"));
list.add(new NetworkPorts.Allocation(19093, "metricsproxy-container", "admin/metrics/mytesthost", "http/1"));
list.add(new NetworkPorts.Allocation(19094, "metricsproxy-container", "admin/metrics/mytesthost", "rpc/admin"));
list.add(new NetworkPorts.Allocation(19095, "metricsproxy-container", "admin/metrics/mytesthost", "rpc/metrics"));
list.add(new NetworkPorts.Allocation(19097, "config-sentinel", "hosts/mytesthost/sentinel", "rpc"));
list.add(new NetworkPorts.Allocation(19098, "config-sentinel", "hosts/mytesthost/sentinel", "http"));
list.add(new NetworkPorts.Allocation(19099, "slobrok", "admin/slobrok.0", "rpc"));
list.add(new NetworkPorts.Allocation(19100, "container", "container/container.0", "http/1"));
list.add(new NetworkPorts.Allocation(19101, "container", "container/container.0", "messaging"));
list.add(new NetworkPorts.Allocation(19102, "container", "container/container.0", "rpc/admin"));
list.add(new NetworkPorts.Allocation(19103, "slobrok", "admin/slobrok.0", "http"));
AllocatedHosts info = session.getAllocatedHosts();
assertNotNull(info);
assertThat(info.getHosts().size(), is(1));
assertTrue(info.getHosts().contains(new HostSpec("mytesthost",
Collections.emptyList(),
Optional.empty())));
Optional<NetworkPorts> portsCopy = info.getHosts().iterator().next().networkPorts();
assertTrue(portsCopy.isPresent());
assertThat(portsCopy.get().allocations(), is(list));
}
@Test
public void testActivationOfUnpreparedSession() {
PrepareResult result = deployApp(testApp);
long firstSession = result.sessionId();
TimeoutBudget timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(10));
long sessionId = applicationRepository.createSession(applicationId(), timeoutBudget, testAppJdiscOnly);
exceptionRule.expect(IllegalStateException.class);
exceptionRule.expectMessage(containsString("tenant:test1 Session 3 is not prepared"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId, timeoutBudget, false);
RemoteSession activeSession = applicationRepository.getActiveSession(applicationId());
assertEquals(firstSession, activeSession.getSessionId());
assertEquals(Session.Status.ACTIVATE, activeSession.getStatus());
}
@Test
public void testActivationTimesOut() {
PrepareResult result = deployApp(testAppJdiscOnly);
long firstSession = result.sessionId();
long sessionId = applicationRepository.createSession(applicationId(), timeoutBudget, testAppJdiscOnly);
applicationRepository.prepare(tenantRepository.getTenant(tenant1), sessionId, prepareParams(), clock.instant());
exceptionRule.expect(RuntimeException.class);
exceptionRule.expectMessage(containsString("Timeout exceeded when trying to activate 'test1.testapp'"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId, new TimeoutBudget(clock, Duration.ofSeconds(0)), false);
RemoteSession activeSession = applicationRepository.getActiveSession(applicationId());
assertEquals(firstSession, activeSession.getSessionId());
assertEquals(Session.Status.ACTIVATE, activeSession.getStatus());
}
@Test
public void testActivationOfSessionCreatedFromNoLongerActiveSessionFails() {
TimeoutBudget timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(10));
PrepareResult result1 = deployApp(testAppJdiscOnly);
result1.sessionId();
long sessionId2 = applicationRepository.createSessionFromExisting(applicationId(),
new BaseDeployLogger(),
false,
timeoutBudget);
PrepareResult result2 = deployApp(testAppJdiscOnly);
result2.sessionId();
applicationRepository.prepare(tenantRepository.getTenant(tenant1), sessionId2, prepareParams(), clock.instant());
exceptionRule.expect(ActivationConflictException.class);
exceptionRule.expectMessage(containsString("tenant:test1 app:testapp:default Cannot activate session 3 because the currently active session (4) has changed since session 3 was created (was 2 at creation time)"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId2, timeoutBudget, false);
}
@Test
public void testPrepareAndActivateAlreadyActivatedSession() {
PrepareResult result = deployApp(testAppJdiscOnly);
long sessionId = result.sessionId();
exceptionRule.expect(IllegalStateException.class);
exceptionRule.expectMessage(containsString("Session is active: 2"));
applicationRepository.prepare(tenantRepository.getTenant(tenant1), sessionId, prepareParams(), clock.instant());
exceptionRule.expect(IllegalStateException.class);
exceptionRule.expectMessage(containsString("tenant:test1 app:testapp:default Session 2 is already active"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId, timeoutBudget, false);
}
@Test
public void testThatPreviousSessionIsDeactivated() {
deployApp(testAppJdiscOnly);
Session firstSession = applicationRepository.getActiveSession(applicationId());
deployApp(testAppJdiscOnly);
assertEquals(Session.Status.DEACTIVATE, firstSession.getStatus());
}
private ApplicationRepository createApplicationRepository() {
return new ApplicationRepository(tenantRepository,
provisioner,
orchestrator,
new ConfigserverConfig(new ConfigserverConfig.Builder()),
new MockLogRetriever(),
clock,
new MockTesterClient(),
new NullMetric());
}
private PrepareResult prepareAndActivate(File application) {
return applicationRepository.deploy(application, prepareParams(), false, Instant.now());
}
private PrepareResult deployApp(File applicationPackage) {
return deployApp(applicationPackage, prepareParams());
}
private PrepareResult deployApp(File applicationPackage, PrepareParams prepareParams) {
return applicationRepository.deploy(applicationPackage, prepareParams);
}
private PrepareParams prepareParams() {
return new PrepareParams.Builder().applicationId(applicationId()).build();
}
private ApplicationId applicationId() {
return ApplicationId.from(tenant1, ApplicationName.from("testapp"), InstanceName.defaultName());
}
private ApplicationId applicationId(TenantName tenantName) {
return ApplicationId.from(tenantName, ApplicationName.from("testapp"), InstanceName.defaultName());
}
private ApplicationMetaData getApplicationMetaData(ApplicationId applicationId, long sessionId) {
Tenant tenant = tenantRepository.getTenant(applicationId.tenant());
return applicationRepository.getMetadataFromLocalSession(tenant, sessionId);
}
/** Stores all added or set values for each metric and context. */
static class MockMetric implements Metric {
final Map<String, Map<Map<String, ?>, Number>> values = new HashMap<>();
@Override
public void set(String key, Number val, Metric.Context ctx) {
values.putIfAbsent(key, new HashMap<>());
values.get(key).put(((Context) ctx).point, val);
}
@Override
public void add(String key, Number val, Metric.Context ctx) {
throw new UnsupportedOperationException();
}
@Override
public Context createContext(Map<String, ?> properties) {
return new Context(properties);
}
private static class Context implements Metric.Context {
private final Map<String, ?> point;
public Context(Map<String, ?> point) {
this.point = Map.copyOf(point);
}
}
}
} | class ApplicationRepositoryTest {
private final static File testApp = new File("src/test/apps/app");
private final static File testAppJdiscOnly = new File("src/test/apps/app-jdisc-only");
private final static File testAppJdiscOnlyRestart = new File("src/test/apps/app-jdisc-only-restart");
private final static File testAppLogServerWithContainer = new File("src/test/apps/app-logserver-with-container");
private final static TenantName tenant1 = TenantName.from("test1");
private final static TenantName tenant2 = TenantName.from("test2");
private final static TenantName tenant3 = TenantName.from("test3");
private final static Clock clock = Clock.systemUTC();
private ApplicationRepository applicationRepository;
private TenantRepository tenantRepository;
private SessionHandlerTest.MockProvisioner provisioner;
private OrchestratorMock orchestrator;
private TimeoutBudget timeoutBudget;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Before
public void setup() {
Curator curator = new MockCurator();
tenantRepository = new TenantRepository(new TestComponentRegistry.Builder()
.curator(curator)
.build());
tenantRepository.addTenant(TenantRepository.HOSTED_VESPA_TENANT);
tenantRepository.addTenant(tenant1);
tenantRepository.addTenant(tenant2);
tenantRepository.addTenant(tenant3);
orchestrator = new OrchestratorMock();
provisioner = new SessionHandlerTest.MockProvisioner();
applicationRepository = new ApplicationRepository(tenantRepository,
provisioner,
orchestrator,
clock);
timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(60));
}
@Test
public void prepareAndActivate() {
PrepareResult result = prepareAndActivate(testApp);
assertTrue(result.configChangeActions().getRefeedActions().isEmpty());
assertTrue(result.configChangeActions().getRestartActions().isEmpty());
TenantName tenantName = applicationId().tenant();
Tenant tenant = tenantRepository.getTenant(tenantName);
LocalSession session = tenant.getLocalSessionRepo().getSession(tenant.getApplicationRepo()
.requireActiveSessionOf(applicationId()));
session.getAllocatedHosts();
}
@Test
public void prepareAndActivateWithRestart() {
prepareAndActivate(testAppJdiscOnly);
PrepareResult result = prepareAndActivate(testAppJdiscOnlyRestart);
assertTrue(result.configChangeActions().getRefeedActions().isEmpty());
assertFalse(result.configChangeActions().getRestartActions().isEmpty());
}
@Test
public void createAndPrepareAndActivate() {
PrepareResult result = deployApp(testApp);
assertTrue(result.configChangeActions().getRefeedActions().isEmpty());
assertTrue(result.configChangeActions().getRestartActions().isEmpty());
}
@Test
@Test
public void createFromActiveSession() {
PrepareResult result = deployApp(testApp);
long sessionId = applicationRepository.createSessionFromExisting(applicationId(),
new SilentDeployLogger(),
false,
timeoutBudget);
long originalSessionId = result.sessionId();
ApplicationMetaData originalApplicationMetaData = getApplicationMetaData(applicationId(), originalSessionId);
ApplicationMetaData applicationMetaData = getApplicationMetaData(applicationId(), sessionId);
assertNotEquals(sessionId, originalSessionId);
assertEquals(originalApplicationMetaData.getApplicationId(), applicationMetaData.getApplicationId());
assertEquals(originalApplicationMetaData.getGeneration().longValue(), applicationMetaData.getPreviousActiveGeneration());
assertNotEquals(originalApplicationMetaData.getGeneration(), applicationMetaData.getGeneration());
assertEquals(originalApplicationMetaData.getDeployedByUser(), applicationMetaData.getDeployedByUser());
}
@Test
public void testSuspension() {
deployApp(testApp);
assertFalse(applicationRepository.isSuspended(applicationId()));
orchestrator.suspend(applicationId());
assertTrue(applicationRepository.isSuspended(applicationId()));
}
@Test
public void getLogs() {
applicationRepository = createApplicationRepository();
deployApp(testAppLogServerWithContainer);
HttpResponse response = applicationRepository.getLogs(applicationId(), Optional.empty(), "");
assertEquals(200, response.getStatus());
}
@Test
public void getLogsForHostname() {
applicationRepository = createApplicationRepository();
ApplicationId applicationId = ApplicationId.from("hosted-vespa", "tenant-host", "default");
deployApp(testAppLogServerWithContainer, new PrepareParams.Builder().applicationId(applicationId).build());
HttpResponse response = applicationRepository.getLogs(applicationId, Optional.of("localhost"), "");
assertEquals(200, response.getStatus());
}
@Test(expected = IllegalArgumentException.class)
public void refuseToGetLogsFromHostnameNotInApplication() {
applicationRepository = createApplicationRepository();
deployApp(testAppLogServerWithContainer);
HttpResponse response = applicationRepository.getLogs(applicationId(), Optional.of("host123.fake.yahoo.com"), "");
assertEquals(200, response.getStatus());
}
@Test
public void deleteUnusedTenants() {
Instant now = ManualClock.at("1970-01-01T01:00:00");
deployApp(testApp);
deployApp(testApp, new PrepareParams.Builder().applicationId(applicationId(tenant2)).build());
Duration ttlForUnusedTenant = Duration.ofHours(1);
assertTrue(applicationRepository.deleteUnusedTenants(ttlForUnusedTenant, now).isEmpty());
ttlForUnusedTenant = Duration.ofMillis(1);
assertEquals(tenant3, applicationRepository.deleteUnusedTenants(ttlForUnusedTenant, now).iterator().next());
applicationRepository.delete(applicationId());
Set<TenantName> tenantsDeleted = applicationRepository.deleteUnusedTenants(Duration.ofMillis(1), now);
assertTrue(tenantsDeleted.contains(tenant1));
assertFalse(tenantsDeleted.contains(tenant2));
}
@Test
public void deleteUnusedFileReferences() throws IOException {
File fileReferencesDir = temporaryFolder.newFolder();
File filereferenceDir = createFilereferenceOnDisk(new File(fileReferencesDir, "foo"), Instant.now().minus(Duration.ofDays(15)));
File filereferenceDir2 = createFilereferenceOnDisk(new File(fileReferencesDir, "baz"), Instant.now());
tenantRepository.addTenant(tenant1);
Provisioner provisioner = new SessionHandlerTest.MockProvisioner();
applicationRepository = new ApplicationRepository(tenantRepository, provisioner, orchestrator, clock);
timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(60));
PrepareParams prepareParams = new PrepareParams.Builder().applicationId(applicationId()).ignoreValidationErrors(true).build();
deployApp(new File("src/test/apps/app"), prepareParams);
Set<String> toBeDeleted = applicationRepository.deleteUnusedFiledistributionReferences(fileReferencesDir, Duration.ofHours(48));
assertEquals(Collections.singleton("foo"), toBeDeleted);
assertFalse(filereferenceDir.exists());
assertTrue(filereferenceDir2.exists());
}
private File createFilereferenceOnDisk(File filereferenceDir, Instant lastModifiedTime) {
assertTrue(filereferenceDir.mkdir());
File bar = new File(filereferenceDir, "file");
IOUtils.writeFile(bar, Utf8.toBytes("test"));
assertTrue(filereferenceDir.setLastModified(lastModifiedTime.toEpochMilli()));
return filereferenceDir;
}
@Test
public void delete() {
{
PrepareResult result = deployApp(testApp);
long sessionId = result.sessionId();
Tenant tenant = tenantRepository.getTenant(applicationId().tenant());
LocalSession applicationData = tenant.getLocalSessionRepo().getSession(sessionId);
assertNotNull(applicationData);
assertNotNull(applicationData.getApplicationId());
assertNotNull(tenant.getRemoteSessionRepo().getSession(sessionId));
assertNotNull(applicationRepository.getActiveSession(applicationId()));
assertTrue(applicationRepository.delete(applicationId()));
assertNull(applicationRepository.getActiveSession(applicationId()));
assertNull(tenant.getLocalSessionRepo().getSession(sessionId));
assertNull(tenant.getRemoteSessionRepo().getSession(sessionId));
assertTrue(provisioner.removed);
assertEquals(tenant.getName(), provisioner.lastApplicationId.tenant());
assertEquals(applicationId(), provisioner.lastApplicationId);
assertFalse(applicationRepository.delete(applicationId()));
}
{
deployApp(testApp);
assertTrue(applicationRepository.delete(applicationId()));
deployApp(testApp);
ApplicationId fooId = applicationId(tenant2);
PrepareParams prepareParams2 = new PrepareParams.Builder().applicationId(fooId).build();
deployApp(testApp, prepareParams2);
assertNotNull(applicationRepository.getActiveSession(fooId));
assertTrue(applicationRepository.delete(fooId));
assertEquals(fooId, provisioner.lastApplicationId);
assertNotNull(applicationRepository.getActiveSession(applicationId()));
assertTrue(applicationRepository.delete(applicationId()));
}
{
PrepareResult prepareResult = deployApp(testApp);
try {
applicationRepository.delete(applicationId(), Duration.ZERO);
fail("Should have gotten an exception");
} catch (InternalServerException e) {
assertEquals("test1.testapp was not deleted (waited PT0S), session " + prepareResult.sessionId(), e.getMessage());
}
RemoteSession activeSession = applicationRepository.getActiveSession(applicationId());
assertNull(activeSession);
Tenant tenant = tenantRepository.getTenant(applicationId().tenant());
assertNull(tenant.getRemoteSessionRepo().getSession(prepareResult.sessionId()));
assertTrue(applicationRepository.delete(applicationId()));
}
}
@Test
public void testDeletingInactiveSessions() throws IOException {
ManualClock clock = new ManualClock(Instant.now());
ConfigserverConfig configserverConfig =
new ConfigserverConfig(new ConfigserverConfig.Builder()
.configServerDBDir(temporaryFolder.newFolder("serverdb").getAbsolutePath())
.configDefinitionsDir(temporaryFolder.newFolder("configdefinitions").getAbsolutePath())
.sessionLifetime(60));
DeployTester tester = new DeployTester(configserverConfig, clock);
tester.deployApp("src/test/apps/app", clock.instant());
clock.advance(Duration.ofSeconds(10));
Optional<Deployment> deployment2 = tester.redeployFromLocalActive();
assertTrue(deployment2.isPresent());
deployment2.get().activate();
long activeSessionId = tester.tenant().getApplicationRepo().requireActiveSessionOf(tester.applicationId());
clock.advance(Duration.ofSeconds(10));
Optional<com.yahoo.config.provision.Deployment> deployment3 = tester.redeployFromLocalActive();
assertTrue(deployment3.isPresent());
deployment3.get().prepare();
LocalSession deployment3session = ((com.yahoo.vespa.config.server.deploy.Deployment) deployment3.get()).session();
assertNotEquals(activeSessionId, deployment3session);
assertEquals(activeSessionId, tester.tenant().getApplicationRepo().requireActiveSessionOf(tester.applicationId()));
LocalSessionRepo localSessionRepo = tester.tenant().getLocalSessionRepo();
assertEquals(3, localSessionRepo.getSessions().size());
clock.advance(Duration.ofHours(1));
tester.applicationRepository().deleteExpiredLocalSessions();
Collection<LocalSession> sessions = localSessionRepo.getSessions();
assertEquals(1, sessions.size());
ArrayList<LocalSession> localSessions = new ArrayList<>(sessions);
LocalSession localSession = localSessions.get(0);
assertEquals(3, localSession.getSessionId());
assertEquals(0, tester.applicationRepository().deleteExpiredRemoteSessions(clock, Duration.ofSeconds(0)));
Optional<com.yahoo.config.provision.Deployment> deployment4 = tester.redeployFromLocalActive();
assertTrue(deployment4.isPresent());
deployment4.get().prepare();
assertEquals(2, localSessionRepo.getSessions().size());
localSessionRepo.deleteSession(localSession);
assertEquals(1, localSessionRepo.getSessions().size());
tester.applicationRepository().deleteExpiredLocalSessions();
}
@Test
public void testMetrics() {
MockMetric actual = new MockMetric();
applicationRepository = new ApplicationRepository(tenantRepository,
provisioner,
orchestrator,
new ConfigserverConfig(new ConfigserverConfig.Builder()),
new MockLogRetriever(),
new ManualClock(),
new MockTesterClient(),
actual);
deployApp(testAppLogServerWithContainer);
Map<String, ?> context = Map.of("applicationId", "test1.testapp.default",
"tenantName", "test1",
"app", "testapp.default",
"zone", "prod.default");
MockMetric expected = new MockMetric();
expected.set("deployment.prepareMillis", 0L, expected.createContext(context));
expected.set("deployment.activateMillis", 0L, expected.createContext(context));
assertEquals(expected.values, actual.values);
}
@Test
public void deletesApplicationRoles() {
var tenant = tenantRepository.getTenant(tenant1);
var applicationId = applicationId(tenant1);
var prepareParams = new PrepareParams.Builder().applicationId(applicationId)
.applicationRoles(ApplicationRoles.fromString("hostRole","containerRole")).build();
deployApp(testApp, prepareParams);
var approlesStore = new ApplicationRolesStore(tenant.getCurator(), tenant.getPath());
var appRoles = approlesStore.readApplicationRoles(applicationId);
assertTrue(appRoles.isPresent());
assertEquals("hostRole", appRoles.get().applicationHostRole());
assertEquals("containerRole", appRoles.get().applicationContainerRole());
assertTrue(applicationRepository.delete(applicationId));
assertTrue(approlesStore.readApplicationRoles(applicationId).isEmpty());
}
@Test
public void require_that_provision_info_can_be_read() {
prepareAndActivate(testAppJdiscOnly);
TenantName tenantName = applicationId().tenant();
Tenant tenant = tenantRepository.getTenant(tenantName);
LocalSession session = tenant.getLocalSessionRepo().getSession(tenant.getApplicationRepo().requireActiveSessionOf(applicationId()));
List<NetworkPorts.Allocation> list = new ArrayList<>();
list.add(new NetworkPorts.Allocation(8080, "container", "container/container.0", "http"));
list.add(new NetworkPorts.Allocation(19070, "configserver", "admin/configservers/configserver.0", "rpc"));
list.add(new NetworkPorts.Allocation(19071, "configserver", "admin/configservers/configserver.0", "http"));
list.add(new NetworkPorts.Allocation(19080, "logserver", "admin/logserver", "rpc"));
list.add(new NetworkPorts.Allocation(19081, "logserver", "admin/logserver", "unused/1"));
list.add(new NetworkPorts.Allocation(19082, "logserver", "admin/logserver", "unused/2"));
list.add(new NetworkPorts.Allocation(19083, "logserver", "admin/logserver", "unused/3"));
list.add(new NetworkPorts.Allocation(19089, "logd", "hosts/mytesthost/logd", "http"));
list.add(new NetworkPorts.Allocation(19090, "configproxy", "hosts/mytesthost/configproxy", "rpc"));
list.add(new NetworkPorts.Allocation(19092, "metricsproxy-container", "admin/metrics/mytesthost", "http"));
list.add(new NetworkPorts.Allocation(19093, "metricsproxy-container", "admin/metrics/mytesthost", "http/1"));
list.add(new NetworkPorts.Allocation(19094, "metricsproxy-container", "admin/metrics/mytesthost", "rpc/admin"));
list.add(new NetworkPorts.Allocation(19095, "metricsproxy-container", "admin/metrics/mytesthost", "rpc/metrics"));
list.add(new NetworkPorts.Allocation(19097, "config-sentinel", "hosts/mytesthost/sentinel", "rpc"));
list.add(new NetworkPorts.Allocation(19098, "config-sentinel", "hosts/mytesthost/sentinel", "http"));
list.add(new NetworkPorts.Allocation(19099, "slobrok", "admin/slobrok.0", "rpc"));
list.add(new NetworkPorts.Allocation(19100, "container", "container/container.0", "http/1"));
list.add(new NetworkPorts.Allocation(19101, "container", "container/container.0", "messaging"));
list.add(new NetworkPorts.Allocation(19102, "container", "container/container.0", "rpc/admin"));
list.add(new NetworkPorts.Allocation(19103, "slobrok", "admin/slobrok.0", "http"));
AllocatedHosts info = session.getAllocatedHosts();
assertNotNull(info);
assertThat(info.getHosts().size(), is(1));
assertTrue(info.getHosts().contains(new HostSpec("mytesthost",
Collections.emptyList(),
Optional.empty())));
Optional<NetworkPorts> portsCopy = info.getHosts().iterator().next().networkPorts();
assertTrue(portsCopy.isPresent());
assertThat(portsCopy.get().allocations(), is(list));
}
@Test
public void testActivationOfUnpreparedSession() {
PrepareResult result = deployApp(testApp);
long firstSession = result.sessionId();
TimeoutBudget timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(10));
long sessionId = applicationRepository.createSession(applicationId(), timeoutBudget, testAppJdiscOnly);
exceptionRule.expect(IllegalStateException.class);
exceptionRule.expectMessage(containsString("tenant:test1 Session 3 is not prepared"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId, timeoutBudget, false);
RemoteSession activeSession = applicationRepository.getActiveSession(applicationId());
assertEquals(firstSession, activeSession.getSessionId());
assertEquals(Session.Status.ACTIVATE, activeSession.getStatus());
}
@Test
public void testActivationTimesOut() {
PrepareResult result = deployApp(testAppJdiscOnly);
long firstSession = result.sessionId();
long sessionId = applicationRepository.createSession(applicationId(), timeoutBudget, testAppJdiscOnly);
applicationRepository.prepare(tenantRepository.getTenant(tenant1), sessionId, prepareParams(), clock.instant());
exceptionRule.expect(RuntimeException.class);
exceptionRule.expectMessage(containsString("Timeout exceeded when trying to activate 'test1.testapp'"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId, new TimeoutBudget(clock, Duration.ofSeconds(0)), false);
RemoteSession activeSession = applicationRepository.getActiveSession(applicationId());
assertEquals(firstSession, activeSession.getSessionId());
assertEquals(Session.Status.ACTIVATE, activeSession.getStatus());
}
@Test
public void testActivationOfSessionCreatedFromNoLongerActiveSessionFails() {
TimeoutBudget timeoutBudget = new TimeoutBudget(clock, Duration.ofSeconds(10));
PrepareResult result1 = deployApp(testAppJdiscOnly);
result1.sessionId();
long sessionId2 = applicationRepository.createSessionFromExisting(applicationId(),
new BaseDeployLogger(),
false,
timeoutBudget);
PrepareResult result2 = deployApp(testAppJdiscOnly);
result2.sessionId();
applicationRepository.prepare(tenantRepository.getTenant(tenant1), sessionId2, prepareParams(), clock.instant());
exceptionRule.expect(ActivationConflictException.class);
exceptionRule.expectMessage(containsString("tenant:test1 app:testapp:default Cannot activate session 3 because the currently active session (4) has changed since session 3 was created (was 2 at creation time)"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId2, timeoutBudget, false);
}
@Test
public void testPrepareAndActivateAlreadyActivatedSession() {
PrepareResult result = deployApp(testAppJdiscOnly);
long sessionId = result.sessionId();
exceptionRule.expect(IllegalStateException.class);
exceptionRule.expectMessage(containsString("Session is active: 2"));
applicationRepository.prepare(tenantRepository.getTenant(tenant1), sessionId, prepareParams(), clock.instant());
exceptionRule.expect(IllegalStateException.class);
exceptionRule.expectMessage(containsString("tenant:test1 app:testapp:default Session 2 is already active"));
applicationRepository.activate(tenantRepository.getTenant(tenant1), sessionId, timeoutBudget, false);
}
@Test
public void testThatPreviousSessionIsDeactivated() {
deployApp(testAppJdiscOnly);
Session firstSession = applicationRepository.getActiveSession(applicationId());
deployApp(testAppJdiscOnly);
assertEquals(Session.Status.DEACTIVATE, firstSession.getStatus());
}
private ApplicationRepository createApplicationRepository() {
return new ApplicationRepository(tenantRepository,
provisioner,
orchestrator,
new ConfigserverConfig(new ConfigserverConfig.Builder()),
new MockLogRetriever(),
clock,
new MockTesterClient(),
new NullMetric());
}
private PrepareResult prepareAndActivate(File application) {
return applicationRepository.deploy(application, prepareParams(), false, Instant.now());
}
private PrepareResult deployApp(File applicationPackage) {
return deployApp(applicationPackage, prepareParams());
}
private PrepareResult deployApp(File applicationPackage, PrepareParams prepareParams) {
return applicationRepository.deploy(applicationPackage, prepareParams);
}
private PrepareParams prepareParams() {
return new PrepareParams.Builder().applicationId(applicationId()).build();
}
private ApplicationId applicationId() {
return ApplicationId.from(tenant1, ApplicationName.from("testapp"), InstanceName.defaultName());
}
private ApplicationId applicationId(TenantName tenantName) {
return ApplicationId.from(tenantName, ApplicationName.from("testapp"), InstanceName.defaultName());
}
private ApplicationMetaData getApplicationMetaData(ApplicationId applicationId, long sessionId) {
Tenant tenant = tenantRepository.getTenant(applicationId.tenant());
return applicationRepository.getMetadataFromLocalSession(tenant, sessionId);
}
/** Stores all added or set values for each metric and context. */
static class MockMetric implements Metric {
final Map<String, Map<Map<String, ?>, Number>> values = new HashMap<>();
@Override
public void set(String key, Number val, Metric.Context ctx) {
values.putIfAbsent(key, new HashMap<>());
values.get(key).put(((Context) ctx).point, val);
}
@Override
public void add(String key, Number val, Metric.Context ctx) {
throw new UnsupportedOperationException();
}
@Override
public Context createContext(Map<String, ?> properties) {
return new Context(properties);
}
private static class Context implements Metric.Context {
private final Map<String, ?> point;
public Context(Map<String, ?> point) {
this.point = Map.copyOf(point);
}
}
}
} |
This could be called unconditionally now. | public void destroy() {
if ( ! isDone())
abort();
} | abort(); | public void destroy() {
abort();
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
data.onMessage(new PutDocumentMessage(new DocumentPut(document)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
}
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final DocumentSelector selector;
private final FieldSet fieldSet;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) throws ParseException {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.selector = new DocumentSelector(parameters.getDocumentSelection());
this.fieldSet = new FieldSetRepo().parse(access.getDocumentTypeManager(), parameters.fieldSet());
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(Comparator.comparing(DocumentId::toString));
this.outstanding.putAll(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
if (state.get() != State.RUNNING)
return;
if (selector.accepts(new DocumentPut(document)) != Result.TRUE)
return;
Document copy = new Document(document.getDataType(), document.getId());
new FieldSetRepo().copyFields(document, copy, fieldSet);
data.onMessage(new PutDocumentMessage(new DocumentPut(copy)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty()
&& control.isDone();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
}
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
} |
Urgh indentation. | void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
data.onMessage(new PutDocumentMessage(new DocumentPut(document)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
} | new AckToken(id)); | void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
if (state.get() != State.RUNNING)
return;
if (selector.accepts(new DocumentPut(document)) != Result.TRUE)
return;
Document copy = new Document(document.getDataType(), document.getId());
new FieldSetRepo().copyFields(document, copy, fieldSet);
data.onMessage(new PutDocumentMessage(new DocumentPut(copy)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
}
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
public void destroy() {
if ( ! isDone())
abort();
}
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final DocumentSelector selector;
private final FieldSet fieldSet;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) throws ParseException {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.selector = new DocumentSelector(parameters.getDocumentSelection());
this.fieldSet = new FieldSetRepo().parse(access.getDocumentTypeManager(), parameters.fieldSet());
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(Comparator.comparing(DocumentId::toString));
this.outstanding.putAll(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty()
&& control.isDone();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
}
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
public void destroy() {
abort();
}
} |
Shall it be guaranteed that `onDocument` is always called from a single thread in the local implementation? If not, consider adding synchronization in the data handlers here. | public void testFeedingAndVisiting() throws InterruptedException, ParseException {
DocumentType musicType = access().getDocumentTypeManager().getDocumentType("music");
Document doc1 = new Document(musicType, "id:ns:music::1"); doc1.setFieldValue("artist", "one");
Document doc2 = new Document(musicType, "id:ns:music::2"); doc2.setFieldValue("artist", "two");
Document doc3 = new Document(musicType, "id:ns:music::3");
VisitorParameters parameters = new VisitorParameters("music.artist");
parameters.setFieldSet("music:artist");
VisitorControlHandler control = new VisitorControlHandler();
parameters.setControlHandler(control);
List<Document> received = new ArrayList<>();
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
received.add(doc);
}
@Override public void onRemove(DocumentId id) {
throw new IllegalStateException("Not supposed to get here");
}
});
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(List.of(),
received);
SyncSession out = access.createSyncSession(new SyncParameters.Builder().build());
out.put(new DocumentPut(doc1));
out.put(new DocumentPut(doc2));
out.put(new DocumentPut(doc3));
assertEquals(Map.of(doc1.getId(), doc1,
doc2.getId(), doc2,
doc3.getId(), doc3),
access.documents);
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(List.of(doc1, doc2),
received);
out.remove(new DocumentRemove(doc2.getId()));
out.update(new DocumentUpdate(musicType, doc3.getId()).addFieldUpdate(FieldUpdate.createAssign(musicType.getField("artist"),
new StringFieldValue("three"))));
assertEquals(Map.of(doc1.getId(), doc1,
doc3.getId(), doc3),
access.documents);
assertEquals("three",
((StringFieldValue) doc3.getFieldValue("artist")).getString());
parameters.setFieldSet("[id]");
received.clear();
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(List.of(new Document(musicType, doc1.getId()), new Document(musicType, doc3.getId())),
received);
received.clear();
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
if (doc3.getId().equals(doc.getId()))
throw new RuntimeException("SEGFAULT");
received.add(doc);
}
@Override public void onRemove(DocumentId id) {
throw new IllegalStateException("Not supposed to get here");
}
});
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.FAILURE,
control.getResult().getCode());
assertEquals("SEGFAULT",
control.getResult().getMessage());
assertEquals(List.of(new Document(musicType, doc1.getId())),
received);
received.clear();
CountDownLatch visitLatch = new CountDownLatch(1);
CountDownLatch abortLatch = new CountDownLatch(1);
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
received.add(doc);
abortLatch.countDown();
try {
visitLatch.await();
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override public void onRemove(DocumentId id) { throw new IllegalStateException("Not supposed to get here"); }
});
VisitorSession visit = access.createVisitorSession(parameters);
abortLatch.await();
control.abort();
visitLatch.countDown();
visit.waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.ABORTED,
control.getResult().getCode());
assertEquals(List.of(new Document(musicType, doc1.getId())),
received);
} | } | public void testFeedingAndVisiting() throws InterruptedException, ParseException {
DocumentType musicType = access().getDocumentTypeManager().getDocumentType("music");
Document doc1 = new Document(musicType, "id:ns:music::1"); doc1.setFieldValue("artist", "one");
Document doc2 = new Document(musicType, "id:ns:music::2"); doc2.setFieldValue("artist", "two");
Document doc3 = new Document(musicType, "id:ns:music::3");
VisitorParameters parameters = new VisitorParameters("music.artist");
parameters.setFieldSet("music:artist");
VisitorControlHandler control = new VisitorControlHandler();
parameters.setControlHandler(control);
Set<Document> received = new ConcurrentSkipListSet<>();
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
received.add(doc);
}
@Override public void onRemove(DocumentId id) {
throw new IllegalStateException("Not supposed to get here");
}
});
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(Set.of(),
received);
SyncSession out = access.createSyncSession(new SyncParameters.Builder().build());
out.put(new DocumentPut(doc1));
out.put(new DocumentPut(doc2));
out.put(new DocumentPut(doc3));
assertEquals(Map.of(doc1.getId(), doc1,
doc2.getId(), doc2,
doc3.getId(), doc3),
access.documents);
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(Set.of(doc1, doc2),
received);
out.remove(new DocumentRemove(doc2.getId()));
out.update(new DocumentUpdate(musicType, doc3.getId()).addFieldUpdate(FieldUpdate.createAssign(musicType.getField("artist"),
new StringFieldValue("three"))));
assertEquals(Map.of(doc1.getId(), doc1,
doc3.getId(), doc3),
access.documents);
assertEquals("three",
((StringFieldValue) doc3.getFieldValue("artist")).getString());
parameters.setFieldSet("[id]");
received.clear();
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(Set.of(new Document(musicType, doc1.getId()), new Document(musicType, doc3.getId())),
received);
received.clear();
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
if (doc3.getId().equals(doc.getId()))
throw new RuntimeException("SEGFAULT");
received.add(doc);
}
@Override public void onRemove(DocumentId id) {
throw new IllegalStateException("Not supposed to get here");
}
});
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.FAILURE,
control.getResult().getCode());
assertEquals("SEGFAULT",
control.getResult().getMessage());
assertEquals(Set.of(new Document(musicType, doc1.getId())),
received);
received.clear();
CountDownLatch visitLatch = new CountDownLatch(1);
CountDownLatch abortLatch = new CountDownLatch(1);
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
received.add(doc);
abortLatch.countDown();
try {
visitLatch.await();
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override public void onRemove(DocumentId id) { throw new IllegalStateException("Not supposed to get here"); }
});
VisitorSession visit = access.createVisitorSession(parameters);
abortLatch.await();
control.abort();
visitLatch.countDown();
visit.waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.ABORTED,
control.getResult().getCode());
assertEquals(Set.of(new Document(musicType, doc1.getId())),
received);
} | class LocalDocumentApiTestCase extends AbstractDocumentApiTestCase {
protected LocalDocumentAccess access;
@Override
protected DocumentAccess access() {
return access;
}
@Before
public void setUp() {
DocumentAccessParams params = new DocumentAccessParams();
params.setDocumentManagerConfigId("file:src/test/cfg/documentmanager.cfg");
access = new LocalDocumentAccess(params);
}
@After
public void shutdownAccess() {
access.shutdown();
}
@Test
public void testNoExceptionFromAsync() {
AsyncSession session = access.createAsyncSession(new AsyncParameters());
DocumentType type = access.getDocumentTypeManager().getDocumentType("music");
DocumentUpdate docUp = new DocumentUpdate(type, new DocumentId("id:ns:music::2"));
Result result = session.update(docUp);
assertTrue(result.isSuccess());
Response response = session.getNext();
assertEquals(result.getRequestId(), response.getRequestId());
assertFalse(response.isSuccess());
session.destroy();
}
@Test
public void testAsyncFetch() {
AsyncSession session = access.createAsyncSession(new AsyncParameters());
List<DocumentId> ids = new ArrayList<>();
ids.add(new DocumentId("id:music:music::1"));
ids.add(new DocumentId("id:music:music::2"));
ids.add(new DocumentId("id:music:music::3"));
for (DocumentId id : ids)
session.put(new Document(access.getDocumentTypeManager().getDocumentType("music"), id));
int timeout = 100;
long startTime = System.currentTimeMillis();
Set<Long> outstandingRequests = new HashSet<>();
for (DocumentId id : ids) {
Result result = session.get(id);
if ( ! result.isSuccess())
throw new IllegalStateException("Failed requesting document " + id, result.getError().getCause());
outstandingRequests.add(result.getRequestId());
}
List<Document> documents = new ArrayList<>();
try {
while ( ! outstandingRequests.isEmpty()) {
int timeSinceStart = (int)(System.currentTimeMillis() - startTime);
Response response = session.getNext(timeout - timeSinceStart);
if (response == null)
throw new RuntimeException("Timed out waiting for documents");
if ( ! outstandingRequests.contains(response.getRequestId())) continue;
if (response.isSuccess())
documents.add(((DocumentResponse)response).getDocument());
outstandingRequests.remove(response.getRequestId());
}
}
catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for documents", e);
}
assertEquals(3, documents.size());
for (Document document : documents)
assertNotNull(document);
}
@Test
} | class LocalDocumentApiTestCase extends AbstractDocumentApiTestCase {
protected LocalDocumentAccess access;
@Override
protected DocumentAccess access() {
return access;
}
@Before
public void setUp() {
DocumentAccessParams params = new DocumentAccessParams();
params.setDocumentManagerConfigId("file:src/test/cfg/documentmanager.cfg");
access = new LocalDocumentAccess(params);
}
@After
public void shutdownAccess() {
access.shutdown();
}
@Test
public void testNoExceptionFromAsync() {
AsyncSession session = access.createAsyncSession(new AsyncParameters());
DocumentType type = access.getDocumentTypeManager().getDocumentType("music");
DocumentUpdate docUp = new DocumentUpdate(type, new DocumentId("id:ns:music::2"));
Result result = session.update(docUp);
assertTrue(result.isSuccess());
Response response = session.getNext();
assertEquals(result.getRequestId(), response.getRequestId());
assertFalse(response.isSuccess());
session.destroy();
}
@Test
public void testAsyncFetch() {
AsyncSession session = access.createAsyncSession(new AsyncParameters());
List<DocumentId> ids = new ArrayList<>();
ids.add(new DocumentId("id:music:music::1"));
ids.add(new DocumentId("id:music:music::2"));
ids.add(new DocumentId("id:music:music::3"));
for (DocumentId id : ids)
session.put(new Document(access.getDocumentTypeManager().getDocumentType("music"), id));
int timeout = 100;
long startTime = System.currentTimeMillis();
Set<Long> outstandingRequests = new HashSet<>();
for (DocumentId id : ids) {
Result result = session.get(id);
if ( ! result.isSuccess())
throw new IllegalStateException("Failed requesting document " + id, result.getError().getCause());
outstandingRequests.add(result.getRequestId());
}
List<Document> documents = new ArrayList<>();
try {
while ( ! outstandingRequests.isEmpty()) {
int timeSinceStart = (int)(System.currentTimeMillis() - startTime);
Response response = session.getNext(timeout - timeSinceStart);
if (response == null)
throw new RuntimeException("Timed out waiting for documents");
if ( ! outstandingRequests.contains(response.getRequestId())) continue;
if (response.isSuccess())
documents.add(((DocumentResponse)response).getDocument());
outstandingRequests.remove(response.getRequestId());
}
}
catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for documents", e);
}
assertEquals(3, documents.size());
for (Document document : documents)
assertNotNull(document);
}
@Test
} |
I'm one of those filthy `{}` lovers, so consider adding braces around at least the outer for-loop since it's easy to accidentally put things in the wrong scope when using multiple nested control flow statements | void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
if (selector.accepts(new DocumentPut(document)) != Result.TRUE)
return;
Document copy = new Document(document.getDataType(), document.getId());
for (Field field : document.getDataType().getFields())
if (fieldSet.contains(field))
copy.setFieldValue(field, document.getFieldValue(field));
data.onMessage(new PutDocumentMessage(new DocumentPut(copy)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
} | copy.setFieldValue(field, document.getFieldValue(field)); | void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
if (state.get() != State.RUNNING)
return;
if (selector.accepts(new DocumentPut(document)) != Result.TRUE)
return;
Document copy = new Document(document.getDataType(), document.getId());
new FieldSetRepo().copyFields(document, copy, fieldSet);
data.onMessage(new PutDocumentMessage(new DocumentPut(copy)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final DocumentSelector selector;
private final FieldSet fieldSet;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) throws ParseException {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.selector = new DocumentSelector(parameters.getDocumentSelection());
this.fieldSet = new FieldSetRepo().parse(access.getDocumentTypeManager(), parameters.fieldSet());
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(Comparator.comparing(DocumentId::toString));
this.outstanding.putAll(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty()
&& control.isDone();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
}
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
public void destroy() {
abort();
}
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final DocumentSelector selector;
private final FieldSet fieldSet;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) throws ParseException {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.selector = new DocumentSelector(parameters.getDocumentSelection());
this.fieldSet = new FieldSetRepo().parse(access.getDocumentTypeManager(), parameters.fieldSet());
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(Comparator.comparing(DocumentId::toString));
this.outstanding.putAll(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty()
&& control.isDone();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
}
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
public void destroy() {
abort();
}
} |
Alternatively, I see that this functionality is already provided in `FieldSetRepo.copyFields` | void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
if (selector.accepts(new DocumentPut(document)) != Result.TRUE)
return;
Document copy = new Document(document.getDataType(), document.getId());
for (Field field : document.getDataType().getFields())
if (fieldSet.contains(field))
copy.setFieldValue(field, document.getFieldValue(field));
data.onMessage(new PutDocumentMessage(new DocumentPut(copy)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
} | copy.setFieldValue(field, document.getFieldValue(field)); | void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
if (state.get() != State.RUNNING)
return;
if (selector.accepts(new DocumentPut(document)) != Result.TRUE)
return;
Document copy = new Document(document.getDataType(), document.getId());
new FieldSetRepo().copyFields(document, copy, fieldSet);
data.onMessage(new PutDocumentMessage(new DocumentPut(copy)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final DocumentSelector selector;
private final FieldSet fieldSet;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) throws ParseException {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.selector = new DocumentSelector(parameters.getDocumentSelection());
this.fieldSet = new FieldSetRepo().parse(access.getDocumentTypeManager(), parameters.fieldSet());
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(Comparator.comparing(DocumentId::toString));
this.outstanding.putAll(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty()
&& control.isDone();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
}
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
public void destroy() {
abort();
}
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final DocumentSelector selector;
private final FieldSet fieldSet;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) throws ParseException {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.selector = new DocumentSelector(parameters.getDocumentSelection());
this.fieldSet = new FieldSetRepo().parse(access.getDocumentTypeManager(), parameters.fieldSet());
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(Comparator.comparing(DocumentId::toString));
this.outstanding.putAll(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty()
&& control.isDone();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
}
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
public void destroy() {
abort();
}
} |
Its iterators are [weakly consistent](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html#Weakly) — while this is weakly defined, they _can_ reflect changes during iteration. This is the case for the last part of the unit test. I suppose this test would break, were the implementation of `ConcurrentSkipListMap` ever to change. | public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
} | } | public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final DocumentSelector selector;
private final FieldSet fieldSet;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) throws ParseException {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.selector = new DocumentSelector(parameters.getDocumentSelection());
this.fieldSet = new FieldSetRepo().parse(access.getDocumentTypeManager(), parameters.fieldSet());
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(Comparator.comparing(DocumentId::toString));
this.outstanding.putAll(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
if (selector.accepts(new DocumentPut(document)) != Result.TRUE)
return;
Document copy = new Document(document.getDataType(), document.getId());
for (Field field : document.getDataType().getFields())
if (fieldSet.contains(field))
copy.setFieldValue(field, document.getFieldValue(field));
data.onMessage(new PutDocumentMessage(new DocumentPut(copy)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty()
&& control.isDone();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
public void destroy() {
abort();
}
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final DocumentSelector selector;
private final FieldSet fieldSet;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) throws ParseException {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.selector = new DocumentSelector(parameters.getDocumentSelection());
this.fieldSet = new FieldSetRepo().parse(access.getDocumentTypeManager(), parameters.fieldSet());
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(Comparator.comparing(DocumentId::toString));
this.outstanding.putAll(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
if (state.get() != State.RUNNING)
return;
if (selector.accepts(new DocumentPut(document)) != Result.TRUE)
return;
Document copy = new Document(document.getDataType(), document.getId());
new FieldSetRepo().copyFields(document, copy, fieldSet);
data.onMessage(new PutDocumentMessage(new DocumentPut(copy)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty()
&& control.isDone();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
public void destroy() {
abort();
}
} |
Sweet! | void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
if (selector.accepts(new DocumentPut(document)) != Result.TRUE)
return;
Document copy = new Document(document.getDataType(), document.getId());
for (Field field : document.getDataType().getFields())
if (fieldSet.contains(field))
copy.setFieldValue(field, document.getFieldValue(field));
data.onMessage(new PutDocumentMessage(new DocumentPut(copy)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
} | copy.setFieldValue(field, document.getFieldValue(field)); | void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
if (state.get() != State.RUNNING)
return;
if (selector.accepts(new DocumentPut(document)) != Result.TRUE)
return;
Document copy = new Document(document.getDataType(), document.getId());
new FieldSetRepo().copyFields(document, copy, fieldSet);
data.onMessage(new PutDocumentMessage(new DocumentPut(copy)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final DocumentSelector selector;
private final FieldSet fieldSet;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) throws ParseException {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.selector = new DocumentSelector(parameters.getDocumentSelection());
this.fieldSet = new FieldSetRepo().parse(access.getDocumentTypeManager(), parameters.fieldSet());
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(Comparator.comparing(DocumentId::toString));
this.outstanding.putAll(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty()
&& control.isDone();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
}
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
public void destroy() {
abort();
}
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final DocumentSelector selector;
private final FieldSet fieldSet;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) throws ParseException {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.selector = new DocumentSelector(parameters.getDocumentSelection());
this.fieldSet = new FieldSetRepo().parse(access.getDocumentTypeManager(), parameters.fieldSet());
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(Comparator.comparing(DocumentId::toString));
this.outstanding.putAll(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty()
&& control.isDone();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
}
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
public void destroy() {
abort();
}
} |
Will use a concurrent list. | public void testFeedingAndVisiting() throws InterruptedException, ParseException {
DocumentType musicType = access().getDocumentTypeManager().getDocumentType("music");
Document doc1 = new Document(musicType, "id:ns:music::1"); doc1.setFieldValue("artist", "one");
Document doc2 = new Document(musicType, "id:ns:music::2"); doc2.setFieldValue("artist", "two");
Document doc3 = new Document(musicType, "id:ns:music::3");
VisitorParameters parameters = new VisitorParameters("music.artist");
parameters.setFieldSet("music:artist");
VisitorControlHandler control = new VisitorControlHandler();
parameters.setControlHandler(control);
List<Document> received = new ArrayList<>();
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
received.add(doc);
}
@Override public void onRemove(DocumentId id) {
throw new IllegalStateException("Not supposed to get here");
}
});
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(List.of(),
received);
SyncSession out = access.createSyncSession(new SyncParameters.Builder().build());
out.put(new DocumentPut(doc1));
out.put(new DocumentPut(doc2));
out.put(new DocumentPut(doc3));
assertEquals(Map.of(doc1.getId(), doc1,
doc2.getId(), doc2,
doc3.getId(), doc3),
access.documents);
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(List.of(doc1, doc2),
received);
out.remove(new DocumentRemove(doc2.getId()));
out.update(new DocumentUpdate(musicType, doc3.getId()).addFieldUpdate(FieldUpdate.createAssign(musicType.getField("artist"),
new StringFieldValue("three"))));
assertEquals(Map.of(doc1.getId(), doc1,
doc3.getId(), doc3),
access.documents);
assertEquals("three",
((StringFieldValue) doc3.getFieldValue("artist")).getString());
parameters.setFieldSet("[id]");
received.clear();
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(List.of(new Document(musicType, doc1.getId()), new Document(musicType, doc3.getId())),
received);
received.clear();
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
if (doc3.getId().equals(doc.getId()))
throw new RuntimeException("SEGFAULT");
received.add(doc);
}
@Override public void onRemove(DocumentId id) {
throw new IllegalStateException("Not supposed to get here");
}
});
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.FAILURE,
control.getResult().getCode());
assertEquals("SEGFAULT",
control.getResult().getMessage());
assertEquals(List.of(new Document(musicType, doc1.getId())),
received);
received.clear();
CountDownLatch visitLatch = new CountDownLatch(1);
CountDownLatch abortLatch = new CountDownLatch(1);
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
received.add(doc);
abortLatch.countDown();
try {
visitLatch.await();
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override public void onRemove(DocumentId id) { throw new IllegalStateException("Not supposed to get here"); }
});
VisitorSession visit = access.createVisitorSession(parameters);
abortLatch.await();
control.abort();
visitLatch.countDown();
visit.waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.ABORTED,
control.getResult().getCode());
assertEquals(List.of(new Document(musicType, doc1.getId())),
received);
} | } | public void testFeedingAndVisiting() throws InterruptedException, ParseException {
DocumentType musicType = access().getDocumentTypeManager().getDocumentType("music");
Document doc1 = new Document(musicType, "id:ns:music::1"); doc1.setFieldValue("artist", "one");
Document doc2 = new Document(musicType, "id:ns:music::2"); doc2.setFieldValue("artist", "two");
Document doc3 = new Document(musicType, "id:ns:music::3");
VisitorParameters parameters = new VisitorParameters("music.artist");
parameters.setFieldSet("music:artist");
VisitorControlHandler control = new VisitorControlHandler();
parameters.setControlHandler(control);
Set<Document> received = new ConcurrentSkipListSet<>();
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
received.add(doc);
}
@Override public void onRemove(DocumentId id) {
throw new IllegalStateException("Not supposed to get here");
}
});
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(Set.of(),
received);
SyncSession out = access.createSyncSession(new SyncParameters.Builder().build());
out.put(new DocumentPut(doc1));
out.put(new DocumentPut(doc2));
out.put(new DocumentPut(doc3));
assertEquals(Map.of(doc1.getId(), doc1,
doc2.getId(), doc2,
doc3.getId(), doc3),
access.documents);
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(Set.of(doc1, doc2),
received);
out.remove(new DocumentRemove(doc2.getId()));
out.update(new DocumentUpdate(musicType, doc3.getId()).addFieldUpdate(FieldUpdate.createAssign(musicType.getField("artist"),
new StringFieldValue("three"))));
assertEquals(Map.of(doc1.getId(), doc1,
doc3.getId(), doc3),
access.documents);
assertEquals("three",
((StringFieldValue) doc3.getFieldValue("artist")).getString());
parameters.setFieldSet("[id]");
received.clear();
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(Set.of(new Document(musicType, doc1.getId()), new Document(musicType, doc3.getId())),
received);
received.clear();
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
if (doc3.getId().equals(doc.getId()))
throw new RuntimeException("SEGFAULT");
received.add(doc);
}
@Override public void onRemove(DocumentId id) {
throw new IllegalStateException("Not supposed to get here");
}
});
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.FAILURE,
control.getResult().getCode());
assertEquals("SEGFAULT",
control.getResult().getMessage());
assertEquals(Set.of(new Document(musicType, doc1.getId())),
received);
received.clear();
CountDownLatch visitLatch = new CountDownLatch(1);
CountDownLatch abortLatch = new CountDownLatch(1);
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
received.add(doc);
abortLatch.countDown();
try {
visitLatch.await();
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override public void onRemove(DocumentId id) { throw new IllegalStateException("Not supposed to get here"); }
});
VisitorSession visit = access.createVisitorSession(parameters);
abortLatch.await();
control.abort();
visitLatch.countDown();
visit.waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.ABORTED,
control.getResult().getCode());
assertEquals(Set.of(new Document(musicType, doc1.getId())),
received);
} | class LocalDocumentApiTestCase extends AbstractDocumentApiTestCase {
protected LocalDocumentAccess access;
@Override
protected DocumentAccess access() {
return access;
}
@Before
public void setUp() {
DocumentAccessParams params = new DocumentAccessParams();
params.setDocumentManagerConfigId("file:src/test/cfg/documentmanager.cfg");
access = new LocalDocumentAccess(params);
}
@After
public void shutdownAccess() {
access.shutdown();
}
@Test
public void testNoExceptionFromAsync() {
AsyncSession session = access.createAsyncSession(new AsyncParameters());
DocumentType type = access.getDocumentTypeManager().getDocumentType("music");
DocumentUpdate docUp = new DocumentUpdate(type, new DocumentId("id:ns:music::2"));
Result result = session.update(docUp);
assertTrue(result.isSuccess());
Response response = session.getNext();
assertEquals(result.getRequestId(), response.getRequestId());
assertFalse(response.isSuccess());
session.destroy();
}
@Test
public void testAsyncFetch() {
AsyncSession session = access.createAsyncSession(new AsyncParameters());
List<DocumentId> ids = new ArrayList<>();
ids.add(new DocumentId("id:music:music::1"));
ids.add(new DocumentId("id:music:music::2"));
ids.add(new DocumentId("id:music:music::3"));
for (DocumentId id : ids)
session.put(new Document(access.getDocumentTypeManager().getDocumentType("music"), id));
int timeout = 100;
long startTime = System.currentTimeMillis();
Set<Long> outstandingRequests = new HashSet<>();
for (DocumentId id : ids) {
Result result = session.get(id);
if ( ! result.isSuccess())
throw new IllegalStateException("Failed requesting document " + id, result.getError().getCause());
outstandingRequests.add(result.getRequestId());
}
List<Document> documents = new ArrayList<>();
try {
while ( ! outstandingRequests.isEmpty()) {
int timeSinceStart = (int)(System.currentTimeMillis() - startTime);
Response response = session.getNext(timeout - timeSinceStart);
if (response == null)
throw new RuntimeException("Timed out waiting for documents");
if ( ! outstandingRequests.contains(response.getRequestId())) continue;
if (response.isSuccess())
documents.add(((DocumentResponse)response).getDocument());
outstandingRequests.remove(response.getRequestId());
}
}
catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for documents", e);
}
assertEquals(3, documents.size());
for (Document document : documents)
assertNotNull(document);
}
@Test
} | class LocalDocumentApiTestCase extends AbstractDocumentApiTestCase {
protected LocalDocumentAccess access;
@Override
protected DocumentAccess access() {
return access;
}
@Before
public void setUp() {
DocumentAccessParams params = new DocumentAccessParams();
params.setDocumentManagerConfigId("file:src/test/cfg/documentmanager.cfg");
access = new LocalDocumentAccess(params);
}
@After
public void shutdownAccess() {
access.shutdown();
}
@Test
public void testNoExceptionFromAsync() {
AsyncSession session = access.createAsyncSession(new AsyncParameters());
DocumentType type = access.getDocumentTypeManager().getDocumentType("music");
DocumentUpdate docUp = new DocumentUpdate(type, new DocumentId("id:ns:music::2"));
Result result = session.update(docUp);
assertTrue(result.isSuccess());
Response response = session.getNext();
assertEquals(result.getRequestId(), response.getRequestId());
assertFalse(response.isSuccess());
session.destroy();
}
@Test
public void testAsyncFetch() {
AsyncSession session = access.createAsyncSession(new AsyncParameters());
List<DocumentId> ids = new ArrayList<>();
ids.add(new DocumentId("id:music:music::1"));
ids.add(new DocumentId("id:music:music::2"));
ids.add(new DocumentId("id:music:music::3"));
for (DocumentId id : ids)
session.put(new Document(access.getDocumentTypeManager().getDocumentType("music"), id));
int timeout = 100;
long startTime = System.currentTimeMillis();
Set<Long> outstandingRequests = new HashSet<>();
for (DocumentId id : ids) {
Result result = session.get(id);
if ( ! result.isSuccess())
throw new IllegalStateException("Failed requesting document " + id, result.getError().getCause());
outstandingRequests.add(result.getRequestId());
}
List<Document> documents = new ArrayList<>();
try {
while ( ! outstandingRequests.isEmpty()) {
int timeSinceStart = (int)(System.currentTimeMillis() - startTime);
Response response = session.getNext(timeout - timeSinceStart);
if (response == null)
throw new RuntimeException("Timed out waiting for documents");
if ( ! outstandingRequests.contains(response.getRequestId())) continue;
if (response.isSuccess())
documents.add(((DocumentResponse)response).getDocument());
outstandingRequests.remove(response.getRequestId());
}
}
catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for documents", e);
}
assertEquals(3, documents.size());
for (Document document : documents)
assertNotNull(document);
}
@Test
} |
Well, that would have to be a set, then. | public void testFeedingAndVisiting() throws InterruptedException, ParseException {
DocumentType musicType = access().getDocumentTypeManager().getDocumentType("music");
Document doc1 = new Document(musicType, "id:ns:music::1"); doc1.setFieldValue("artist", "one");
Document doc2 = new Document(musicType, "id:ns:music::2"); doc2.setFieldValue("artist", "two");
Document doc3 = new Document(musicType, "id:ns:music::3");
VisitorParameters parameters = new VisitorParameters("music.artist");
parameters.setFieldSet("music:artist");
VisitorControlHandler control = new VisitorControlHandler();
parameters.setControlHandler(control);
List<Document> received = new ArrayList<>();
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
received.add(doc);
}
@Override public void onRemove(DocumentId id) {
throw new IllegalStateException("Not supposed to get here");
}
});
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(List.of(),
received);
SyncSession out = access.createSyncSession(new SyncParameters.Builder().build());
out.put(new DocumentPut(doc1));
out.put(new DocumentPut(doc2));
out.put(new DocumentPut(doc3));
assertEquals(Map.of(doc1.getId(), doc1,
doc2.getId(), doc2,
doc3.getId(), doc3),
access.documents);
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(List.of(doc1, doc2),
received);
out.remove(new DocumentRemove(doc2.getId()));
out.update(new DocumentUpdate(musicType, doc3.getId()).addFieldUpdate(FieldUpdate.createAssign(musicType.getField("artist"),
new StringFieldValue("three"))));
assertEquals(Map.of(doc1.getId(), doc1,
doc3.getId(), doc3),
access.documents);
assertEquals("three",
((StringFieldValue) doc3.getFieldValue("artist")).getString());
parameters.setFieldSet("[id]");
received.clear();
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(List.of(new Document(musicType, doc1.getId()), new Document(musicType, doc3.getId())),
received);
received.clear();
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
if (doc3.getId().equals(doc.getId()))
throw new RuntimeException("SEGFAULT");
received.add(doc);
}
@Override public void onRemove(DocumentId id) {
throw new IllegalStateException("Not supposed to get here");
}
});
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.FAILURE,
control.getResult().getCode());
assertEquals("SEGFAULT",
control.getResult().getMessage());
assertEquals(List.of(new Document(musicType, doc1.getId())),
received);
received.clear();
CountDownLatch visitLatch = new CountDownLatch(1);
CountDownLatch abortLatch = new CountDownLatch(1);
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
received.add(doc);
abortLatch.countDown();
try {
visitLatch.await();
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override public void onRemove(DocumentId id) { throw new IllegalStateException("Not supposed to get here"); }
});
VisitorSession visit = access.createVisitorSession(parameters);
abortLatch.await();
control.abort();
visitLatch.countDown();
visit.waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.ABORTED,
control.getResult().getCode());
assertEquals(List.of(new Document(musicType, doc1.getId())),
received);
} | } | public void testFeedingAndVisiting() throws InterruptedException, ParseException {
DocumentType musicType = access().getDocumentTypeManager().getDocumentType("music");
Document doc1 = new Document(musicType, "id:ns:music::1"); doc1.setFieldValue("artist", "one");
Document doc2 = new Document(musicType, "id:ns:music::2"); doc2.setFieldValue("artist", "two");
Document doc3 = new Document(musicType, "id:ns:music::3");
VisitorParameters parameters = new VisitorParameters("music.artist");
parameters.setFieldSet("music:artist");
VisitorControlHandler control = new VisitorControlHandler();
parameters.setControlHandler(control);
Set<Document> received = new ConcurrentSkipListSet<>();
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
received.add(doc);
}
@Override public void onRemove(DocumentId id) {
throw new IllegalStateException("Not supposed to get here");
}
});
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(Set.of(),
received);
SyncSession out = access.createSyncSession(new SyncParameters.Builder().build());
out.put(new DocumentPut(doc1));
out.put(new DocumentPut(doc2));
out.put(new DocumentPut(doc3));
assertEquals(Map.of(doc1.getId(), doc1,
doc2.getId(), doc2,
doc3.getId(), doc3),
access.documents);
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(Set.of(doc1, doc2),
received);
out.remove(new DocumentRemove(doc2.getId()));
out.update(new DocumentUpdate(musicType, doc3.getId()).addFieldUpdate(FieldUpdate.createAssign(musicType.getField("artist"),
new StringFieldValue("three"))));
assertEquals(Map.of(doc1.getId(), doc1,
doc3.getId(), doc3),
access.documents);
assertEquals("three",
((StringFieldValue) doc3.getFieldValue("artist")).getString());
parameters.setFieldSet("[id]");
received.clear();
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.SUCCESS,
control.getResult().getCode());
assertEquals(Set.of(new Document(musicType, doc1.getId()), new Document(musicType, doc3.getId())),
received);
received.clear();
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
if (doc3.getId().equals(doc.getId()))
throw new RuntimeException("SEGFAULT");
received.add(doc);
}
@Override public void onRemove(DocumentId id) {
throw new IllegalStateException("Not supposed to get here");
}
});
access.createVisitorSession(parameters).waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.FAILURE,
control.getResult().getCode());
assertEquals("SEGFAULT",
control.getResult().getMessage());
assertEquals(Set.of(new Document(musicType, doc1.getId())),
received);
received.clear();
CountDownLatch visitLatch = new CountDownLatch(1);
CountDownLatch abortLatch = new CountDownLatch(1);
parameters.setLocalDataHandler(new DumpVisitorDataHandler() {
@Override public void onDocument(Document doc, long timeStamp) {
received.add(doc);
abortLatch.countDown();
try {
visitLatch.await();
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override public void onRemove(DocumentId id) { throw new IllegalStateException("Not supposed to get here"); }
});
VisitorSession visit = access.createVisitorSession(parameters);
abortLatch.await();
control.abort();
visitLatch.countDown();
visit.waitUntilDone(0);
assertSame(VisitorControlHandler.CompletionCode.ABORTED,
control.getResult().getCode());
assertEquals(Set.of(new Document(musicType, doc1.getId())),
received);
} | class LocalDocumentApiTestCase extends AbstractDocumentApiTestCase {
protected LocalDocumentAccess access;
@Override
protected DocumentAccess access() {
return access;
}
@Before
public void setUp() {
DocumentAccessParams params = new DocumentAccessParams();
params.setDocumentManagerConfigId("file:src/test/cfg/documentmanager.cfg");
access = new LocalDocumentAccess(params);
}
@After
public void shutdownAccess() {
access.shutdown();
}
@Test
public void testNoExceptionFromAsync() {
AsyncSession session = access.createAsyncSession(new AsyncParameters());
DocumentType type = access.getDocumentTypeManager().getDocumentType("music");
DocumentUpdate docUp = new DocumentUpdate(type, new DocumentId("id:ns:music::2"));
Result result = session.update(docUp);
assertTrue(result.isSuccess());
Response response = session.getNext();
assertEquals(result.getRequestId(), response.getRequestId());
assertFalse(response.isSuccess());
session.destroy();
}
@Test
public void testAsyncFetch() {
AsyncSession session = access.createAsyncSession(new AsyncParameters());
List<DocumentId> ids = new ArrayList<>();
ids.add(new DocumentId("id:music:music::1"));
ids.add(new DocumentId("id:music:music::2"));
ids.add(new DocumentId("id:music:music::3"));
for (DocumentId id : ids)
session.put(new Document(access.getDocumentTypeManager().getDocumentType("music"), id));
int timeout = 100;
long startTime = System.currentTimeMillis();
Set<Long> outstandingRequests = new HashSet<>();
for (DocumentId id : ids) {
Result result = session.get(id);
if ( ! result.isSuccess())
throw new IllegalStateException("Failed requesting document " + id, result.getError().getCause());
outstandingRequests.add(result.getRequestId());
}
List<Document> documents = new ArrayList<>();
try {
while ( ! outstandingRequests.isEmpty()) {
int timeSinceStart = (int)(System.currentTimeMillis() - startTime);
Response response = session.getNext(timeout - timeSinceStart);
if (response == null)
throw new RuntimeException("Timed out waiting for documents");
if ( ! outstandingRequests.contains(response.getRequestId())) continue;
if (response.isSuccess())
documents.add(((DocumentResponse)response).getDocument());
outstandingRequests.remove(response.getRequestId());
}
}
catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for documents", e);
}
assertEquals(3, documents.size());
for (Document document : documents)
assertNotNull(document);
}
@Test
} | class LocalDocumentApiTestCase extends AbstractDocumentApiTestCase {
protected LocalDocumentAccess access;
@Override
protected DocumentAccess access() {
return access;
}
@Before
public void setUp() {
DocumentAccessParams params = new DocumentAccessParams();
params.setDocumentManagerConfigId("file:src/test/cfg/documentmanager.cfg");
access = new LocalDocumentAccess(params);
}
@After
public void shutdownAccess() {
access.shutdown();
}
@Test
public void testNoExceptionFromAsync() {
AsyncSession session = access.createAsyncSession(new AsyncParameters());
DocumentType type = access.getDocumentTypeManager().getDocumentType("music");
DocumentUpdate docUp = new DocumentUpdate(type, new DocumentId("id:ns:music::2"));
Result result = session.update(docUp);
assertTrue(result.isSuccess());
Response response = session.getNext();
assertEquals(result.getRequestId(), response.getRequestId());
assertFalse(response.isSuccess());
session.destroy();
}
@Test
public void testAsyncFetch() {
AsyncSession session = access.createAsyncSession(new AsyncParameters());
List<DocumentId> ids = new ArrayList<>();
ids.add(new DocumentId("id:music:music::1"));
ids.add(new DocumentId("id:music:music::2"));
ids.add(new DocumentId("id:music:music::3"));
for (DocumentId id : ids)
session.put(new Document(access.getDocumentTypeManager().getDocumentType("music"), id));
int timeout = 100;
long startTime = System.currentTimeMillis();
Set<Long> outstandingRequests = new HashSet<>();
for (DocumentId id : ids) {
Result result = session.get(id);
if ( ! result.isSuccess())
throw new IllegalStateException("Failed requesting document " + id, result.getError().getCause());
outstandingRequests.add(result.getRequestId());
}
List<Document> documents = new ArrayList<>();
try {
while ( ! outstandingRequests.isEmpty()) {
int timeSinceStart = (int)(System.currentTimeMillis() - startTime);
Response response = session.getNext(timeout - timeSinceStart);
if (response == null)
throw new RuntimeException("Timed out waiting for documents");
if ( ! outstandingRequests.contains(response.getRequestId())) continue;
if (response.isSuccess())
documents.add(((DocumentResponse)response).getDocument());
outstandingRequests.remove(response.getRequestId());
}
}
catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for documents", e);
}
assertEquals(3, documents.size());
for (Document document : documents)
assertNotNull(document);
}
@Test
} |
Put a guard on state being `RUNNING` in the iteration. | public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
} | } | public void ack(AckToken token) {
outstanding.remove((DocumentId) token.ackObject);
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final DocumentSelector selector;
private final FieldSet fieldSet;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) throws ParseException {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.selector = new DocumentSelector(parameters.getDocumentSelection());
this.fieldSet = new FieldSetRepo().parse(access.getDocumentTypeManager(), parameters.fieldSet());
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(Comparator.comparing(DocumentId::toString));
this.outstanding.putAll(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
if (selector.accepts(new DocumentPut(document)) != Result.TRUE)
return;
Document copy = new Document(document.getDataType(), document.getId());
for (Field field : document.getDataType().getFields())
if (fieldSet.contains(field))
copy.setFieldValue(field, document.getFieldValue(field));
data.onMessage(new PutDocumentMessage(new DocumentPut(copy)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty()
&& control.isDone();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
public void destroy() {
abort();
}
} | class LocalVisitorSession implements VisitorSession {
private enum State { RUNNING, FAILURE, ABORTED, SUCCESS }
private final VisitorDataHandler data;
private final VisitorControlHandler control;
private final Map<DocumentId, Document> outstanding;
private final DocumentSelector selector;
private final FieldSet fieldSet;
private final AtomicReference<State> state;
public LocalVisitorSession(LocalDocumentAccess access, VisitorParameters parameters) throws ParseException {
if (parameters.getResumeToken() != null)
throw new UnsupportedOperationException("Continuation via progress tokens is not supported");
if (parameters.getRemoteDataHandler() != null)
throw new UnsupportedOperationException("Remote data handlers are not supported");
this.selector = new DocumentSelector(parameters.getDocumentSelection());
this.fieldSet = new FieldSetRepo().parse(access.getDocumentTypeManager(), parameters.fieldSet());
this.data = parameters.getLocalDataHandler() == null ? new VisitorDataQueue() : parameters.getLocalDataHandler();
this.data.reset();
this.data.setSession(this);
this.control = parameters.getControlHandler() == null ? new VisitorControlHandler() : parameters.getControlHandler();
this.control.reset();
this.control.setSession(this);
this.outstanding = new ConcurrentSkipListMap<>(Comparator.comparing(DocumentId::toString));
this.outstanding.putAll(access.documents);
this.state = new AtomicReference<>(State.RUNNING);
start();
}
void start() {
new Thread(() -> {
try {
outstanding.forEach((id, document) -> {
if (state.get() != State.RUNNING)
return;
if (selector.accepts(new DocumentPut(document)) != Result.TRUE)
return;
Document copy = new Document(document.getDataType(), document.getId());
new FieldSetRepo().copyFields(document, copy, fieldSet);
data.onMessage(new PutDocumentMessage(new DocumentPut(copy)),
new AckToken(id));
});
state.updateAndGet(current -> {
switch (current) {
case RUNNING:
control.onDone(VisitorControlHandler.CompletionCode.SUCCESS, "Success");
return State.SUCCESS;
case ABORTED:
control.onDone(VisitorControlHandler.CompletionCode.ABORTED, "Aborted by user");
return State.ABORTED;
default:
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, "Unexpected state '" + current + "'");;
return State.FAILURE;
}
});
}
catch (Exception e) {
state.set(State.FAILURE);
outstanding.clear();
control.onDone(VisitorControlHandler.CompletionCode.FAILURE, Exceptions.toMessageString(e));
}
finally {
data.onDone();
}
}).start();
}
@Override
public boolean isDone() {
return outstanding.isEmpty()
&& control.isDone();
}
@Override
public ProgressToken getProgress() {
throw new UnsupportedOperationException("Progress tokens are not supported");
}
@Override
public Trace getTrace() {
throw new UnsupportedOperationException("Traces are not supported");
}
@Override
public boolean waitUntilDone(long timeoutMs) throws InterruptedException {
return control.waitUntilDone(timeoutMs);
}
@Override
@Override
public void abort() {
state.updateAndGet(current -> current == State.RUNNING ? State.ABORTED : current);
outstanding.clear();
}
@Override
public VisitorResponse getNext() {
return data.getNext();
}
@Override
public VisitorResponse getNext(int timeoutMilliseconds) throws InterruptedException {
return data.getNext(timeoutMilliseconds);
}
@Override
public void destroy() {
abort();
}
} |
```suggestion ``` | private List<List<Path>> getMatchingFiles(Instant from, Instant to) {
List<Path> paths = new ArrayList<>();
try {
Files.walkFileTree(logDirectory, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (logFilePattern.matcher(file.getFileName().toString()).matches())
paths.add(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return FileVisitResult.CONTINUE;
}
});
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
var logsByTimestamp = paths.stream()
.collect(Collectors.groupingBy(this::extractTimestamp,
TreeMap::new,
Collectors.toList()));
System.err.println(logsByTimestamp);
List<List<Path>> sorted = new ArrayList<>();
for (var entry : logsByTimestamp.entrySet()) {
if (entry.getKey().isAfter(from))
sorted.add(entry.getValue());
if (entry.getKey().isAfter(to))
break;
}
return sorted;
} | System.err.println(logsByTimestamp); | Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
return FileVisitResult.CONTINUE;
} | class LogReader {
static final Pattern logArchivePathPattern = Pattern.compile("(\\d{4})/(\\d{2})/(\\d{2})/(\\d{2})-\\d(.gz)?");
static final Pattern vespaLogPathPattern = Pattern.compile("vespa\\.log(?:-(\\d{4})-(\\d{2})-(\\d{2})\\.(\\d{2})-(\\d{2})-(\\d{2})(?:.gz)?)?");
private final Path logDirectory;
private final Pattern logFilePattern;
LogReader(String logDirectory, String logFilePattern) {
this(Paths.get(Defaults.getDefaults().underVespaHome(logDirectory)), Pattern.compile(logFilePattern));
}
LogReader(Path logDirectory, Pattern logFilePattern) {
this.logDirectory = logDirectory;
this.logFilePattern = logFilePattern;
}
void writeLogs(OutputStream outputStream, Instant from, Instant to) {
try {
List<List<Path>> logs = getMatchingFiles(from, to);
for (int i = 0; i < logs.size(); i++) {
for (Path log : logs.get(i)) {
boolean zipped = log.toString().endsWith(".gz");
try (InputStream in = Files.newInputStream(log)) {
InputStream inProxy;
if (i == 0 || i == logs.size() - 1) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(zipped ? new GZIPInputStream(in) : in, UTF_8));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zipped ? new GZIPOutputStream(buffer) : buffer, UTF_8))) {
for (String line; (line = reader.readLine()) != null; ) {
String[] parts = line.split("\t");
if (parts.length != 7)
continue;
Instant at = Instant.EPOCH.plus((long) (Double.parseDouble(parts[0]) * 1_000_000), ChronoUnit.MICROS);
if (at.isAfter(from) && !at.isAfter(to)) {
writer.write(line);
writer.newLine();
}
}
}
inProxy = new ByteArrayInputStream(buffer.toByteArray());
}
else
inProxy = in;
if ( ! zipped) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (OutputStream outProxy = new GZIPOutputStream(buffer)) {
inProxy.transferTo(outProxy);
}
inProxy = new ByteArrayInputStream(buffer.toByteArray());
}
inProxy.transferTo(outputStream);
}
}
}
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** Returns log files which may have relevant entries, grouped and sorted by {@link
private List<List<Path>> getMatchingFiles(Instant from, Instant to) {
List<Path> paths = new ArrayList<>();
try {
Files.walkFileTree(logDirectory, new SimpleFileVisitor<>() {
@
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (logFilePattern.matcher(file.getFileName().toString()).matches())
paths.add(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return FileVisitResult.CONTINUE;
}
});
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
var logsByTimestamp = paths.stream()
.collect(Collectors.groupingBy(this::extractTimestamp,
TreeMap::new,
Collectors.toList()));
System.err.println(logsByTimestamp);
List<List<Path>> sorted = new ArrayList<>();
for (var entry : logsByTimestamp.entrySet()) {
if (entry.getKey().isAfter(from))
sorted.add(entry.getValue());
if (entry.getKey().isAfter(to))
break;
}
return sorted;
}
/** Extracts a timestamp after all entries in the log file with the given path. */
Instant extractTimestamp(Path path) {
String relativePath = logDirectory.relativize(path).toString();
Matcher matcher = logArchivePathPattern.matcher(relativePath);
if (matcher.matches()) {
return ZonedDateTime.of(Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3)),
Integer.parseInt(matcher.group(4)) + 1,
0,
0,
0,
ZoneId.of("UTC"))
.toInstant();
}
matcher = vespaLogPathPattern.matcher(relativePath);
if (matcher.matches()) {
if (matcher.group(1) == null)
return Instant.MAX;
return ZonedDateTime.of(Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3)),
Integer.parseInt(matcher.group(4)),
Integer.parseInt(matcher.group(5)),
Integer.parseInt(matcher.group(6)) + 1,
0,
ZoneId.of("UTC"))
.toInstant();
}
throw new IllegalArgumentException("Unrecognized file pattern for file at '" + path + "'");
}
} | class LogReader {
static final Pattern logArchivePathPattern = Pattern.compile("(\\d{4})/(\\d{2})/(\\d{2})/(\\d{2})-\\d+(.gz)?");
static final Pattern vespaLogPathPattern = Pattern.compile("vespa\\.log(?:-(\\d{4})-(\\d{2})-(\\d{2})\\.(\\d{2})-(\\d{2})-(\\d{2})(?:.gz)?)?");
private final Path logDirectory;
private final Pattern logFilePattern;
LogReader(String logDirectory, String logFilePattern) {
this(Paths.get(Defaults.getDefaults().underVespaHome(logDirectory)), Pattern.compile(logFilePattern));
}
LogReader(Path logDirectory, Pattern logFilePattern) {
this.logDirectory = logDirectory;
this.logFilePattern = logFilePattern;
}
void writeLogs(OutputStream outputStream, Instant from, Instant to) {
try {
List<List<Path>> logs = getMatchingFiles(from, to);
for (int i = 0; i < logs.size(); i++) {
for (Path log : logs.get(i)) {
boolean zipped = log.toString().endsWith(".gz");
try (InputStream in = Files.newInputStream(log)) {
InputStream inProxy;
if (i == 0 || i == logs.size() - 1) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(zipped ? new GZIPInputStream(in) : in, UTF_8));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zipped ? new GZIPOutputStream(buffer) : buffer, UTF_8))) {
for (String line; (line = reader.readLine()) != null; ) {
String[] parts = line.split("\t");
if (parts.length != 7)
continue;
Instant at = Instant.EPOCH.plus((long) (Double.parseDouble(parts[0]) * 1_000_000), ChronoUnit.MICROS);
if (at.isAfter(from) && !at.isAfter(to)) {
writer.write(line);
writer.newLine();
}
}
}
inProxy = new ByteArrayInputStream(buffer.toByteArray());
}
else
inProxy = in;
if ( ! zipped) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (OutputStream outProxy = new GZIPOutputStream(buffer)) {
inProxy.transferTo(outProxy);
}
inProxy = new ByteArrayInputStream(buffer.toByteArray());
}
inProxy.transferTo(outputStream);
}
}
}
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** Returns log files which may have relevant entries, grouped and sorted by {@link
private List<List<Path>> getMatchingFiles(Instant from, Instant to) {
List<Path> paths = new ArrayList<>();
try {
Files.walkFileTree(logDirectory, new SimpleFileVisitor<>() {
@
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (logFilePattern.matcher(file.getFileName().toString()).matches())
paths.add(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return FileVisitResult.CONTINUE;
}
});
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
var logsByTimestamp = paths.stream()
.collect(Collectors.groupingBy(this::extractTimestamp,
TreeMap::new,
Collectors.toList()));
List<List<Path>> sorted = new ArrayList<>();
for (var entry : logsByTimestamp.entrySet()) {
if (entry.getKey().isAfter(from))
sorted.add(entry.getValue());
if (entry.getKey().isAfter(to))
break;
}
return sorted;
}
/** Extracts a timestamp after all entries in the log file with the given path. */
Instant extractTimestamp(Path path) {
String relativePath = logDirectory.relativize(path).toString();
Matcher matcher = logArchivePathPattern.matcher(relativePath);
if (matcher.matches()) {
return ZonedDateTime.of(Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3)),
Integer.parseInt(matcher.group(4)) + 1,
0,
0,
0,
ZoneId.of("UTC"))
.toInstant();
}
matcher = vespaLogPathPattern.matcher(relativePath);
if (matcher.matches()) {
if (matcher.group(1) == null)
return Instant.MAX;
return ZonedDateTime.of(Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3)),
Integer.parseInt(matcher.group(4)),
Integer.parseInt(matcher.group(5)),
Integer.parseInt(matcher.group(6)) + 1,
0,
ZoneId.of("UTC"))
.toInstant();
}
throw new IllegalArgumentException("Unrecognized file pattern for file at '" + path + "'");
}
} |
```suggestion Integer.parseInt(matcher.group(6)) + 1, // timestamp is that of the last entry, truncated to second accuracy ``` | Instant extractTimestamp(Path path) {
String relativePath = logDirectory.relativize(path).toString();
Matcher matcher = logArchivePathPattern.matcher(relativePath);
if (matcher.matches()) {
return ZonedDateTime.of(Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3)),
Integer.parseInt(matcher.group(4)) + 1,
0,
0,
0,
ZoneId.of("UTC"))
.toInstant();
}
matcher = vespaLogPathPattern.matcher(relativePath);
if (matcher.matches()) {
if (matcher.group(1) == null)
return Instant.MAX;
return ZonedDateTime.of(Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3)),
Integer.parseInt(matcher.group(4)),
Integer.parseInt(matcher.group(5)),
Integer.parseInt(matcher.group(6)) + 1,
0,
ZoneId.of("UTC"))
.toInstant();
}
throw new IllegalArgumentException("Unrecognized file pattern for file at '" + path + "'");
} | Integer.parseInt(matcher.group(6)) + 1, | Instant extractTimestamp(Path path) {
String relativePath = logDirectory.relativize(path).toString();
Matcher matcher = logArchivePathPattern.matcher(relativePath);
if (matcher.matches()) {
return ZonedDateTime.of(Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3)),
Integer.parseInt(matcher.group(4)) + 1,
0,
0,
0,
ZoneId.of("UTC"))
.toInstant();
}
matcher = vespaLogPathPattern.matcher(relativePath);
if (matcher.matches()) {
if (matcher.group(1) == null)
return Instant.MAX;
return ZonedDateTime.of(Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3)),
Integer.parseInt(matcher.group(4)),
Integer.parseInt(matcher.group(5)),
Integer.parseInt(matcher.group(6)) + 1,
0,
ZoneId.of("UTC"))
.toInstant();
}
throw new IllegalArgumentException("Unrecognized file pattern for file at '" + path + "'");
} | class LogReader {
static final Pattern logArchivePathPattern = Pattern.compile("(\\d{4})/(\\d{2})/(\\d{2})/(\\d{2})-\\d(.gz)?");
static final Pattern vespaLogPathPattern = Pattern.compile("vespa\\.log(?:-(\\d{4})-(\\d{2})-(\\d{2})\\.(\\d{2})-(\\d{2})-(\\d{2})(?:.gz)?)?");
private final Path logDirectory;
private final Pattern logFilePattern;
LogReader(String logDirectory, String logFilePattern) {
this(Paths.get(Defaults.getDefaults().underVespaHome(logDirectory)), Pattern.compile(logFilePattern));
}
LogReader(Path logDirectory, Pattern logFilePattern) {
this.logDirectory = logDirectory;
this.logFilePattern = logFilePattern;
}
void writeLogs(OutputStream outputStream, Instant from, Instant to) {
try {
List<List<Path>> logs = getMatchingFiles(from, to);
for (int i = 0; i < logs.size(); i++) {
for (Path log : logs.get(i)) {
boolean zipped = log.toString().endsWith(".gz");
try (InputStream in = Files.newInputStream(log)) {
InputStream inProxy;
if (i == 0 || i == logs.size() - 1) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(zipped ? new GZIPInputStream(in) : in, UTF_8));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zipped ? new GZIPOutputStream(buffer) : buffer, UTF_8))) {
for (String line; (line = reader.readLine()) != null; ) {
String[] parts = line.split("\t");
if (parts.length != 7)
continue;
Instant at = Instant.EPOCH.plus((long) (Double.parseDouble(parts[0]) * 1_000_000), ChronoUnit.MICROS);
if (at.isAfter(from) && !at.isAfter(to)) {
writer.write(line);
writer.newLine();
}
}
}
inProxy = new ByteArrayInputStream(buffer.toByteArray());
}
else
inProxy = in;
if ( ! zipped) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (OutputStream outProxy = new GZIPOutputStream(buffer)) {
inProxy.transferTo(outProxy);
}
inProxy = new ByteArrayInputStream(buffer.toByteArray());
}
inProxy.transferTo(outputStream);
}
}
}
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** Returns log files which may have relevant entries, grouped and sorted by {@link
private List<List<Path>> getMatchingFiles(Instant from, Instant to) {
List<Path> paths = new ArrayList<>();
try {
Files.walkFileTree(logDirectory, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (logFilePattern.matcher(file.getFileName().toString()).matches())
paths.add(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return FileVisitResult.CONTINUE;
}
});
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
var logsByTimestamp = paths.stream()
.collect(Collectors.groupingBy(this::extractTimestamp,
TreeMap::new,
Collectors.toList()));
List<List<Path>> sorted = new ArrayList<>();
for (var entry : logsByTimestamp.entrySet()) {
if (entry.getKey().isAfter(from))
sorted.add(entry.getValue());
if (entry.getKey().isAfter(to))
break;
}
return sorted;
}
/** Extracts a timestamp after all entries in the log file with the given path. */
} | class LogReader {
static final Pattern logArchivePathPattern = Pattern.compile("(\\d{4})/(\\d{2})/(\\d{2})/(\\d{2})-\\d+(.gz)?");
static final Pattern vespaLogPathPattern = Pattern.compile("vespa\\.log(?:-(\\d{4})-(\\d{2})-(\\d{2})\\.(\\d{2})-(\\d{2})-(\\d{2})(?:.gz)?)?");
private final Path logDirectory;
private final Pattern logFilePattern;
LogReader(String logDirectory, String logFilePattern) {
this(Paths.get(Defaults.getDefaults().underVespaHome(logDirectory)), Pattern.compile(logFilePattern));
}
LogReader(Path logDirectory, Pattern logFilePattern) {
this.logDirectory = logDirectory;
this.logFilePattern = logFilePattern;
}
void writeLogs(OutputStream outputStream, Instant from, Instant to) {
try {
List<List<Path>> logs = getMatchingFiles(from, to);
for (int i = 0; i < logs.size(); i++) {
for (Path log : logs.get(i)) {
boolean zipped = log.toString().endsWith(".gz");
try (InputStream in = Files.newInputStream(log)) {
InputStream inProxy;
if (i == 0 || i == logs.size() - 1) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(zipped ? new GZIPInputStream(in) : in, UTF_8));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zipped ? new GZIPOutputStream(buffer) : buffer, UTF_8))) {
for (String line; (line = reader.readLine()) != null; ) {
String[] parts = line.split("\t");
if (parts.length != 7)
continue;
Instant at = Instant.EPOCH.plus((long) (Double.parseDouble(parts[0]) * 1_000_000), ChronoUnit.MICROS);
if (at.isAfter(from) && !at.isAfter(to)) {
writer.write(line);
writer.newLine();
}
}
}
inProxy = new ByteArrayInputStream(buffer.toByteArray());
}
else
inProxy = in;
if ( ! zipped) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (OutputStream outProxy = new GZIPOutputStream(buffer)) {
inProxy.transferTo(outProxy);
}
inProxy = new ByteArrayInputStream(buffer.toByteArray());
}
inProxy.transferTo(outputStream);
}
}
}
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** Returns log files which may have relevant entries, grouped and sorted by {@link
private List<List<Path>> getMatchingFiles(Instant from, Instant to) {
List<Path> paths = new ArrayList<>();
try {
Files.walkFileTree(logDirectory, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (logFilePattern.matcher(file.getFileName().toString()).matches())
paths.add(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return FileVisitResult.CONTINUE;
}
});
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
var logsByTimestamp = paths.stream()
.collect(Collectors.groupingBy(this::extractTimestamp,
TreeMap::new,
Collectors.toList()));
List<List<Path>> sorted = new ArrayList<>();
for (var entry : logsByTimestamp.entrySet()) {
if (entry.getKey().isAfter(from))
sorted.add(entry.getValue());
if (entry.getKey().isAfter(to))
break;
}
return sorted;
}
/** Extracts a timestamp after all entries in the log file with the given path. */
} |
Can this iterator facade be removed too? | public Iterator<Field> fieldIteratorThisTypeOnly() {
return new Iterator<>() {
Iterator<Field> headerIt = headerType.getFields().iterator();
public boolean hasNext() {
return headerIt.hasNext();
}
public Field next() {
return headerIt.next();
}
public void remove() {
if (headerIt != null) {
headerIt.remove();
}
}
};
} | return headerIt.hasNext(); | public Iterator<Field> fieldIteratorThisTypeOnly() {
return headerType.getFields().iterator();
} | class DocumentType extends StructuredDataType {
private static final String ALL = "[all]";
public static final String DOCUMENT = "[document]";
public static final int classId = registerClass(Ids.document + 58, DocumentType.class);
private StructDataType headerType;
private List<DocumentType> inherits = new ArrayList<>(1);
private Map<String, Set<Field>> fieldSets = new HashMap<>();
private final Set<String> importedFieldNames;
/**
* Creates a new document type and registers it with the document type manager.
* This will be created as version 0 of this document type.
* Implicitly registers this with the document type manager.
* The document type id will be generated as a hash from the document type name.
*
* @param name The name of the new document type
*/
public DocumentType(String name) {
this(name, createHeaderStructType(name));
}
/**
* Creates a new document type and registers it with the document type manager.
* Implicitly registers this with the document type manager.
* The document type id will be generated as a hash from the document type name.
*
* @param name The name of the new document type
* @param headerType The type of the header struct
*/
public DocumentType(String name, StructDataType headerType) {
this(name, headerType, Collections.emptySet());
}
/**
* @deprecated
*/
@Deprecated
public DocumentType(String name, StructDataType headerType, StructDataType bodyType) {
this(name, headerType, Collections.emptySet());
}
public DocumentType(String name, StructDataType headerType, Set<String> importedFieldNames) {
super(name);
this.headerType = headerType;
this.importedFieldNames = Collections.unmodifiableSet(importedFieldNames);
}
/**
* @deprecated
*/
@Deprecated
public DocumentType(String name, StructDataType headerType,
StructDataType bodyType, Set<String> importedFieldNames) {
this(name, headerType, importedFieldNames);
}
public DocumentType(String name, Set<String> importedFieldNames) {
this(name, createHeaderStructType(name), importedFieldNames);
}
private static StructDataType createHeaderStructType(String name) {
return new StructDataType(name + ".header");
}
@Override
public DocumentType clone() {
DocumentType type = (DocumentType) super.clone();
type.headerType = headerType.clone();
type.inherits = new ArrayList<>(inherits.size());
type.inherits.addAll(inherits);
return type;
}
@Override
public Document createFieldValue() {
return new Document(this, (DocumentId) null);
}
@Override
public Class getValueClass() {
return Document.class;
}
@Override
public boolean isValueCompatible(FieldValue value) {
if (!(value instanceof Document)) {
return false;
}
Document doc = (Document) value;
if (doc.getDataType().inherits(this)) {
return true;
}
return false;
}
/**
* Provides the Struct describing the fields in the document.
*
* @return a struct describing the document fields.
*/
public StructDataType contentStruct() {
return headerType;
}
/** @deprecated use contentStruct instead */
@Deprecated
public StructDataType getHeaderType() {
return contentStruct();
}
@Deprecated
/** @deprecated use contentStruct instead */
public StructDataType getBodyType() {
return null;
}
@Override
protected void register(DocumentTypeManager manager, List<DataType> seenTypes) {
seenTypes.add(this);
for (DocumentType type : getInheritedTypes()) {
if (!seenTypes.contains(type)) {
type.register(manager, seenTypes);
}
}
StructDataType header = headerType.clone();
header.clearFields();
for (Field field : getAllUniqueFields()) {
header.addField(field);
}
headerType.assign(header);
if (!seenTypes.contains(headerType)) {
headerType.register(manager, seenTypes);
}
manager.registerSingleType(this);
}
/**
* Check if this document type has the given name,
* or inherits from a type with that name.
*/
public boolean isA(String docTypeName) {
if (getName().equalsIgnoreCase(docTypeName)) {
return true;
}
for (DocumentType parent : inherits) {
if (parent.isA(docTypeName)) {
return true;
}
}
return false;
}
/**
* Adds an field that can be used with this document type.
*
* @param field the field to add
*/
public void addField(Field field) {
if (isRegistered()) {
throw new IllegalStateException("You cannot add fields to a document type that is already registered.");
}
headerType.addField(field);
}
public void addFieldSets(Map<String, Collection<String>> fieldSets) {
for (Map.Entry<String, Collection<String>> entry : fieldSets.entrySet()) {
Set<Field> fields = new LinkedHashSet<>(entry.getValue().size());
for (DocumentType parent : inherits) {
Set<Field> parentFieldSet = parent.fieldSet(entry.getKey());
if (parentFieldSet != null) {
fields.addAll(parentFieldSet);
}
}
for (Field orderedField : getAllUniqueFields()) {
if (entry.getValue().contains(orderedField.getName())) {
fields.add(orderedField);
}
}
this.fieldSets.put(entry.getKey(), ImmutableSet.copyOf(fields));
}
if ( ! this.fieldSets.containsKey(ALL)) {
this.fieldSets.put(ALL, getAllUniqueFields());
}
}
/**
* Adds a new field to this document type and returns the new field object
*
* @param name The name of the field to add
* @param type The datatype of the field to add
* @return The field created
* TODO Fix searchdefinition so that exception can be thrown if filed is already registerd.
*/
public Field addField(String name, DataType type) {
if (isRegistered()) {
throw new IllegalStateException("You cannot add fields to a document type that is already registered.");
}
Field field = new Field(name, type);
headerType.addField(field);
return field;
}
/**
* Adds a new header field to this document type and returns the new field object
*
* @param name The name of the field to add
* @param type The datatype of the field to add
* @return The field created
* TODO Fix searchdefinition so that exception can be thrown if filed is already registerd
*/
@Deprecated
public Field addHeaderField(String name, DataType type) {
return addField(name, type);
}
/**
* Adds a document to the inherited document types of this.
* If this type is already directly inherited, nothing is done
*
* @param type An already DocumentType object.
*/
public void inherit(DocumentType type) {
verifyTypeConsistency(type);
if (isRegistered()) {
throw new IllegalStateException("You cannot add inheritance to a document type that is already registered.");
}
if (type == null) {
throw new IllegalArgumentException("The document type cannot be null in inherit()");
}
if (inherits.contains(type)) return;
if (inherits.size() == 1 && inherits.get(0).getDataTypeName().equals(new DataTypeName("document"))) {
inherits.clear();
}
inherits.add(type);
}
/**
* Fail if the subtype changes the type of any equally named field.
*
* @param superType The supertype to verify against
* TODO Add strict type checking no duplicate fields are allowed
*/
private void verifyTypeConsistency(DocumentType superType) {
for (Field f : getAllUniqueFields()) {
Field supField = superType.getField(f.getName());
if (supField != null) {
if (!f.getDataType().equals(supField.getDataType())) {
throw new IllegalArgumentException("Inheritance type mismatch: field \"" + f.getName() +
"\" in datatype \"" + getName() + "\"" +
" must have same datatype as in parent document type \"" + superType.getName() + "\"");
}
}
}
}
/**
* Returns the DocumentNames which are directly inherited by this
* as a read-only collection.
* If this document type does not explicitly inherit anything, the list will
* contain the root type 'Document'
*
* @return a read-only list iterator containing the name Strings of the directly
* inherited document types of this
*/
public Collection<DocumentType> getInheritedTypes() {
return Collections.unmodifiableCollection(inherits);
}
public ListIterator<DataTypeName> inheritedIterator() {
List<DataTypeName> names = new ArrayList<>(inherits.size());
for (DocumentType type : inherits) {
names.add(type.getDataTypeName());
}
return ImmutableList.copyOf(names).listIterator();
}
/**
* Return whether this document type inherits the given document type.
*
* @param superType The documenttype to check if it inherits.
* @return true if it inherits the superType, false if not
*/
public boolean inherits(DocumentType superType) {
if (equals(superType)) return true;
for (DocumentType type : inherits) {
if (type.inherits(superType)) return true;
}
return false;
}
/**
* Gets the field matching a given name.
*
* @param name the name of a field.
* @return returns the matching field, or null if not found.
*/
public Field getField(String name) {
Field field = headerType.getField(name);
if (field == null && !isRegistered()) {
for (DocumentType inheritedType : inherits) {
field = inheritedType.getField(name);
if (field != null) break;
}
}
return field;
}
@Override
public Field getField(int id) {
Field field = headerType.getField(id);
if (field == null && !isRegistered()) {
for (DocumentType inheritedType : inherits) {
field = inheritedType.getField(id);
if (field != null) break;
}
}
return field;
}
/**
* Returns whether this type defines the given field name
*
* @param name The name of the field to check if it has
* @return True if there is a field with the given name.
*/
public boolean hasField(String name) {
return getField(name) != null;
}
public int getFieldCount() {
return headerType.getFieldCount();
}
public Set<String> getImportedFieldNames() {
return importedFieldNames;
}
public boolean hasImportedField(String fieldName) {
return importedFieldNames.contains(fieldName);
}
/**
* Removes an field from the DocumentType.
*
* @param name The name of the field.
* @return The field that was removed or null if it did not exist.
*/
public Field removeField(String name) {
if (isRegistered()) {
throw new IllegalStateException("You cannot remove fields from a document type that is already registered.");
}
Field field = headerType.removeField(name);
if (field == null) {
for (DocumentType inheritedType : inherits) {
field = inheritedType.removeField(name);
if (field != null) break;
}
}
return field;
}
/**
* All fields defined in the document and its parents
* This is for internal use
* Use {@link
* @return All fields defined in the document and its parents
*/
@Override
public Collection<Field> getFields() {
Collection<Field> collection = new LinkedList<>();
for (DocumentType type : inherits) {
collection.addAll(type.getFields());
}
collection.addAll(headerType.getFields());
return ImmutableList.copyOf(collection);
}
private Set<Field> getAllUniqueFields() {
Map<String, Field> map = new LinkedHashMap<>();
for (Field field : getFields()) {
map.put(field.getName(), field);
}
return ImmutableSet.copyOf(map.values());
}
/**
* <p>Returns an ordered set snapshot of all fields of this documenttype,
* <i>except the fields of Document</i>.
* Only the overridden version will be returned for overridden fields.</p>
*
* <p>The fields of a document type has a well-defined order which is
* exhibited in this set:
* - Fields come in the order defined in the document type definition.
* - The fields defined in inherited types come before those in
* the document type itself.
* - When a field in an inherited type is overridden, the value is overridden,
* but not the ordering.
* </p>
*
* @return an unmodifiable snapshot of the fields in this type
*/
public Set<Field> fieldSet() {
return fieldSet(DOCUMENT);
}
/**
* This is identical to {@link | class DocumentType extends StructuredDataType {
private static final String ALL = "[all]";
public static final String DOCUMENT = "[document]";
public static final int classId = registerClass(Ids.document + 58, DocumentType.class);
private StructDataType headerType;
private List<DocumentType> inherits = new ArrayList<>(1);
private Map<String, Set<Field>> fieldSets = new HashMap<>();
private final Set<String> importedFieldNames;
/**
* Creates a new document type and registers it with the document type manager.
* This will be created as version 0 of this document type.
* Implicitly registers this with the document type manager.
* The document type id will be generated as a hash from the document type name.
*
* @param name The name of the new document type
*/
public DocumentType(String name) {
this(name, createHeaderStructType(name));
}
/**
* Creates a new document type and registers it with the document type manager.
* Implicitly registers this with the document type manager.
* The document type id will be generated as a hash from the document type name.
*
* @param name The name of the new document type
* @param headerType The type of the header struct
*/
public DocumentType(String name, StructDataType headerType) {
this(name, headerType, Collections.emptySet());
}
/**
* @deprecated
*/
@Deprecated
public DocumentType(String name, StructDataType headerType, StructDataType bodyType) {
this(name, headerType, Collections.emptySet());
}
public DocumentType(String name, StructDataType headerType, Set<String> importedFieldNames) {
super(name);
this.headerType = headerType;
this.importedFieldNames = Collections.unmodifiableSet(importedFieldNames);
}
/**
* @deprecated
*/
@Deprecated
public DocumentType(String name, StructDataType headerType,
StructDataType bodyType, Set<String> importedFieldNames) {
this(name, headerType, importedFieldNames);
}
public DocumentType(String name, Set<String> importedFieldNames) {
this(name, createHeaderStructType(name), importedFieldNames);
}
private static StructDataType createHeaderStructType(String name) {
return new StructDataType(name + ".header");
}
@Override
public DocumentType clone() {
DocumentType type = (DocumentType) super.clone();
type.headerType = headerType.clone();
type.inherits = new ArrayList<>(inherits.size());
type.inherits.addAll(inherits);
return type;
}
@Override
public Document createFieldValue() {
return new Document(this, (DocumentId) null);
}
@Override
public Class getValueClass() {
return Document.class;
}
@Override
public boolean isValueCompatible(FieldValue value) {
if (!(value instanceof Document)) {
return false;
}
Document doc = (Document) value;
if (doc.getDataType().inherits(this)) {
return true;
}
return false;
}
/**
* Provides the Struct describing the fields in the document.
*
* @return a struct describing the document fields.
*/
public StructDataType contentStruct() {
return headerType;
}
/** @deprecated use contentStruct instead */
@Deprecated
public StructDataType getHeaderType() {
return contentStruct();
}
@Override
protected void register(DocumentTypeManager manager, List<DataType> seenTypes) {
seenTypes.add(this);
for (DocumentType type : getInheritedTypes()) {
if (!seenTypes.contains(type)) {
type.register(manager, seenTypes);
}
}
StructDataType header = headerType.clone();
header.clearFields();
for (Field field : getAllUniqueFields()) {
header.addField(field);
}
headerType.assign(header);
if (!seenTypes.contains(headerType)) {
headerType.register(manager, seenTypes);
}
manager.registerSingleType(this);
}
/**
* Check if this document type has the given name,
* or inherits from a type with that name.
*/
public boolean isA(String docTypeName) {
if (getName().equalsIgnoreCase(docTypeName)) {
return true;
}
for (DocumentType parent : inherits) {
if (parent.isA(docTypeName)) {
return true;
}
}
return false;
}
/**
* Adds an field that can be used with this document type.
*
* @param field the field to add
*/
public void addField(Field field) {
if (isRegistered()) {
throw new IllegalStateException("You cannot add fields to a document type that is already registered.");
}
headerType.addField(field);
}
public void addFieldSets(Map<String, Collection<String>> fieldSets) {
for (Map.Entry<String, Collection<String>> entry : fieldSets.entrySet()) {
Set<Field> fields = new LinkedHashSet<>(entry.getValue().size());
for (DocumentType parent : inherits) {
Set<Field> parentFieldSet = parent.fieldSet(entry.getKey());
if (parentFieldSet != null) {
fields.addAll(parentFieldSet);
}
}
for (Field orderedField : getAllUniqueFields()) {
if (entry.getValue().contains(orderedField.getName())) {
fields.add(orderedField);
}
}
this.fieldSets.put(entry.getKey(), ImmutableSet.copyOf(fields));
}
if ( ! this.fieldSets.containsKey(ALL)) {
this.fieldSets.put(ALL, getAllUniqueFields());
}
}
/**
* Adds a new field to this document type and returns the new field object
*
* @param name The name of the field to add
* @param type The datatype of the field to add
* @return The field created
* TODO Fix searchdefinition so that exception can be thrown if filed is already registerd.
*/
public Field addField(String name, DataType type) {
if (isRegistered()) {
throw new IllegalStateException("You cannot add fields to a document type that is already registered.");
}
Field field = new Field(name, type);
headerType.addField(field);
return field;
}
/**
* Adds a new header field to this document type and returns the new field object
*
* @param name The name of the field to add
* @param type The datatype of the field to add
* @return The field created
* TODO Fix searchdefinition so that exception can be thrown if filed is already registerd
*/
@Deprecated
public Field addHeaderField(String name, DataType type) {
return addField(name, type);
}
/**
* Adds a document to the inherited document types of this.
* If this type is already directly inherited, nothing is done
*
* @param type An already DocumentType object.
*/
public void inherit(DocumentType type) {
verifyTypeConsistency(type);
if (isRegistered()) {
throw new IllegalStateException("You cannot add inheritance to a document type that is already registered.");
}
if (type == null) {
throw new IllegalArgumentException("The document type cannot be null in inherit()");
}
if (inherits.contains(type)) return;
if (inherits.size() == 1 && inherits.get(0).getDataTypeName().equals(new DataTypeName("document"))) {
inherits.clear();
}
inherits.add(type);
}
/**
* Fail if the subtype changes the type of any equally named field.
*
* @param superType The supertype to verify against
* TODO Add strict type checking no duplicate fields are allowed
*/
private void verifyTypeConsistency(DocumentType superType) {
for (Field f : getAllUniqueFields()) {
Field supField = superType.getField(f.getName());
if (supField != null) {
if (!f.getDataType().equals(supField.getDataType())) {
throw new IllegalArgumentException("Inheritance type mismatch: field \"" + f.getName() +
"\" in datatype \"" + getName() + "\"" +
" must have same datatype as in parent document type \"" + superType.getName() + "\"");
}
}
}
}
/**
* Returns the DocumentNames which are directly inherited by this
* as a read-only collection.
* If this document type does not explicitly inherit anything, the list will
* contain the root type 'Document'
*
* @return a read-only list iterator containing the name Strings of the directly
* inherited document types of this
*/
public Collection<DocumentType> getInheritedTypes() {
return Collections.unmodifiableCollection(inherits);
}
public ListIterator<DataTypeName> inheritedIterator() {
List<DataTypeName> names = new ArrayList<>(inherits.size());
for (DocumentType type : inherits) {
names.add(type.getDataTypeName());
}
return ImmutableList.copyOf(names).listIterator();
}
/**
* Return whether this document type inherits the given document type.
*
* @param superType The documenttype to check if it inherits.
* @return true if it inherits the superType, false if not
*/
public boolean inherits(DocumentType superType) {
if (equals(superType)) return true;
for (DocumentType type : inherits) {
if (type.inherits(superType)) return true;
}
return false;
}
/**
* Gets the field matching a given name.
*
* @param name the name of a field.
* @return returns the matching field, or null if not found.
*/
public Field getField(String name) {
Field field = headerType.getField(name);
if (field == null && !isRegistered()) {
for (DocumentType inheritedType : inherits) {
field = inheritedType.getField(name);
if (field != null) break;
}
}
return field;
}
@Override
public Field getField(int id) {
Field field = headerType.getField(id);
if (field == null && !isRegistered()) {
for (DocumentType inheritedType : inherits) {
field = inheritedType.getField(id);
if (field != null) break;
}
}
return field;
}
/**
* Returns whether this type defines the given field name
*
* @param name The name of the field to check if it has
* @return True if there is a field with the given name.
*/
public boolean hasField(String name) {
return getField(name) != null;
}
public int getFieldCount() {
return headerType.getFieldCount();
}
public Set<String> getImportedFieldNames() {
return importedFieldNames;
}
public boolean hasImportedField(String fieldName) {
return importedFieldNames.contains(fieldName);
}
/**
* Removes an field from the DocumentType.
*
* @param name The name of the field.
* @return The field that was removed or null if it did not exist.
*/
public Field removeField(String name) {
if (isRegistered()) {
throw new IllegalStateException("You cannot remove fields from a document type that is already registered.");
}
Field field = headerType.removeField(name);
if (field == null) {
for (DocumentType inheritedType : inherits) {
field = inheritedType.removeField(name);
if (field != null) break;
}
}
return field;
}
/**
* All fields defined in the document and its parents
* This is for internal use
* Use {@link
* @return All fields defined in the document and its parents
*/
@Override
public Collection<Field> getFields() {
Collection<Field> collection = new LinkedList<>();
for (DocumentType type : inherits) {
collection.addAll(type.getFields());
}
collection.addAll(headerType.getFields());
return ImmutableList.copyOf(collection);
}
private Set<Field> getAllUniqueFields() {
Map<String, Field> map = new LinkedHashMap<>();
for (Field field : getFields()) {
map.put(field.getName(), field);
}
return ImmutableSet.copyOf(map.values());
}
/**
* <p>Returns an ordered set snapshot of all fields of this documenttype,
* <i>except the fields of Document</i>.
* Only the overridden version will be returned for overridden fields.</p>
*
* <p>The fields of a document type has a well-defined order which is
* exhibited in this set:
* - Fields come in the order defined in the document type definition.
* - The fields defined in inherited types come before those in
* the document type itself.
* - When a field in an inherited type is overridden, the value is overridden,
* but not the ordering.
* </p>
*
* @return an unmodifiable snapshot of the fields in this type
*/
public Set<Field> fieldSet() {
return fieldSet(DOCUMENT);
}
/**
* This is identical to {@link |
Yes, it can. | public Iterator<Field> fieldIteratorThisTypeOnly() {
return new Iterator<>() {
Iterator<Field> headerIt = headerType.getFields().iterator();
public boolean hasNext() {
return headerIt.hasNext();
}
public Field next() {
return headerIt.next();
}
public void remove() {
if (headerIt != null) {
headerIt.remove();
}
}
};
} | return headerIt.hasNext(); | public Iterator<Field> fieldIteratorThisTypeOnly() {
return headerType.getFields().iterator();
} | class DocumentType extends StructuredDataType {
private static final String ALL = "[all]";
public static final String DOCUMENT = "[document]";
public static final int classId = registerClass(Ids.document + 58, DocumentType.class);
private StructDataType headerType;
private List<DocumentType> inherits = new ArrayList<>(1);
private Map<String, Set<Field>> fieldSets = new HashMap<>();
private final Set<String> importedFieldNames;
/**
* Creates a new document type and registers it with the document type manager.
* This will be created as version 0 of this document type.
* Implicitly registers this with the document type manager.
* The document type id will be generated as a hash from the document type name.
*
* @param name The name of the new document type
*/
public DocumentType(String name) {
this(name, createHeaderStructType(name));
}
/**
* Creates a new document type and registers it with the document type manager.
* Implicitly registers this with the document type manager.
* The document type id will be generated as a hash from the document type name.
*
* @param name The name of the new document type
* @param headerType The type of the header struct
*/
public DocumentType(String name, StructDataType headerType) {
this(name, headerType, Collections.emptySet());
}
/**
* @deprecated
*/
@Deprecated
public DocumentType(String name, StructDataType headerType, StructDataType bodyType) {
this(name, headerType, Collections.emptySet());
}
public DocumentType(String name, StructDataType headerType, Set<String> importedFieldNames) {
super(name);
this.headerType = headerType;
this.importedFieldNames = Collections.unmodifiableSet(importedFieldNames);
}
/**
* @deprecated
*/
@Deprecated
public DocumentType(String name, StructDataType headerType,
StructDataType bodyType, Set<String> importedFieldNames) {
this(name, headerType, importedFieldNames);
}
public DocumentType(String name, Set<String> importedFieldNames) {
this(name, createHeaderStructType(name), importedFieldNames);
}
private static StructDataType createHeaderStructType(String name) {
return new StructDataType(name + ".header");
}
@Override
public DocumentType clone() {
DocumentType type = (DocumentType) super.clone();
type.headerType = headerType.clone();
type.inherits = new ArrayList<>(inherits.size());
type.inherits.addAll(inherits);
return type;
}
@Override
public Document createFieldValue() {
return new Document(this, (DocumentId) null);
}
@Override
public Class getValueClass() {
return Document.class;
}
@Override
public boolean isValueCompatible(FieldValue value) {
if (!(value instanceof Document)) {
return false;
}
Document doc = (Document) value;
if (doc.getDataType().inherits(this)) {
return true;
}
return false;
}
/**
* Provides the Struct describing the fields in the document.
*
* @return a struct describing the document fields.
*/
public StructDataType contentStruct() {
return headerType;
}
/** @deprecated use contentStruct instead */
@Deprecated
public StructDataType getHeaderType() {
return contentStruct();
}
@Deprecated
/** @deprecated use contentStruct instead */
public StructDataType getBodyType() {
return null;
}
@Override
protected void register(DocumentTypeManager manager, List<DataType> seenTypes) {
seenTypes.add(this);
for (DocumentType type : getInheritedTypes()) {
if (!seenTypes.contains(type)) {
type.register(manager, seenTypes);
}
}
StructDataType header = headerType.clone();
header.clearFields();
for (Field field : getAllUniqueFields()) {
header.addField(field);
}
headerType.assign(header);
if (!seenTypes.contains(headerType)) {
headerType.register(manager, seenTypes);
}
manager.registerSingleType(this);
}
/**
* Check if this document type has the given name,
* or inherits from a type with that name.
*/
public boolean isA(String docTypeName) {
if (getName().equalsIgnoreCase(docTypeName)) {
return true;
}
for (DocumentType parent : inherits) {
if (parent.isA(docTypeName)) {
return true;
}
}
return false;
}
/**
* Adds an field that can be used with this document type.
*
* @param field the field to add
*/
public void addField(Field field) {
if (isRegistered()) {
throw new IllegalStateException("You cannot add fields to a document type that is already registered.");
}
headerType.addField(field);
}
public void addFieldSets(Map<String, Collection<String>> fieldSets) {
for (Map.Entry<String, Collection<String>> entry : fieldSets.entrySet()) {
Set<Field> fields = new LinkedHashSet<>(entry.getValue().size());
for (DocumentType parent : inherits) {
Set<Field> parentFieldSet = parent.fieldSet(entry.getKey());
if (parentFieldSet != null) {
fields.addAll(parentFieldSet);
}
}
for (Field orderedField : getAllUniqueFields()) {
if (entry.getValue().contains(orderedField.getName())) {
fields.add(orderedField);
}
}
this.fieldSets.put(entry.getKey(), ImmutableSet.copyOf(fields));
}
if ( ! this.fieldSets.containsKey(ALL)) {
this.fieldSets.put(ALL, getAllUniqueFields());
}
}
/**
* Adds a new field to this document type and returns the new field object
*
* @param name The name of the field to add
* @param type The datatype of the field to add
* @return The field created
* TODO Fix searchdefinition so that exception can be thrown if filed is already registerd.
*/
public Field addField(String name, DataType type) {
if (isRegistered()) {
throw new IllegalStateException("You cannot add fields to a document type that is already registered.");
}
Field field = new Field(name, type);
headerType.addField(field);
return field;
}
/**
* Adds a new header field to this document type and returns the new field object
*
* @param name The name of the field to add
* @param type The datatype of the field to add
* @return The field created
* TODO Fix searchdefinition so that exception can be thrown if filed is already registerd
*/
@Deprecated
public Field addHeaderField(String name, DataType type) {
return addField(name, type);
}
/**
* Adds a document to the inherited document types of this.
* If this type is already directly inherited, nothing is done
*
* @param type An already DocumentType object.
*/
public void inherit(DocumentType type) {
verifyTypeConsistency(type);
if (isRegistered()) {
throw new IllegalStateException("You cannot add inheritance to a document type that is already registered.");
}
if (type == null) {
throw new IllegalArgumentException("The document type cannot be null in inherit()");
}
if (inherits.contains(type)) return;
if (inherits.size() == 1 && inherits.get(0).getDataTypeName().equals(new DataTypeName("document"))) {
inherits.clear();
}
inherits.add(type);
}
/**
* Fail if the subtype changes the type of any equally named field.
*
* @param superType The supertype to verify against
* TODO Add strict type checking no duplicate fields are allowed
*/
private void verifyTypeConsistency(DocumentType superType) {
for (Field f : getAllUniqueFields()) {
Field supField = superType.getField(f.getName());
if (supField != null) {
if (!f.getDataType().equals(supField.getDataType())) {
throw new IllegalArgumentException("Inheritance type mismatch: field \"" + f.getName() +
"\" in datatype \"" + getName() + "\"" +
" must have same datatype as in parent document type \"" + superType.getName() + "\"");
}
}
}
}
/**
* Returns the DocumentNames which are directly inherited by this
* as a read-only collection.
* If this document type does not explicitly inherit anything, the list will
* contain the root type 'Document'
*
* @return a read-only list iterator containing the name Strings of the directly
* inherited document types of this
*/
public Collection<DocumentType> getInheritedTypes() {
return Collections.unmodifiableCollection(inherits);
}
public ListIterator<DataTypeName> inheritedIterator() {
List<DataTypeName> names = new ArrayList<>(inherits.size());
for (DocumentType type : inherits) {
names.add(type.getDataTypeName());
}
return ImmutableList.copyOf(names).listIterator();
}
/**
* Return whether this document type inherits the given document type.
*
* @param superType The documenttype to check if it inherits.
* @return true if it inherits the superType, false if not
*/
public boolean inherits(DocumentType superType) {
if (equals(superType)) return true;
for (DocumentType type : inherits) {
if (type.inherits(superType)) return true;
}
return false;
}
/**
* Gets the field matching a given name.
*
* @param name the name of a field.
* @return returns the matching field, or null if not found.
*/
public Field getField(String name) {
Field field = headerType.getField(name);
if (field == null && !isRegistered()) {
for (DocumentType inheritedType : inherits) {
field = inheritedType.getField(name);
if (field != null) break;
}
}
return field;
}
@Override
public Field getField(int id) {
Field field = headerType.getField(id);
if (field == null && !isRegistered()) {
for (DocumentType inheritedType : inherits) {
field = inheritedType.getField(id);
if (field != null) break;
}
}
return field;
}
/**
* Returns whether this type defines the given field name
*
* @param name The name of the field to check if it has
* @return True if there is a field with the given name.
*/
public boolean hasField(String name) {
return getField(name) != null;
}
public int getFieldCount() {
return headerType.getFieldCount();
}
public Set<String> getImportedFieldNames() {
return importedFieldNames;
}
public boolean hasImportedField(String fieldName) {
return importedFieldNames.contains(fieldName);
}
/**
* Removes an field from the DocumentType.
*
* @param name The name of the field.
* @return The field that was removed or null if it did not exist.
*/
public Field removeField(String name) {
if (isRegistered()) {
throw new IllegalStateException("You cannot remove fields from a document type that is already registered.");
}
Field field = headerType.removeField(name);
if (field == null) {
for (DocumentType inheritedType : inherits) {
field = inheritedType.removeField(name);
if (field != null) break;
}
}
return field;
}
/**
* All fields defined in the document and its parents
* This is for internal use
* Use {@link
* @return All fields defined in the document and its parents
*/
@Override
public Collection<Field> getFields() {
Collection<Field> collection = new LinkedList<>();
for (DocumentType type : inherits) {
collection.addAll(type.getFields());
}
collection.addAll(headerType.getFields());
return ImmutableList.copyOf(collection);
}
private Set<Field> getAllUniqueFields() {
Map<String, Field> map = new LinkedHashMap<>();
for (Field field : getFields()) {
map.put(field.getName(), field);
}
return ImmutableSet.copyOf(map.values());
}
/**
* <p>Returns an ordered set snapshot of all fields of this documenttype,
* <i>except the fields of Document</i>.
* Only the overridden version will be returned for overridden fields.</p>
*
* <p>The fields of a document type has a well-defined order which is
* exhibited in this set:
* - Fields come in the order defined in the document type definition.
* - The fields defined in inherited types come before those in
* the document type itself.
* - When a field in an inherited type is overridden, the value is overridden,
* but not the ordering.
* </p>
*
* @return an unmodifiable snapshot of the fields in this type
*/
public Set<Field> fieldSet() {
return fieldSet(DOCUMENT);
}
/**
* This is identical to {@link | class DocumentType extends StructuredDataType {
private static final String ALL = "[all]";
public static final String DOCUMENT = "[document]";
public static final int classId = registerClass(Ids.document + 58, DocumentType.class);
private StructDataType headerType;
private List<DocumentType> inherits = new ArrayList<>(1);
private Map<String, Set<Field>> fieldSets = new HashMap<>();
private final Set<String> importedFieldNames;
/**
* Creates a new document type and registers it with the document type manager.
* This will be created as version 0 of this document type.
* Implicitly registers this with the document type manager.
* The document type id will be generated as a hash from the document type name.
*
* @param name The name of the new document type
*/
public DocumentType(String name) {
this(name, createHeaderStructType(name));
}
/**
* Creates a new document type and registers it with the document type manager.
* Implicitly registers this with the document type manager.
* The document type id will be generated as a hash from the document type name.
*
* @param name The name of the new document type
* @param headerType The type of the header struct
*/
public DocumentType(String name, StructDataType headerType) {
this(name, headerType, Collections.emptySet());
}
/**
* @deprecated
*/
@Deprecated
public DocumentType(String name, StructDataType headerType, StructDataType bodyType) {
this(name, headerType, Collections.emptySet());
}
public DocumentType(String name, StructDataType headerType, Set<String> importedFieldNames) {
super(name);
this.headerType = headerType;
this.importedFieldNames = Collections.unmodifiableSet(importedFieldNames);
}
/**
* @deprecated
*/
@Deprecated
public DocumentType(String name, StructDataType headerType,
StructDataType bodyType, Set<String> importedFieldNames) {
this(name, headerType, importedFieldNames);
}
public DocumentType(String name, Set<String> importedFieldNames) {
this(name, createHeaderStructType(name), importedFieldNames);
}
private static StructDataType createHeaderStructType(String name) {
return new StructDataType(name + ".header");
}
@Override
public DocumentType clone() {
DocumentType type = (DocumentType) super.clone();
type.headerType = headerType.clone();
type.inherits = new ArrayList<>(inherits.size());
type.inherits.addAll(inherits);
return type;
}
@Override
public Document createFieldValue() {
return new Document(this, (DocumentId) null);
}
@Override
public Class getValueClass() {
return Document.class;
}
@Override
public boolean isValueCompatible(FieldValue value) {
if (!(value instanceof Document)) {
return false;
}
Document doc = (Document) value;
if (doc.getDataType().inherits(this)) {
return true;
}
return false;
}
/**
* Provides the Struct describing the fields in the document.
*
* @return a struct describing the document fields.
*/
public StructDataType contentStruct() {
return headerType;
}
/** @deprecated use contentStruct instead */
@Deprecated
public StructDataType getHeaderType() {
return contentStruct();
}
@Override
protected void register(DocumentTypeManager manager, List<DataType> seenTypes) {
seenTypes.add(this);
for (DocumentType type : getInheritedTypes()) {
if (!seenTypes.contains(type)) {
type.register(manager, seenTypes);
}
}
StructDataType header = headerType.clone();
header.clearFields();
for (Field field : getAllUniqueFields()) {
header.addField(field);
}
headerType.assign(header);
if (!seenTypes.contains(headerType)) {
headerType.register(manager, seenTypes);
}
manager.registerSingleType(this);
}
/**
* Check if this document type has the given name,
* or inherits from a type with that name.
*/
public boolean isA(String docTypeName) {
if (getName().equalsIgnoreCase(docTypeName)) {
return true;
}
for (DocumentType parent : inherits) {
if (parent.isA(docTypeName)) {
return true;
}
}
return false;
}
/**
* Adds an field that can be used with this document type.
*
* @param field the field to add
*/
public void addField(Field field) {
if (isRegistered()) {
throw new IllegalStateException("You cannot add fields to a document type that is already registered.");
}
headerType.addField(field);
}
public void addFieldSets(Map<String, Collection<String>> fieldSets) {
for (Map.Entry<String, Collection<String>> entry : fieldSets.entrySet()) {
Set<Field> fields = new LinkedHashSet<>(entry.getValue().size());
for (DocumentType parent : inherits) {
Set<Field> parentFieldSet = parent.fieldSet(entry.getKey());
if (parentFieldSet != null) {
fields.addAll(parentFieldSet);
}
}
for (Field orderedField : getAllUniqueFields()) {
if (entry.getValue().contains(orderedField.getName())) {
fields.add(orderedField);
}
}
this.fieldSets.put(entry.getKey(), ImmutableSet.copyOf(fields));
}
if ( ! this.fieldSets.containsKey(ALL)) {
this.fieldSets.put(ALL, getAllUniqueFields());
}
}
/**
* Adds a new field to this document type and returns the new field object
*
* @param name The name of the field to add
* @param type The datatype of the field to add
* @return The field created
* TODO Fix searchdefinition so that exception can be thrown if filed is already registerd.
*/
public Field addField(String name, DataType type) {
if (isRegistered()) {
throw new IllegalStateException("You cannot add fields to a document type that is already registered.");
}
Field field = new Field(name, type);
headerType.addField(field);
return field;
}
/**
* Adds a new header field to this document type and returns the new field object
*
* @param name The name of the field to add
* @param type The datatype of the field to add
* @return The field created
* TODO Fix searchdefinition so that exception can be thrown if filed is already registerd
*/
@Deprecated
public Field addHeaderField(String name, DataType type) {
return addField(name, type);
}
/**
* Adds a document to the inherited document types of this.
* If this type is already directly inherited, nothing is done
*
* @param type An already DocumentType object.
*/
public void inherit(DocumentType type) {
verifyTypeConsistency(type);
if (isRegistered()) {
throw new IllegalStateException("You cannot add inheritance to a document type that is already registered.");
}
if (type == null) {
throw new IllegalArgumentException("The document type cannot be null in inherit()");
}
if (inherits.contains(type)) return;
if (inherits.size() == 1 && inherits.get(0).getDataTypeName().equals(new DataTypeName("document"))) {
inherits.clear();
}
inherits.add(type);
}
/**
* Fail if the subtype changes the type of any equally named field.
*
* @param superType The supertype to verify against
* TODO Add strict type checking no duplicate fields are allowed
*/
private void verifyTypeConsistency(DocumentType superType) {
for (Field f : getAllUniqueFields()) {
Field supField = superType.getField(f.getName());
if (supField != null) {
if (!f.getDataType().equals(supField.getDataType())) {
throw new IllegalArgumentException("Inheritance type mismatch: field \"" + f.getName() +
"\" in datatype \"" + getName() + "\"" +
" must have same datatype as in parent document type \"" + superType.getName() + "\"");
}
}
}
}
/**
* Returns the DocumentNames which are directly inherited by this
* as a read-only collection.
* If this document type does not explicitly inherit anything, the list will
* contain the root type 'Document'
*
* @return a read-only list iterator containing the name Strings of the directly
* inherited document types of this
*/
public Collection<DocumentType> getInheritedTypes() {
return Collections.unmodifiableCollection(inherits);
}
public ListIterator<DataTypeName> inheritedIterator() {
List<DataTypeName> names = new ArrayList<>(inherits.size());
for (DocumentType type : inherits) {
names.add(type.getDataTypeName());
}
return ImmutableList.copyOf(names).listIterator();
}
/**
* Return whether this document type inherits the given document type.
*
* @param superType The documenttype to check if it inherits.
* @return true if it inherits the superType, false if not
*/
public boolean inherits(DocumentType superType) {
if (equals(superType)) return true;
for (DocumentType type : inherits) {
if (type.inherits(superType)) return true;
}
return false;
}
/**
* Gets the field matching a given name.
*
* @param name the name of a field.
* @return returns the matching field, or null if not found.
*/
public Field getField(String name) {
Field field = headerType.getField(name);
if (field == null && !isRegistered()) {
for (DocumentType inheritedType : inherits) {
field = inheritedType.getField(name);
if (field != null) break;
}
}
return field;
}
@Override
public Field getField(int id) {
Field field = headerType.getField(id);
if (field == null && !isRegistered()) {
for (DocumentType inheritedType : inherits) {
field = inheritedType.getField(id);
if (field != null) break;
}
}
return field;
}
/**
* Returns whether this type defines the given field name
*
* @param name The name of the field to check if it has
* @return True if there is a field with the given name.
*/
public boolean hasField(String name) {
return getField(name) != null;
}
public int getFieldCount() {
return headerType.getFieldCount();
}
public Set<String> getImportedFieldNames() {
return importedFieldNames;
}
public boolean hasImportedField(String fieldName) {
return importedFieldNames.contains(fieldName);
}
/**
* Removes an field from the DocumentType.
*
* @param name The name of the field.
* @return The field that was removed or null if it did not exist.
*/
public Field removeField(String name) {
if (isRegistered()) {
throw new IllegalStateException("You cannot remove fields from a document type that is already registered.");
}
Field field = headerType.removeField(name);
if (field == null) {
for (DocumentType inheritedType : inherits) {
field = inheritedType.removeField(name);
if (field != null) break;
}
}
return field;
}
/**
* All fields defined in the document and its parents
* This is for internal use
* Use {@link
* @return All fields defined in the document and its parents
*/
@Override
public Collection<Field> getFields() {
Collection<Field> collection = new LinkedList<>();
for (DocumentType type : inherits) {
collection.addAll(type.getFields());
}
collection.addAll(headerType.getFields());
return ImmutableList.copyOf(collection);
}
private Set<Field> getAllUniqueFields() {
Map<String, Field> map = new LinkedHashMap<>();
for (Field field : getFields()) {
map.put(field.getName(), field);
}
return ImmutableSet.copyOf(map.values());
}
/**
* <p>Returns an ordered set snapshot of all fields of this documenttype,
* <i>except the fields of Document</i>.
* Only the overridden version will be returned for overridden fields.</p>
*
* <p>The fields of a document type has a well-defined order which is
* exhibited in this set:
* - Fields come in the order defined in the document type definition.
* - The fields defined in inherited types come before those in
* the document type itself.
* - When a field in an inherited type is overridden, the value is overridden,
* but not the ordering.
* </p>
*
* @return an unmodifiable snapshot of the fields in this type
*/
public Set<Field> fieldSet() {
return fieldSet(DOCUMENT);
}
/**
* This is identical to {@link |
```suggestion resources = resources.add(move.node().resources()); ``` | private NodeResources freeCapacityWith(List<Move> moves, Node host) {
NodeResources resources = hostCapacity.freeCapacityOf(host);
for (Move move : moves) {
if ( ! move.toHost().equals(host)) continue;
resources = resources.subtract(move.node().resources());
}
for (Move move : moves) {
if ( ! move.fromHost().equals(host)) continue;
resources = resources.add(move.fromHost().resources());
}
return resources;
} | resources = resources.add(move.fromHost().resources()); | private NodeResources freeCapacityWith(List<Move> moves, Node host) {
NodeResources resources = hostCapacity.freeCapacityOf(host);
for (Move move : moves) {
if ( ! move.toHost().equals(host)) continue;
resources = resources.subtract(move.node().resources());
}
for (Move move : moves) {
if ( ! move.fromHost().equals(host)) continue;
resources = resources.add(move.node().resources());
}
return resources;
} | class CapacitySolver {
private final HostCapacity hostCapacity;
private final int maxIterations;
private int iterations = 0;
CapacitySolver(HostCapacity hostCapacity, int maxIterations) {
this.hostCapacity = hostCapacity;
this.maxIterations = maxIterations;
}
/** The map of subproblem solutions already found. The value is null when there is no solution. */
private Map<SolutionKey, List<Move>> solutions = new HashMap<>();
/**
* Finds the shortest sequence of moves which makes room for the given node on the given host,
* assuming the given moves already made over the given hosts' current allocation.
*
* @param node the node to make room for
* @param host the target host to make room on
* @param hosts the hosts onto which we can move nodes
* @param movesConsidered the moves already being considered to add as part of this scenario
* (after any moves made by this)
* @param movesMade the moves already made in this scenario
* @return the list of movesMade with the moves needed for this appended, in the order they should be performed,
* or null if no sequence could be found
*/
List<Move> makeRoomFor(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
SolutionKey solutionKey = new SolutionKey(node, host, movesConsidered, movesMade);
List<Move> solution = solutions.get(solutionKey);
if (solution == null) {
solution = findRoomFor(node, host, hosts, movesConsidered, movesMade);
solutions.put(solutionKey, solution);
}
return solution;
}
private List<Move> findRoomFor(Node node, Node host, List<Node> hosts,
List<Move> movesConsidered, List<Move> movesMade) {
if (iterations++ > maxIterations)
return null;
if ( ! host.resources().satisfies(node.resources())) return null;
NodeResources freeCapacity = freeCapacityWith(movesMade, host);
if (freeCapacity.satisfies(node.resources())) return List.of();
List<Move> shortest = null;
for (var i = subsets(hostCapacity.allNodes().childrenOf(host), 5); i.hasNext(); ) {
List<Node> childrenToMove = i.next();
if ( ! addResourcesOf(childrenToMove, freeCapacity).satisfies(node.resources())) continue;
List<Move> moves = move(childrenToMove, host, hosts, movesConsidered, movesMade);
if (moves == null) continue;
if (shortest == null || moves.size() < shortest.size())
shortest = moves;
}
if (shortest == null) return null;
return append(movesMade, shortest);
}
private List<Move> move(List<Node> nodes, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
List<Move> moves = new ArrayList<>();
for (Node childToMove : nodes) {
List<Move> childMoves = move(childToMove, host, hosts, movesConsidered, append(movesMade, moves));
if (childMoves == null) return null;
moves.addAll(childMoves);
}
return moves;
}
private List<Move> move(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
if (contains(node, movesConsidered)) return null;
if (contains(node, movesMade)) return null;
List<Move> shortest = null;
for (Node target : hosts) {
if (target.equals(host)) continue;
Move move = new Move(node, host, target);
List<Move> childMoves = makeRoomFor(node, target, hosts, append(movesConsidered, move), movesMade);
if (childMoves == null) continue;
if (shortest == null || shortest.size() > childMoves.size() + 1) {
shortest = new ArrayList<>(childMoves);
shortest.add(move);
}
}
return shortest;
}
private boolean contains(Node node, List<Move> moves) {
return moves.stream().anyMatch(move -> move.node().equals(node));
}
private NodeResources addResourcesOf(List<Node> nodes, NodeResources resources) {
for (Node node : nodes)
resources = resources.add(node.resources());
return resources;
}
private Iterator<List<Node>> subsets(NodeList nodes, int maxSize) {
return new SubsetIterator(nodes.asList(), maxSize);
}
private List<Move> append(List<Move> a, List<Move> b) {
List<Move> list = new ArrayList<>();
list.addAll(a);
list.addAll(b);
return list;
}
private List<Move> append(List<Move> moves, Move move) {
List<Move> list = new ArrayList<>(moves);
list.add(move);
return list;
}
} | class CapacitySolver {
private final HostCapacity hostCapacity;
private final int maxIterations;
private int iterations = 0;
CapacitySolver(HostCapacity hostCapacity, int maxIterations) {
this.hostCapacity = hostCapacity;
this.maxIterations = maxIterations;
}
/** The map of subproblem solutions already found. The value is null when there is no solution. */
private Map<SolutionKey, List<Move>> solutions = new HashMap<>();
/**
* Finds the shortest sequence of moves which makes room for the given node on the given host,
* assuming the given moves already made over the given hosts' current allocation.
*
* @param node the node to make room for
* @param host the target host to make room on
* @param hosts the hosts onto which we can move nodes
* @param movesConsidered the moves already being considered to add as part of this scenario
* (after any moves made by this)
* @param movesMade the moves already made in this scenario
* @return the list of movesMade with the moves needed for this appended, in the order they should be performed,
* or null if no sequence could be found
*/
List<Move> makeRoomFor(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
SolutionKey solutionKey = new SolutionKey(node, host, movesConsidered, movesMade);
List<Move> solution = solutions.get(solutionKey);
if (solution == null) {
solution = findRoomFor(node, host, hosts, movesConsidered, movesMade);
solutions.put(solutionKey, solution);
}
return solution;
}
private List<Move> findRoomFor(Node node, Node host, List<Node> hosts,
List<Move> movesConsidered, List<Move> movesMade) {
if (iterations++ > maxIterations)
return null;
if ( ! host.resources().satisfies(node.resources())) return null;
NodeResources freeCapacity = freeCapacityWith(movesMade, host);
if (freeCapacity.satisfies(node.resources())) return List.of();
List<Move> shortest = null;
for (var i = subsets(hostCapacity.allNodes().childrenOf(host), 5); i.hasNext(); ) {
List<Node> childrenToMove = i.next();
if ( ! addResourcesOf(childrenToMove, freeCapacity).satisfies(node.resources())) continue;
List<Move> moves = move(childrenToMove, host, hosts, movesConsidered, movesMade);
if (moves == null) continue;
if (shortest == null || moves.size() < shortest.size())
shortest = moves;
}
if (shortest == null) return null;
return append(movesMade, shortest);
}
private List<Move> move(List<Node> nodes, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
List<Move> moves = new ArrayList<>();
for (Node childToMove : nodes) {
List<Move> childMoves = move(childToMove, host, hosts, movesConsidered, append(movesMade, moves));
if (childMoves == null) return null;
moves.addAll(childMoves);
}
return moves;
}
private List<Move> move(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
if (contains(node, movesConsidered)) return null;
if (contains(node, movesMade)) return null;
List<Move> shortest = null;
for (Node target : hosts) {
if (target.equals(host)) continue;
Move move = new Move(node, host, target);
List<Move> childMoves = makeRoomFor(node, target, hosts, append(movesConsidered, move), movesMade);
if (childMoves == null) continue;
if (shortest == null || shortest.size() > childMoves.size() + 1) {
shortest = new ArrayList<>(childMoves);
shortest.add(move);
}
}
return shortest;
}
private boolean contains(Node node, List<Move> moves) {
return moves.stream().anyMatch(move -> move.node().equals(node));
}
private NodeResources addResourcesOf(List<Node> nodes, NodeResources resources) {
for (Node node : nodes)
resources = resources.add(node.resources());
return resources;
}
private Iterator<List<Node>> subsets(NodeList nodes, int maxSize) {
return new SubsetIterator(nodes.asList(), maxSize);
}
private List<Move> append(List<Move> a, List<Move> b) {
List<Move> list = new ArrayList<>();
list.addAll(a);
list.addAll(b);
return list;
}
private List<Move> append(List<Move> moves, Move move) {
List<Move> list = new ArrayList<>(moves);
list.add(move);
return list;
}
} |
Why is this needed? | private void addNodes(int id, int count, NodeResources resources, int hostOffset) {
List<Node> nodes = new ArrayList<>();
ApplicationId application = ApplicationId.from("tenant" + id, "application" + id, "default");
for (int i = 0; i < count; i++) {
ClusterMembership membership = ClusterMembership.from(ClusterSpec.specification(ClusterSpec.Type.content, ClusterSpec.Id.from("cluster" + id))
.group(ClusterSpec.Group.from(0))
.vespaVersion("7")
.build(),
i);
Node node = nodeRepository.createNode("node" + nodeIndex,
"node" + nodeIndex + ".yahoo.com",
ipConfig(hostIndex + nodeIndex, false),
Optional.of("host" + ( hostOffset + i) + ".yahoo.com"),
new Flavor(resources),
Optional.empty(),
NodeType.tenant);
node = node.allocate(application, membership, node.resources(), Instant.now());
nodes.add(node);
nodeIndex++;
}
nodes = nodeRepository.addNodes(nodes, Agent.system);
for (int i = 0; i < count; i++) {
Node node = nodes.get(i);
ClusterMembership membership = ClusterMembership.from(ClusterSpec.specification(ClusterSpec.Type.content, ClusterSpec.Id.from("cluster" + id))
.group(ClusterSpec.Group.from(0))
.vespaVersion("7")
.build(),
i);
node = node.allocate(application, membership, node.resources(), Instant.now());
nodes.set(i, node);
}
nodes = nodeRepository.reserve(nodes);
var transaction = new NestedTransaction();
nodes = nodeRepository.activate(nodes, transaction);
transaction.commit();
} | for (int i = 0; i < count; i++) { | private void addNodes(int id, int count, NodeResources resources, int hostOffset) {
List<Node> nodes = new ArrayList<>();
ApplicationId application = ApplicationId.from("tenant" + id, "application" + id, "default");
for (int i = 0; i < count; i++) {
ClusterMembership membership = ClusterMembership.from(ClusterSpec.specification(ClusterSpec.Type.content, ClusterSpec.Id.from("cluster" + id))
.group(ClusterSpec.Group.from(0))
.vespaVersion("7")
.build(),
i);
Node node = nodeRepository.createNode("node" + nodeIndex,
"node" + nodeIndex + ".yahoo.com",
ipConfig(hostIndex + nodeIndex, false),
Optional.of("host" + ( hostOffset + i) + ".yahoo.com"),
new Flavor(resources),
Optional.empty(),
NodeType.tenant);
node = node.allocate(application, membership, node.resources(), Instant.now());
nodes.add(node);
nodeIndex++;
}
nodes = nodeRepository.addNodes(nodes, Agent.system);
for (int i = 0; i < count; i++) {
Node node = nodes.get(i);
ClusterMembership membership = ClusterMembership.from(ClusterSpec.specification(ClusterSpec.Type.content, ClusterSpec.Id.from("cluster" + id))
.group(ClusterSpec.Group.from(0))
.vespaVersion("7")
.build(),
i);
node = node.allocate(application, membership, node.resources(), Instant.now());
nodes.set(i, node);
}
nodes = nodeRepository.reserve(nodes);
var transaction = new NestedTransaction();
nodes = nodeRepository.activate(nodes, transaction);
transaction.commit();
} | class SpareCapacityMaintainerTester {
NodeRepository nodeRepository;
MockDeployer deployer;
TestMetric metric = new TestMetric();
SpareCapacityMaintainer maintainer;
private int hostIndex = 0;
private int nodeIndex = 0;
private SpareCapacityMaintainerTester() {
this(1000);
}
private SpareCapacityMaintainerTester(int maxIterations) {
NodeFlavors flavors = new NodeFlavors(new FlavorConfigBuilder().build());
nodeRepository = new NodeRepository(flavors,
new EmptyProvisionServiceProvider().getHostResourcesCalculator(),
new MockCurator(),
new ManualClock(),
new Zone(Environment.prod, RegionName.from("us-east-3")),
new MockNameResolver().mockAnyLookup(),
DockerImage.fromString("docker-registry.domain.tld:8080/dist/vespa"), true, false);
deployer = new MockDeployer(nodeRepository);
maintainer = new SpareCapacityMaintainer(deployer, nodeRepository, metric, Duration.ofDays(1), maxIterations);
}
private void addHosts(int count, NodeResources resources) {
List<Node> hosts = new ArrayList<>();
for (int i = 0; i < count; i++) {
Node host = nodeRepository.createNode("host" + hostIndex,
"host" + hostIndex + ".yahoo.com",
ipConfig(hostIndex + nodeIndex, true),
Optional.empty(),
new Flavor(resources),
Optional.empty(),
NodeType.host);
hosts.add(host);
hostIndex++;
}
hosts = nodeRepository.addNodes(hosts, Agent.system);
hosts = nodeRepository.setReady(hosts, Agent.system, "Test");
var transaction = new NestedTransaction();
nodeRepository.activate(hosts, transaction);
transaction.commit();
}
private IP.Config ipConfig(int id, boolean host) {
return new IP.Config(Set.of(String.format("%04X::%04X", id, 0)),
host ? IntStream.range(0, 10)
.mapToObj(n -> String.format("%04X::%04X", id, n))
.collect(Collectors.toSet())
: Set.of());
}
private void dumpState() {
for (Node host : nodeRepository.list().hosts().asList()) {
System.out.println("Host " + host.hostname() + " " + host.resources());
for (Node node : nodeRepository.list().childrenOf(host).asList())
System.out.println(" Node " + node.hostname() + " " + node.resources() + " allocation " +node.allocation());
}
}
} | class SpareCapacityMaintainerTester {
NodeRepository nodeRepository;
MockDeployer deployer;
TestMetric metric = new TestMetric();
SpareCapacityMaintainer maintainer;
private int hostIndex = 0;
private int nodeIndex = 0;
private SpareCapacityMaintainerTester() {
this(1000);
}
private SpareCapacityMaintainerTester(int maxIterations) {
NodeFlavors flavors = new NodeFlavors(new FlavorConfigBuilder().build());
nodeRepository = new NodeRepository(flavors,
new EmptyProvisionServiceProvider().getHostResourcesCalculator(),
new MockCurator(),
new ManualClock(),
new Zone(Environment.prod, RegionName.from("us-east-3")),
new MockNameResolver().mockAnyLookup(),
DockerImage.fromString("docker-registry.domain.tld:8080/dist/vespa"), true, false);
deployer = new MockDeployer(nodeRepository);
maintainer = new SpareCapacityMaintainer(deployer, nodeRepository, metric, Duration.ofDays(1), maxIterations);
}
private void addHosts(int count, NodeResources resources) {
List<Node> hosts = new ArrayList<>();
for (int i = 0; i < count; i++) {
Node host = nodeRepository.createNode("host" + hostIndex,
"host" + hostIndex + ".yahoo.com",
ipConfig(hostIndex + nodeIndex, true),
Optional.empty(),
new Flavor(resources),
Optional.empty(),
NodeType.host);
hosts.add(host);
hostIndex++;
}
hosts = nodeRepository.addNodes(hosts, Agent.system);
hosts = nodeRepository.setReady(hosts, Agent.system, "Test");
var transaction = new NestedTransaction();
nodeRepository.activate(hosts, transaction);
transaction.commit();
}
private IP.Config ipConfig(int id, boolean host) {
return new IP.Config(Set.of(String.format("%04X::%04X", id, 0)),
host ? IntStream.range(0, 10)
.mapToObj(n -> String.format("%04X::%04X", id, n))
.collect(Collectors.toSet())
: Set.of());
}
private void dumpState() {
for (Node host : nodeRepository.list().hosts().asList()) {
System.out.println("Host " + host.hostname() + " " + host.resources());
for (Node node : nodeRepository.list().childrenOf(host).asList())
System.out.println(" Node " + node.hostname() + " " + node.resources() + " allocation " +node.allocation());
}
}
} |
It's not obvious to me that this return `null`/empty list always ends being correct, why not always return non-null? Also, add a check here to ignore empty mitigation if we already have a `shortestMitigation` candidate, after all doing something that takes longer should be better than doing nothing? | private Move findMitigatingMove(CapacityChecker.HostFailurePath failurePath) {
Optional<Node> nodeWhichCantMove = failurePath.failureReason.tenant;
if (nodeWhichCantMove.isEmpty()) return Move.empty();
Node node = nodeWhichCantMove.get();
NodeList allNodes = nodeRepository().list();
HostCapacity hostCapacity = new HostCapacity(allNodes, nodeRepository().resourcesCalculator());
Set<Node> spareHosts = hostCapacity.findSpareHosts(allNodes.hosts().satisfies(node.resources()).asList(), 2);
List<Node> hosts = allNodes.hosts().except(spareHosts).asList();
CapacitySolver capacitySolver = new CapacitySolver(hostCapacity, maxIterations);
List<Move> shortestMitigation = null;
for (Node spareHost : spareHosts) {
List<Move> mitigation = capacitySolver.makeRoomFor(node, spareHost, hosts, List.of(), List.of());
if (mitigation == null) continue;
if (shortestMitigation == null || shortestMitigation.size() > mitigation.size())
shortestMitigation = mitigation;
}
if (shortestMitigation == null || shortestMitigation.isEmpty()) return Move.empty();
return shortestMitigation.get(0);
} | if (shortestMitigation == null || shortestMitigation.size() > mitigation.size()) | private Move findMitigatingMove(CapacityChecker.HostFailurePath failurePath) {
Optional<Node> nodeWhichCantMove = failurePath.failureReason.tenant;
if (nodeWhichCantMove.isEmpty()) return Move.empty();
Node node = nodeWhichCantMove.get();
NodeList allNodes = nodeRepository().list();
HostCapacity hostCapacity = new HostCapacity(allNodes, nodeRepository().resourcesCalculator());
Set<Node> spareHosts = hostCapacity.findSpareHosts(allNodes.hosts().satisfies(node.resources()).asList(), 2);
List<Node> hosts = allNodes.hosts().except(spareHosts).asList();
CapacitySolver capacitySolver = new CapacitySolver(hostCapacity, maxIterations);
List<Move> shortestMitigation = null;
for (Node spareHost : spareHosts) {
List<Move> mitigation = capacitySolver.makeRoomFor(node, spareHost, hosts, List.of(), List.of());
if (mitigation == null) continue;
if (shortestMitigation == null || shortestMitigation.size() > mitigation.size())
shortestMitigation = mitigation;
}
if (shortestMitigation == null || shortestMitigation.isEmpty()) return Move.empty();
return shortestMitigation.get(0);
} | class SpareCapacityMaintainer extends NodeRepositoryMaintainer {
private final int maxIterations;
private final Deployer deployer;
private final Metric metric;
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval) {
this(deployer, nodeRepository, metric, interval,
10_000
);
}
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval,
int maxIterations) {
super(nodeRepository, interval);
this.deployer = deployer;
this.metric = metric;
this.maxIterations = maxIterations;
}
@Override
protected void maintain() {
if ( ! nodeRepository().zone().getCloud().allowHostSharing()) return;
CapacityChecker capacityChecker = new CapacityChecker(nodeRepository());
List<Node> overcommittedHosts = capacityChecker.findOvercommittedHosts();
if (overcommittedHosts.size() != 0) {
log.log(Level.WARNING, String.format("%d nodes are overcommitted! [ %s ]",
overcommittedHosts.size(),
overcommittedHosts.stream().map(Node::hostname).collect(Collectors.joining(", "))));
}
metric.set("overcommittedHosts", overcommittedHosts.size(), null);
Optional<CapacityChecker.HostFailurePath> failurePath = capacityChecker.worstCaseHostLossLeadingToFailure();
if (failurePath.isPresent()) {
int spareHostCapacity = failurePath.get().hostsCausingFailure.size() - 1;
if (spareHostCapacity == 0) {
Move move = findMitigatingMove(failurePath.get());
if (moving(move)) {
spareHostCapacity++;
}
}
metric.set("spareHostCapacity", spareHostCapacity, null);
}
}
private boolean moving(Move move) {
if (move.isEmpty()) return false;
if (move.node().allocation().get().membership().retired()) return true;
return move.execute(false, Agent.SpareCapacityMaintainer, deployer, metric, nodeRepository());
}
private static class CapacitySolver {
private final HostCapacity hostCapacity;
private final int maxIterations;
private int iterations = 0;
CapacitySolver(HostCapacity hostCapacity, int maxIterations) {
this.hostCapacity = hostCapacity;
this.maxIterations = maxIterations;
}
/** The map of subproblem solutions already found. The value is null when there is no solution. */
private Map<SolutionKey, List<Move>> solutions = new HashMap<>();
/**
* Finds the shortest sequence of moves which makes room for the given node on the given host,
* assuming the given moves already made over the given hosts' current allocation.
*
* @param node the node to make room for
* @param host the target host to make room on
* @param hosts the hosts onto which we can move nodes
* @param movesConsidered the moves already being considered to add as part of this scenario
* (after any moves made by this)
* @param movesMade the moves already made in this scenario
* @return the list of movesMade with the moves needed for this appended, in the order they should be performed,
* or null if no sequence could be found
*/
List<Move> makeRoomFor(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
SolutionKey solutionKey = new SolutionKey(node, host, movesConsidered, movesMade);
List<Move> solution = solutions.get(solutionKey);
if (solution == null) {
solution = findRoomFor(node, host, hosts, movesConsidered, movesMade);
solutions.put(solutionKey, solution);
}
return solution;
}
private List<Move> findRoomFor(Node node, Node host, List<Node> hosts,
List<Move> movesConsidered, List<Move> movesMade) {
if (iterations++ > maxIterations)
return null;
if ( ! host.resources().satisfies(node.resources())) return null;
NodeResources freeCapacity = freeCapacityWith(movesMade, host);
if (freeCapacity.satisfies(node.resources())) return List.of();
List<Move> shortest = null;
for (var i = subsets(hostCapacity.allNodes().childrenOf(host), 5); i.hasNext(); ) {
List<Node> childrenToMove = i.next();
if ( ! addResourcesOf(childrenToMove, freeCapacity).satisfies(node.resources())) continue;
List<Move> moves = move(childrenToMove, host, hosts, movesConsidered, movesMade);
if (moves == null) continue;
if (shortest == null || moves.size() < shortest.size())
shortest = moves;
}
if (shortest == null) return null;
return append(movesMade, shortest);
}
private List<Move> move(List<Node> nodes, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
List<Move> moves = new ArrayList<>();
for (Node childToMove : nodes) {
List<Move> childMoves = move(childToMove, host, hosts, movesConsidered, append(movesMade, moves));
if (childMoves == null) return null;
moves.addAll(childMoves);
}
return moves;
}
private List<Move> move(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
if (contains(node, movesConsidered)) return null;
if (contains(node, movesMade)) return null;
List<Move> shortest = null;
for (Node target : hosts) {
if (target.equals(host)) continue;
Move move = new Move(node, host, target);
List<Move> childMoves = makeRoomFor(node, target, hosts, append(movesConsidered, move), movesMade);
if (childMoves == null) continue;
if (shortest == null || shortest.size() > childMoves.size() + 1) {
shortest = new ArrayList<>(childMoves);
shortest.add(move);
}
}
return shortest;
}
private boolean contains(Node node, List<Move> moves) {
return moves.stream().anyMatch(move -> move.node().equals(node));
}
private NodeResources addResourcesOf(List<Node> nodes, NodeResources resources) {
for (Node node : nodes)
resources = resources.add(node.resources());
return resources;
}
private Iterator<List<Node>> subsets(NodeList nodes, int maxSize) {
return new SubsetIterator(nodes.asList(), maxSize);
}
private List<Move> append(List<Move> a, List<Move> b) {
List<Move> list = new ArrayList<>();
list.addAll(a);
list.addAll(b);
return list;
}
private List<Move> append(List<Move> moves, Move move) {
List<Move> list = new ArrayList<>(moves);
list.add(move);
return list;
}
private NodeResources freeCapacityWith(List<Move> moves, Node host) {
NodeResources resources = hostCapacity.freeCapacityOf(host);
for (Move move : moves) {
if ( ! move.toHost().equals(host)) continue;
resources = resources.subtract(move.node().resources());
}
for (Move move : moves) {
if ( ! move.fromHost().equals(host)) continue;
resources = resources.add(move.fromHost().resources());
}
return resources;
}
}
private static class SolutionKey {
private final Node node;
private final Node host;
private final List<Move> movesConsidered;
private final List<Move> movesMade;
private final int hash;
public SolutionKey(Node node, Node host, List<Move> movesConsidered, List<Move> movesMade) {
this.node = node;
this.host = host;
this.movesConsidered = movesConsidered;
this.movesMade = movesMade;
hash = Objects.hash(node, host, movesConsidered, movesMade);
}
@Override
public int hashCode() { return hash; }
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || o.getClass() != this.getClass()) return false;
SolutionKey other = (SolutionKey)o;
if ( ! other.node.equals(this.node)) return false;
if ( ! other.host.equals(this.host)) return false;
if ( ! other.movesConsidered.equals(this.movesConsidered)) return false;
if ( ! other.movesMade.equals(this.movesMade)) return false;
return true;
}
}
private static class SubsetIterator implements Iterator<List<Node>> {
private final List<Node> nodes;
private final int maxLength;
private int i = 0;
private List<Node> next = null;
public SubsetIterator(List<Node> nodes, int maxLength) {
this.nodes = new ArrayList<>(nodes.subList(0, Math.min(nodes.size(), 31)));
this.maxLength = maxLength;
}
@Override
public boolean hasNext() {
if (next != null) return true;
while (++i < 1<<nodes.size()) {
int ones = onesIn(i);
if (ones > maxLength) continue;
next = new ArrayList<>(ones);
for (int position = 0; position < nodes.size(); position++) {
if (hasOneAtPosition(position, i))
next.add(nodes.get(position));
}
return true;
}
return false;
}
@Override
public List<Node> next() {
if ( ! hasNext()) throw new IllegalStateException("No more elements");
var current = next;
next = null;
return current;
}
private boolean hasOneAtPosition(int position, int number) {
return (number & (1 << position)) > 0;
}
private int onesIn(int number) {
int ones = 0;
for (int position = 0; Math.pow(2, position) <= number; position++) {
if (hasOneAtPosition(position, number))
ones++;
}
return ones;
}
}
} | class SpareCapacityMaintainer extends NodeRepositoryMaintainer {
private final int maxIterations;
private final Deployer deployer;
private final Metric metric;
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval) {
this(deployer, nodeRepository, metric, interval,
10_000
);
}
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval,
int maxIterations) {
super(nodeRepository, interval);
this.deployer = deployer;
this.metric = metric;
this.maxIterations = maxIterations;
}
@Override
protected void maintain() {
if ( ! nodeRepository().zone().getCloud().allowHostSharing()) return;
CapacityChecker capacityChecker = new CapacityChecker(nodeRepository());
List<Node> overcommittedHosts = capacityChecker.findOvercommittedHosts();
if (overcommittedHosts.size() != 0) {
log.log(Level.WARNING, String.format("%d nodes are overcommitted! [ %s ]",
overcommittedHosts.size(),
overcommittedHosts.stream().map(Node::hostname).collect(Collectors.joining(", "))));
}
metric.set("overcommittedHosts", overcommittedHosts.size(), null);
Optional<CapacityChecker.HostFailurePath> failurePath = capacityChecker.worstCaseHostLossLeadingToFailure();
if (failurePath.isPresent()) {
int spareHostCapacity = failurePath.get().hostsCausingFailure.size() - 1;
if (spareHostCapacity == 0) {
Move move = findMitigatingMove(failurePath.get());
if (moving(move)) {
spareHostCapacity++;
}
}
metric.set("spareHostCapacity", spareHostCapacity, null);
}
}
private boolean moving(Move move) {
if (move.isEmpty()) return false;
if (move.node().allocation().get().membership().retired()) return true;
return move.execute(false, Agent.SpareCapacityMaintainer, deployer, metric, nodeRepository());
}
private static class CapacitySolver {
private final HostCapacity hostCapacity;
private final int maxIterations;
private int iterations = 0;
CapacitySolver(HostCapacity hostCapacity, int maxIterations) {
this.hostCapacity = hostCapacity;
this.maxIterations = maxIterations;
}
/** The map of subproblem solutions already found. The value is null when there is no solution. */
private Map<SolutionKey, List<Move>> solutions = new HashMap<>();
/**
* Finds the shortest sequence of moves which makes room for the given node on the given host,
* assuming the given moves already made over the given hosts' current allocation.
*
* @param node the node to make room for
* @param host the target host to make room on
* @param hosts the hosts onto which we can move nodes
* @param movesConsidered the moves already being considered to add as part of this scenario
* (after any moves made by this)
* @param movesMade the moves already made in this scenario
* @return the list of movesMade with the moves needed for this appended, in the order they should be performed,
* or null if no sequence could be found
*/
List<Move> makeRoomFor(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
SolutionKey solutionKey = new SolutionKey(node, host, movesConsidered, movesMade);
List<Move> solution = solutions.get(solutionKey);
if (solution == null) {
solution = findRoomFor(node, host, hosts, movesConsidered, movesMade);
solutions.put(solutionKey, solution);
}
return solution;
}
private List<Move> findRoomFor(Node node, Node host, List<Node> hosts,
List<Move> movesConsidered, List<Move> movesMade) {
if (iterations++ > maxIterations)
return null;
if ( ! host.resources().satisfies(node.resources())) return null;
NodeResources freeCapacity = freeCapacityWith(movesMade, host);
if (freeCapacity.satisfies(node.resources())) return List.of();
List<Move> shortest = null;
for (var i = subsets(hostCapacity.allNodes().childrenOf(host), 5); i.hasNext(); ) {
List<Node> childrenToMove = i.next();
if ( ! addResourcesOf(childrenToMove, freeCapacity).satisfies(node.resources())) continue;
List<Move> moves = move(childrenToMove, host, hosts, movesConsidered, movesMade);
if (moves == null) continue;
if (shortest == null || moves.size() < shortest.size())
shortest = moves;
}
if (shortest == null) return null;
return append(movesMade, shortest);
}
private List<Move> move(List<Node> nodes, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
List<Move> moves = new ArrayList<>();
for (Node childToMove : nodes) {
List<Move> childMoves = move(childToMove, host, hosts, movesConsidered, append(movesMade, moves));
if (childMoves == null) return null;
moves.addAll(childMoves);
}
return moves;
}
private List<Move> move(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
if (contains(node, movesConsidered)) return null;
if (contains(node, movesMade)) return null;
List<Move> shortest = null;
for (Node target : hosts) {
if (target.equals(host)) continue;
Move move = new Move(node, host, target);
List<Move> childMoves = makeRoomFor(node, target, hosts, append(movesConsidered, move), movesMade);
if (childMoves == null) continue;
if (shortest == null || shortest.size() > childMoves.size() + 1) {
shortest = new ArrayList<>(childMoves);
shortest.add(move);
}
}
return shortest;
}
private boolean contains(Node node, List<Move> moves) {
return moves.stream().anyMatch(move -> move.node().equals(node));
}
private NodeResources addResourcesOf(List<Node> nodes, NodeResources resources) {
for (Node node : nodes)
resources = resources.add(node.resources());
return resources;
}
private Iterator<List<Node>> subsets(NodeList nodes, int maxSize) {
return new SubsetIterator(nodes.asList(), maxSize);
}
private List<Move> append(List<Move> a, List<Move> b) {
List<Move> list = new ArrayList<>();
list.addAll(a);
list.addAll(b);
return list;
}
private List<Move> append(List<Move> moves, Move move) {
List<Move> list = new ArrayList<>(moves);
list.add(move);
return list;
}
private NodeResources freeCapacityWith(List<Move> moves, Node host) {
NodeResources resources = hostCapacity.freeCapacityOf(host);
for (Move move : moves) {
if ( ! move.toHost().equals(host)) continue;
resources = resources.subtract(move.node().resources());
}
for (Move move : moves) {
if ( ! move.fromHost().equals(host)) continue;
resources = resources.add(move.node().resources());
}
return resources;
}
}
private static class SolutionKey {
private final Node node;
private final Node host;
private final List<Move> movesConsidered;
private final List<Move> movesMade;
private final int hash;
public SolutionKey(Node node, Node host, List<Move> movesConsidered, List<Move> movesMade) {
this.node = node;
this.host = host;
this.movesConsidered = movesConsidered;
this.movesMade = movesMade;
hash = Objects.hash(node, host, movesConsidered, movesMade);
}
@Override
public int hashCode() { return hash; }
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || o.getClass() != this.getClass()) return false;
SolutionKey other = (SolutionKey)o;
if ( ! other.node.equals(this.node)) return false;
if ( ! other.host.equals(this.host)) return false;
if ( ! other.movesConsidered.equals(this.movesConsidered)) return false;
if ( ! other.movesMade.equals(this.movesMade)) return false;
return true;
}
}
private static class SubsetIterator implements Iterator<List<Node>> {
private final List<Node> nodes;
private final int maxLength;
private int i = 0;
private List<Node> next = null;
public SubsetIterator(List<Node> nodes, int maxLength) {
this.nodes = new ArrayList<>(nodes.subList(0, Math.min(nodes.size(), 31)));
this.maxLength = maxLength;
}
@Override
public boolean hasNext() {
if (next != null) return true;
while (++i < 1<<nodes.size()) {
int ones = Integer.bitCount(i);
if (ones > maxLength) continue;
next = new ArrayList<>(ones);
for (int position = 0; position < nodes.size(); position++) {
if (hasOneAtPosition(position, i))
next.add(nodes.get(position));
}
return true;
}
return false;
}
@Override
public List<Node> next() {
if ( ! hasNext()) throw new IllegalStateException("No more elements");
var current = next;
next = null;
return current;
}
private boolean hasOneAtPosition(int position, int number) {
return (number & (1 << position)) > 0;
}
}
} |
The second loop? This whole thing is in lieu of allocating properly, because here I want full control over where nodes are placed, without being dependent on constraints applied during allocation. The second loop is needed because setting nodes ready will remove the allocation if I set it at creation. | private void addNodes(int id, int count, NodeResources resources, int hostOffset) {
List<Node> nodes = new ArrayList<>();
ApplicationId application = ApplicationId.from("tenant" + id, "application" + id, "default");
for (int i = 0; i < count; i++) {
ClusterMembership membership = ClusterMembership.from(ClusterSpec.specification(ClusterSpec.Type.content, ClusterSpec.Id.from("cluster" + id))
.group(ClusterSpec.Group.from(0))
.vespaVersion("7")
.build(),
i);
Node node = nodeRepository.createNode("node" + nodeIndex,
"node" + nodeIndex + ".yahoo.com",
ipConfig(hostIndex + nodeIndex, false),
Optional.of("host" + ( hostOffset + i) + ".yahoo.com"),
new Flavor(resources),
Optional.empty(),
NodeType.tenant);
node = node.allocate(application, membership, node.resources(), Instant.now());
nodes.add(node);
nodeIndex++;
}
nodes = nodeRepository.addNodes(nodes, Agent.system);
for (int i = 0; i < count; i++) {
Node node = nodes.get(i);
ClusterMembership membership = ClusterMembership.from(ClusterSpec.specification(ClusterSpec.Type.content, ClusterSpec.Id.from("cluster" + id))
.group(ClusterSpec.Group.from(0))
.vespaVersion("7")
.build(),
i);
node = node.allocate(application, membership, node.resources(), Instant.now());
nodes.set(i, node);
}
nodes = nodeRepository.reserve(nodes);
var transaction = new NestedTransaction();
nodes = nodeRepository.activate(nodes, transaction);
transaction.commit();
} | for (int i = 0; i < count; i++) { | private void addNodes(int id, int count, NodeResources resources, int hostOffset) {
List<Node> nodes = new ArrayList<>();
ApplicationId application = ApplicationId.from("tenant" + id, "application" + id, "default");
for (int i = 0; i < count; i++) {
ClusterMembership membership = ClusterMembership.from(ClusterSpec.specification(ClusterSpec.Type.content, ClusterSpec.Id.from("cluster" + id))
.group(ClusterSpec.Group.from(0))
.vespaVersion("7")
.build(),
i);
Node node = nodeRepository.createNode("node" + nodeIndex,
"node" + nodeIndex + ".yahoo.com",
ipConfig(hostIndex + nodeIndex, false),
Optional.of("host" + ( hostOffset + i) + ".yahoo.com"),
new Flavor(resources),
Optional.empty(),
NodeType.tenant);
node = node.allocate(application, membership, node.resources(), Instant.now());
nodes.add(node);
nodeIndex++;
}
nodes = nodeRepository.addNodes(nodes, Agent.system);
for (int i = 0; i < count; i++) {
Node node = nodes.get(i);
ClusterMembership membership = ClusterMembership.from(ClusterSpec.specification(ClusterSpec.Type.content, ClusterSpec.Id.from("cluster" + id))
.group(ClusterSpec.Group.from(0))
.vespaVersion("7")
.build(),
i);
node = node.allocate(application, membership, node.resources(), Instant.now());
nodes.set(i, node);
}
nodes = nodeRepository.reserve(nodes);
var transaction = new NestedTransaction();
nodes = nodeRepository.activate(nodes, transaction);
transaction.commit();
} | class SpareCapacityMaintainerTester {
NodeRepository nodeRepository;
MockDeployer deployer;
TestMetric metric = new TestMetric();
SpareCapacityMaintainer maintainer;
private int hostIndex = 0;
private int nodeIndex = 0;
private SpareCapacityMaintainerTester() {
this(1000);
}
private SpareCapacityMaintainerTester(int maxIterations) {
NodeFlavors flavors = new NodeFlavors(new FlavorConfigBuilder().build());
nodeRepository = new NodeRepository(flavors,
new EmptyProvisionServiceProvider().getHostResourcesCalculator(),
new MockCurator(),
new ManualClock(),
new Zone(Environment.prod, RegionName.from("us-east-3")),
new MockNameResolver().mockAnyLookup(),
DockerImage.fromString("docker-registry.domain.tld:8080/dist/vespa"), true, false);
deployer = new MockDeployer(nodeRepository);
maintainer = new SpareCapacityMaintainer(deployer, nodeRepository, metric, Duration.ofDays(1), maxIterations);
}
private void addHosts(int count, NodeResources resources) {
List<Node> hosts = new ArrayList<>();
for (int i = 0; i < count; i++) {
Node host = nodeRepository.createNode("host" + hostIndex,
"host" + hostIndex + ".yahoo.com",
ipConfig(hostIndex + nodeIndex, true),
Optional.empty(),
new Flavor(resources),
Optional.empty(),
NodeType.host);
hosts.add(host);
hostIndex++;
}
hosts = nodeRepository.addNodes(hosts, Agent.system);
hosts = nodeRepository.setReady(hosts, Agent.system, "Test");
var transaction = new NestedTransaction();
nodeRepository.activate(hosts, transaction);
transaction.commit();
}
private IP.Config ipConfig(int id, boolean host) {
return new IP.Config(Set.of(String.format("%04X::%04X", id, 0)),
host ? IntStream.range(0, 10)
.mapToObj(n -> String.format("%04X::%04X", id, n))
.collect(Collectors.toSet())
: Set.of());
}
private void dumpState() {
for (Node host : nodeRepository.list().hosts().asList()) {
System.out.println("Host " + host.hostname() + " " + host.resources());
for (Node node : nodeRepository.list().childrenOf(host).asList())
System.out.println(" Node " + node.hostname() + " " + node.resources() + " allocation " +node.allocation());
}
}
} | class SpareCapacityMaintainerTester {
NodeRepository nodeRepository;
MockDeployer deployer;
TestMetric metric = new TestMetric();
SpareCapacityMaintainer maintainer;
private int hostIndex = 0;
private int nodeIndex = 0;
private SpareCapacityMaintainerTester() {
this(1000);
}
private SpareCapacityMaintainerTester(int maxIterations) {
NodeFlavors flavors = new NodeFlavors(new FlavorConfigBuilder().build());
nodeRepository = new NodeRepository(flavors,
new EmptyProvisionServiceProvider().getHostResourcesCalculator(),
new MockCurator(),
new ManualClock(),
new Zone(Environment.prod, RegionName.from("us-east-3")),
new MockNameResolver().mockAnyLookup(),
DockerImage.fromString("docker-registry.domain.tld:8080/dist/vespa"), true, false);
deployer = new MockDeployer(nodeRepository);
maintainer = new SpareCapacityMaintainer(deployer, nodeRepository, metric, Duration.ofDays(1), maxIterations);
}
private void addHosts(int count, NodeResources resources) {
List<Node> hosts = new ArrayList<>();
for (int i = 0; i < count; i++) {
Node host = nodeRepository.createNode("host" + hostIndex,
"host" + hostIndex + ".yahoo.com",
ipConfig(hostIndex + nodeIndex, true),
Optional.empty(),
new Flavor(resources),
Optional.empty(),
NodeType.host);
hosts.add(host);
hostIndex++;
}
hosts = nodeRepository.addNodes(hosts, Agent.system);
hosts = nodeRepository.setReady(hosts, Agent.system, "Test");
var transaction = new NestedTransaction();
nodeRepository.activate(hosts, transaction);
transaction.commit();
}
private IP.Config ipConfig(int id, boolean host) {
return new IP.Config(Set.of(String.format("%04X::%04X", id, 0)),
host ? IntStream.range(0, 10)
.mapToObj(n -> String.format("%04X::%04X", id, n))
.collect(Collectors.toSet())
: Set.of());
}
private void dumpState() {
for (Node host : nodeRepository.list().hosts().asList()) {
System.out.println("Host " + host.hostname() + " " + host.resources());
for (Node node : nodeRepository.list().childrenOf(host).asList())
System.out.println(" Node " + node.hostname() + " " + node.resources() + " allocation " +node.allocation());
}
}
} |
Empty list means the solution needs no moves. null means there are no solutions. I don't understand the second paragraph - if it's null we continue because we found no solution. Otherwise we compare it to the current best, if any. | private Move findMitigatingMove(CapacityChecker.HostFailurePath failurePath) {
Optional<Node> nodeWhichCantMove = failurePath.failureReason.tenant;
if (nodeWhichCantMove.isEmpty()) return Move.empty();
Node node = nodeWhichCantMove.get();
NodeList allNodes = nodeRepository().list();
HostCapacity hostCapacity = new HostCapacity(allNodes, nodeRepository().resourcesCalculator());
Set<Node> spareHosts = hostCapacity.findSpareHosts(allNodes.hosts().satisfies(node.resources()).asList(), 2);
List<Node> hosts = allNodes.hosts().except(spareHosts).asList();
CapacitySolver capacitySolver = new CapacitySolver(hostCapacity, maxIterations);
List<Move> shortestMitigation = null;
for (Node spareHost : spareHosts) {
List<Move> mitigation = capacitySolver.makeRoomFor(node, spareHost, hosts, List.of(), List.of());
if (mitigation == null) continue;
if (shortestMitigation == null || shortestMitigation.size() > mitigation.size())
shortestMitigation = mitigation;
}
if (shortestMitigation == null || shortestMitigation.isEmpty()) return Move.empty();
return shortestMitigation.get(0);
} | if (shortestMitigation == null || shortestMitigation.size() > mitigation.size()) | private Move findMitigatingMove(CapacityChecker.HostFailurePath failurePath) {
Optional<Node> nodeWhichCantMove = failurePath.failureReason.tenant;
if (nodeWhichCantMove.isEmpty()) return Move.empty();
Node node = nodeWhichCantMove.get();
NodeList allNodes = nodeRepository().list();
HostCapacity hostCapacity = new HostCapacity(allNodes, nodeRepository().resourcesCalculator());
Set<Node> spareHosts = hostCapacity.findSpareHosts(allNodes.hosts().satisfies(node.resources()).asList(), 2);
List<Node> hosts = allNodes.hosts().except(spareHosts).asList();
CapacitySolver capacitySolver = new CapacitySolver(hostCapacity, maxIterations);
List<Move> shortestMitigation = null;
for (Node spareHost : spareHosts) {
List<Move> mitigation = capacitySolver.makeRoomFor(node, spareHost, hosts, List.of(), List.of());
if (mitigation == null) continue;
if (shortestMitigation == null || shortestMitigation.size() > mitigation.size())
shortestMitigation = mitigation;
}
if (shortestMitigation == null || shortestMitigation.isEmpty()) return Move.empty();
return shortestMitigation.get(0);
} | class SpareCapacityMaintainer extends NodeRepositoryMaintainer {
private final int maxIterations;
private final Deployer deployer;
private final Metric metric;
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval) {
this(deployer, nodeRepository, metric, interval,
10_000
);
}
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval,
int maxIterations) {
super(nodeRepository, interval);
this.deployer = deployer;
this.metric = metric;
this.maxIterations = maxIterations;
}
@Override
protected void maintain() {
if ( ! nodeRepository().zone().getCloud().allowHostSharing()) return;
CapacityChecker capacityChecker = new CapacityChecker(nodeRepository());
List<Node> overcommittedHosts = capacityChecker.findOvercommittedHosts();
if (overcommittedHosts.size() != 0) {
log.log(Level.WARNING, String.format("%d nodes are overcommitted! [ %s ]",
overcommittedHosts.size(),
overcommittedHosts.stream().map(Node::hostname).collect(Collectors.joining(", "))));
}
metric.set("overcommittedHosts", overcommittedHosts.size(), null);
Optional<CapacityChecker.HostFailurePath> failurePath = capacityChecker.worstCaseHostLossLeadingToFailure();
if (failurePath.isPresent()) {
int spareHostCapacity = failurePath.get().hostsCausingFailure.size() - 1;
if (spareHostCapacity == 0) {
Move move = findMitigatingMove(failurePath.get());
if (moving(move)) {
spareHostCapacity++;
}
}
metric.set("spareHostCapacity", spareHostCapacity, null);
}
}
private boolean moving(Move move) {
if (move.isEmpty()) return false;
if (move.node().allocation().get().membership().retired()) return true;
return move.execute(false, Agent.SpareCapacityMaintainer, deployer, metric, nodeRepository());
}
private static class CapacitySolver {
private final HostCapacity hostCapacity;
private final int maxIterations;
private int iterations = 0;
CapacitySolver(HostCapacity hostCapacity, int maxIterations) {
this.hostCapacity = hostCapacity;
this.maxIterations = maxIterations;
}
/** The map of subproblem solutions already found. The value is null when there is no solution. */
private Map<SolutionKey, List<Move>> solutions = new HashMap<>();
/**
* Finds the shortest sequence of moves which makes room for the given node on the given host,
* assuming the given moves already made over the given hosts' current allocation.
*
* @param node the node to make room for
* @param host the target host to make room on
* @param hosts the hosts onto which we can move nodes
* @param movesConsidered the moves already being considered to add as part of this scenario
* (after any moves made by this)
* @param movesMade the moves already made in this scenario
* @return the list of movesMade with the moves needed for this appended, in the order they should be performed,
* or null if no sequence could be found
*/
List<Move> makeRoomFor(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
SolutionKey solutionKey = new SolutionKey(node, host, movesConsidered, movesMade);
List<Move> solution = solutions.get(solutionKey);
if (solution == null) {
solution = findRoomFor(node, host, hosts, movesConsidered, movesMade);
solutions.put(solutionKey, solution);
}
return solution;
}
private List<Move> findRoomFor(Node node, Node host, List<Node> hosts,
List<Move> movesConsidered, List<Move> movesMade) {
if (iterations++ > maxIterations)
return null;
if ( ! host.resources().satisfies(node.resources())) return null;
NodeResources freeCapacity = freeCapacityWith(movesMade, host);
if (freeCapacity.satisfies(node.resources())) return List.of();
List<Move> shortest = null;
for (var i = subsets(hostCapacity.allNodes().childrenOf(host), 5); i.hasNext(); ) {
List<Node> childrenToMove = i.next();
if ( ! addResourcesOf(childrenToMove, freeCapacity).satisfies(node.resources())) continue;
List<Move> moves = move(childrenToMove, host, hosts, movesConsidered, movesMade);
if (moves == null) continue;
if (shortest == null || moves.size() < shortest.size())
shortest = moves;
}
if (shortest == null) return null;
return append(movesMade, shortest);
}
private List<Move> move(List<Node> nodes, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
List<Move> moves = new ArrayList<>();
for (Node childToMove : nodes) {
List<Move> childMoves = move(childToMove, host, hosts, movesConsidered, append(movesMade, moves));
if (childMoves == null) return null;
moves.addAll(childMoves);
}
return moves;
}
private List<Move> move(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
if (contains(node, movesConsidered)) return null;
if (contains(node, movesMade)) return null;
List<Move> shortest = null;
for (Node target : hosts) {
if (target.equals(host)) continue;
Move move = new Move(node, host, target);
List<Move> childMoves = makeRoomFor(node, target, hosts, append(movesConsidered, move), movesMade);
if (childMoves == null) continue;
if (shortest == null || shortest.size() > childMoves.size() + 1) {
shortest = new ArrayList<>(childMoves);
shortest.add(move);
}
}
return shortest;
}
private boolean contains(Node node, List<Move> moves) {
return moves.stream().anyMatch(move -> move.node().equals(node));
}
private NodeResources addResourcesOf(List<Node> nodes, NodeResources resources) {
for (Node node : nodes)
resources = resources.add(node.resources());
return resources;
}
private Iterator<List<Node>> subsets(NodeList nodes, int maxSize) {
return new SubsetIterator(nodes.asList(), maxSize);
}
private List<Move> append(List<Move> a, List<Move> b) {
List<Move> list = new ArrayList<>();
list.addAll(a);
list.addAll(b);
return list;
}
private List<Move> append(List<Move> moves, Move move) {
List<Move> list = new ArrayList<>(moves);
list.add(move);
return list;
}
private NodeResources freeCapacityWith(List<Move> moves, Node host) {
NodeResources resources = hostCapacity.freeCapacityOf(host);
for (Move move : moves) {
if ( ! move.toHost().equals(host)) continue;
resources = resources.subtract(move.node().resources());
}
for (Move move : moves) {
if ( ! move.fromHost().equals(host)) continue;
resources = resources.add(move.fromHost().resources());
}
return resources;
}
}
private static class SolutionKey {
private final Node node;
private final Node host;
private final List<Move> movesConsidered;
private final List<Move> movesMade;
private final int hash;
public SolutionKey(Node node, Node host, List<Move> movesConsidered, List<Move> movesMade) {
this.node = node;
this.host = host;
this.movesConsidered = movesConsidered;
this.movesMade = movesMade;
hash = Objects.hash(node, host, movesConsidered, movesMade);
}
@Override
public int hashCode() { return hash; }
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || o.getClass() != this.getClass()) return false;
SolutionKey other = (SolutionKey)o;
if ( ! other.node.equals(this.node)) return false;
if ( ! other.host.equals(this.host)) return false;
if ( ! other.movesConsidered.equals(this.movesConsidered)) return false;
if ( ! other.movesMade.equals(this.movesMade)) return false;
return true;
}
}
private static class SubsetIterator implements Iterator<List<Node>> {
private final List<Node> nodes;
private final int maxLength;
private int i = 0;
private List<Node> next = null;
public SubsetIterator(List<Node> nodes, int maxLength) {
this.nodes = new ArrayList<>(nodes.subList(0, Math.min(nodes.size(), 31)));
this.maxLength = maxLength;
}
@Override
public boolean hasNext() {
if (next != null) return true;
while (++i < 1<<nodes.size()) {
int ones = onesIn(i);
if (ones > maxLength) continue;
next = new ArrayList<>(ones);
for (int position = 0; position < nodes.size(); position++) {
if (hasOneAtPosition(position, i))
next.add(nodes.get(position));
}
return true;
}
return false;
}
@Override
public List<Node> next() {
if ( ! hasNext()) throw new IllegalStateException("No more elements");
var current = next;
next = null;
return current;
}
private boolean hasOneAtPosition(int position, int number) {
return (number & (1 << position)) > 0;
}
private int onesIn(int number) {
int ones = 0;
for (int position = 0; Math.pow(2, position) <= number; position++) {
if (hasOneAtPosition(position, number))
ones++;
}
return ones;
}
}
} | class SpareCapacityMaintainer extends NodeRepositoryMaintainer {
private final int maxIterations;
private final Deployer deployer;
private final Metric metric;
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval) {
this(deployer, nodeRepository, metric, interval,
10_000
);
}
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval,
int maxIterations) {
super(nodeRepository, interval);
this.deployer = deployer;
this.metric = metric;
this.maxIterations = maxIterations;
}
@Override
protected void maintain() {
if ( ! nodeRepository().zone().getCloud().allowHostSharing()) return;
CapacityChecker capacityChecker = new CapacityChecker(nodeRepository());
List<Node> overcommittedHosts = capacityChecker.findOvercommittedHosts();
if (overcommittedHosts.size() != 0) {
log.log(Level.WARNING, String.format("%d nodes are overcommitted! [ %s ]",
overcommittedHosts.size(),
overcommittedHosts.stream().map(Node::hostname).collect(Collectors.joining(", "))));
}
metric.set("overcommittedHosts", overcommittedHosts.size(), null);
Optional<CapacityChecker.HostFailurePath> failurePath = capacityChecker.worstCaseHostLossLeadingToFailure();
if (failurePath.isPresent()) {
int spareHostCapacity = failurePath.get().hostsCausingFailure.size() - 1;
if (spareHostCapacity == 0) {
Move move = findMitigatingMove(failurePath.get());
if (moving(move)) {
spareHostCapacity++;
}
}
metric.set("spareHostCapacity", spareHostCapacity, null);
}
}
private boolean moving(Move move) {
if (move.isEmpty()) return false;
if (move.node().allocation().get().membership().retired()) return true;
return move.execute(false, Agent.SpareCapacityMaintainer, deployer, metric, nodeRepository());
}
private static class CapacitySolver {
private final HostCapacity hostCapacity;
private final int maxIterations;
private int iterations = 0;
CapacitySolver(HostCapacity hostCapacity, int maxIterations) {
this.hostCapacity = hostCapacity;
this.maxIterations = maxIterations;
}
/** The map of subproblem solutions already found. The value is null when there is no solution. */
private Map<SolutionKey, List<Move>> solutions = new HashMap<>();
/**
* Finds the shortest sequence of moves which makes room for the given node on the given host,
* assuming the given moves already made over the given hosts' current allocation.
*
* @param node the node to make room for
* @param host the target host to make room on
* @param hosts the hosts onto which we can move nodes
* @param movesConsidered the moves already being considered to add as part of this scenario
* (after any moves made by this)
* @param movesMade the moves already made in this scenario
* @return the list of movesMade with the moves needed for this appended, in the order they should be performed,
* or null if no sequence could be found
*/
List<Move> makeRoomFor(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
SolutionKey solutionKey = new SolutionKey(node, host, movesConsidered, movesMade);
List<Move> solution = solutions.get(solutionKey);
if (solution == null) {
solution = findRoomFor(node, host, hosts, movesConsidered, movesMade);
solutions.put(solutionKey, solution);
}
return solution;
}
private List<Move> findRoomFor(Node node, Node host, List<Node> hosts,
List<Move> movesConsidered, List<Move> movesMade) {
if (iterations++ > maxIterations)
return null;
if ( ! host.resources().satisfies(node.resources())) return null;
NodeResources freeCapacity = freeCapacityWith(movesMade, host);
if (freeCapacity.satisfies(node.resources())) return List.of();
List<Move> shortest = null;
for (var i = subsets(hostCapacity.allNodes().childrenOf(host), 5); i.hasNext(); ) {
List<Node> childrenToMove = i.next();
if ( ! addResourcesOf(childrenToMove, freeCapacity).satisfies(node.resources())) continue;
List<Move> moves = move(childrenToMove, host, hosts, movesConsidered, movesMade);
if (moves == null) continue;
if (shortest == null || moves.size() < shortest.size())
shortest = moves;
}
if (shortest == null) return null;
return append(movesMade, shortest);
}
private List<Move> move(List<Node> nodes, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
List<Move> moves = new ArrayList<>();
for (Node childToMove : nodes) {
List<Move> childMoves = move(childToMove, host, hosts, movesConsidered, append(movesMade, moves));
if (childMoves == null) return null;
moves.addAll(childMoves);
}
return moves;
}
private List<Move> move(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
if (contains(node, movesConsidered)) return null;
if (contains(node, movesMade)) return null;
List<Move> shortest = null;
for (Node target : hosts) {
if (target.equals(host)) continue;
Move move = new Move(node, host, target);
List<Move> childMoves = makeRoomFor(node, target, hosts, append(movesConsidered, move), movesMade);
if (childMoves == null) continue;
if (shortest == null || shortest.size() > childMoves.size() + 1) {
shortest = new ArrayList<>(childMoves);
shortest.add(move);
}
}
return shortest;
}
private boolean contains(Node node, List<Move> moves) {
return moves.stream().anyMatch(move -> move.node().equals(node));
}
private NodeResources addResourcesOf(List<Node> nodes, NodeResources resources) {
for (Node node : nodes)
resources = resources.add(node.resources());
return resources;
}
private Iterator<List<Node>> subsets(NodeList nodes, int maxSize) {
return new SubsetIterator(nodes.asList(), maxSize);
}
private List<Move> append(List<Move> a, List<Move> b) {
List<Move> list = new ArrayList<>();
list.addAll(a);
list.addAll(b);
return list;
}
private List<Move> append(List<Move> moves, Move move) {
List<Move> list = new ArrayList<>(moves);
list.add(move);
return list;
}
private NodeResources freeCapacityWith(List<Move> moves, Node host) {
NodeResources resources = hostCapacity.freeCapacityOf(host);
for (Move move : moves) {
if ( ! move.toHost().equals(host)) continue;
resources = resources.subtract(move.node().resources());
}
for (Move move : moves) {
if ( ! move.fromHost().equals(host)) continue;
resources = resources.add(move.node().resources());
}
return resources;
}
}
private static class SolutionKey {
private final Node node;
private final Node host;
private final List<Move> movesConsidered;
private final List<Move> movesMade;
private final int hash;
public SolutionKey(Node node, Node host, List<Move> movesConsidered, List<Move> movesMade) {
this.node = node;
this.host = host;
this.movesConsidered = movesConsidered;
this.movesMade = movesMade;
hash = Objects.hash(node, host, movesConsidered, movesMade);
}
@Override
public int hashCode() { return hash; }
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || o.getClass() != this.getClass()) return false;
SolutionKey other = (SolutionKey)o;
if ( ! other.node.equals(this.node)) return false;
if ( ! other.host.equals(this.host)) return false;
if ( ! other.movesConsidered.equals(this.movesConsidered)) return false;
if ( ! other.movesMade.equals(this.movesMade)) return false;
return true;
}
}
private static class SubsetIterator implements Iterator<List<Node>> {
private final List<Node> nodes;
private final int maxLength;
private int i = 0;
private List<Node> next = null;
public SubsetIterator(List<Node> nodes, int maxLength) {
this.nodes = new ArrayList<>(nodes.subList(0, Math.min(nodes.size(), 31)));
this.maxLength = maxLength;
}
@Override
public boolean hasNext() {
if (next != null) return true;
while (++i < 1<<nodes.size()) {
int ones = Integer.bitCount(i);
if (ones > maxLength) continue;
next = new ArrayList<>(ones);
for (int position = 0; position < nodes.size(); position++) {
if (hasOneAtPosition(position, i))
next.add(nodes.get(position));
}
return true;
}
return false;
}
@Override
public List<Node> next() {
if ( ! hasNext()) throw new IllegalStateException("No more elements");
var current = next;
next = null;
return current;
}
private boolean hasOneAtPosition(int position, int number) {
return (number & (1 << position)) > 0;
}
}
} |
If `makeRoomFor()` returns empty list, it will be set as the `shortestMitigation` since `shortestMitigation.size() > mitigation.size()` == `shortestMitigation.size() > 0`, but then 2 lines below, if `shortestMitigation.isEmpty()` we return `Move.empty()`. So wouldn't it be better to change this if to ``` if (shortestMitigation == null || (shortestMitigation.size() > mitigation.size() && !mitigation.isEmpty())) ``` ? | private Move findMitigatingMove(CapacityChecker.HostFailurePath failurePath) {
Optional<Node> nodeWhichCantMove = failurePath.failureReason.tenant;
if (nodeWhichCantMove.isEmpty()) return Move.empty();
Node node = nodeWhichCantMove.get();
NodeList allNodes = nodeRepository().list();
HostCapacity hostCapacity = new HostCapacity(allNodes, nodeRepository().resourcesCalculator());
Set<Node> spareHosts = hostCapacity.findSpareHosts(allNodes.hosts().satisfies(node.resources()).asList(), 2);
List<Node> hosts = allNodes.hosts().except(spareHosts).asList();
CapacitySolver capacitySolver = new CapacitySolver(hostCapacity, maxIterations);
List<Move> shortestMitigation = null;
for (Node spareHost : spareHosts) {
List<Move> mitigation = capacitySolver.makeRoomFor(node, spareHost, hosts, List.of(), List.of());
if (mitigation == null) continue;
if (shortestMitigation == null || shortestMitigation.size() > mitigation.size())
shortestMitigation = mitigation;
}
if (shortestMitigation == null || shortestMitigation.isEmpty()) return Move.empty();
return shortestMitigation.get(0);
} | if (shortestMitigation == null || shortestMitigation.size() > mitigation.size()) | private Move findMitigatingMove(CapacityChecker.HostFailurePath failurePath) {
Optional<Node> nodeWhichCantMove = failurePath.failureReason.tenant;
if (nodeWhichCantMove.isEmpty()) return Move.empty();
Node node = nodeWhichCantMove.get();
NodeList allNodes = nodeRepository().list();
HostCapacity hostCapacity = new HostCapacity(allNodes, nodeRepository().resourcesCalculator());
Set<Node> spareHosts = hostCapacity.findSpareHosts(allNodes.hosts().satisfies(node.resources()).asList(), 2);
List<Node> hosts = allNodes.hosts().except(spareHosts).asList();
CapacitySolver capacitySolver = new CapacitySolver(hostCapacity, maxIterations);
List<Move> shortestMitigation = null;
for (Node spareHost : spareHosts) {
List<Move> mitigation = capacitySolver.makeRoomFor(node, spareHost, hosts, List.of(), List.of());
if (mitigation == null) continue;
if (shortestMitigation == null || shortestMitigation.size() > mitigation.size())
shortestMitigation = mitigation;
}
if (shortestMitigation == null || shortestMitigation.isEmpty()) return Move.empty();
return shortestMitigation.get(0);
} | class SpareCapacityMaintainer extends NodeRepositoryMaintainer {
private final int maxIterations;
private final Deployer deployer;
private final Metric metric;
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval) {
this(deployer, nodeRepository, metric, interval,
10_000
);
}
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval,
int maxIterations) {
super(nodeRepository, interval);
this.deployer = deployer;
this.metric = metric;
this.maxIterations = maxIterations;
}
@Override
protected void maintain() {
if ( ! nodeRepository().zone().getCloud().allowHostSharing()) return;
CapacityChecker capacityChecker = new CapacityChecker(nodeRepository());
List<Node> overcommittedHosts = capacityChecker.findOvercommittedHosts();
if (overcommittedHosts.size() != 0) {
log.log(Level.WARNING, String.format("%d nodes are overcommitted! [ %s ]",
overcommittedHosts.size(),
overcommittedHosts.stream().map(Node::hostname).collect(Collectors.joining(", "))));
}
metric.set("overcommittedHosts", overcommittedHosts.size(), null);
Optional<CapacityChecker.HostFailurePath> failurePath = capacityChecker.worstCaseHostLossLeadingToFailure();
if (failurePath.isPresent()) {
int spareHostCapacity = failurePath.get().hostsCausingFailure.size() - 1;
if (spareHostCapacity == 0) {
Move move = findMitigatingMove(failurePath.get());
if (moving(move)) {
spareHostCapacity++;
}
}
metric.set("spareHostCapacity", spareHostCapacity, null);
}
}
private boolean moving(Move move) {
if (move.isEmpty()) return false;
if (move.node().allocation().get().membership().retired()) return true;
return move.execute(false, Agent.SpareCapacityMaintainer, deployer, metric, nodeRepository());
}
private static class CapacitySolver {
private final HostCapacity hostCapacity;
private final int maxIterations;
private int iterations = 0;
CapacitySolver(HostCapacity hostCapacity, int maxIterations) {
this.hostCapacity = hostCapacity;
this.maxIterations = maxIterations;
}
/** The map of subproblem solutions already found. The value is null when there is no solution. */
private Map<SolutionKey, List<Move>> solutions = new HashMap<>();
/**
* Finds the shortest sequence of moves which makes room for the given node on the given host,
* assuming the given moves already made over the given hosts' current allocation.
*
* @param node the node to make room for
* @param host the target host to make room on
* @param hosts the hosts onto which we can move nodes
* @param movesConsidered the moves already being considered to add as part of this scenario
* (after any moves made by this)
* @param movesMade the moves already made in this scenario
* @return the list of movesMade with the moves needed for this appended, in the order they should be performed,
* or null if no sequence could be found
*/
List<Move> makeRoomFor(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
SolutionKey solutionKey = new SolutionKey(node, host, movesConsidered, movesMade);
List<Move> solution = solutions.get(solutionKey);
if (solution == null) {
solution = findRoomFor(node, host, hosts, movesConsidered, movesMade);
solutions.put(solutionKey, solution);
}
return solution;
}
private List<Move> findRoomFor(Node node, Node host, List<Node> hosts,
List<Move> movesConsidered, List<Move> movesMade) {
if (iterations++ > maxIterations)
return null;
if ( ! host.resources().satisfies(node.resources())) return null;
NodeResources freeCapacity = freeCapacityWith(movesMade, host);
if (freeCapacity.satisfies(node.resources())) return List.of();
List<Move> shortest = null;
for (var i = subsets(hostCapacity.allNodes().childrenOf(host), 5); i.hasNext(); ) {
List<Node> childrenToMove = i.next();
if ( ! addResourcesOf(childrenToMove, freeCapacity).satisfies(node.resources())) continue;
List<Move> moves = move(childrenToMove, host, hosts, movesConsidered, movesMade);
if (moves == null) continue;
if (shortest == null || moves.size() < shortest.size())
shortest = moves;
}
if (shortest == null) return null;
return append(movesMade, shortest);
}
private List<Move> move(List<Node> nodes, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
List<Move> moves = new ArrayList<>();
for (Node childToMove : nodes) {
List<Move> childMoves = move(childToMove, host, hosts, movesConsidered, append(movesMade, moves));
if (childMoves == null) return null;
moves.addAll(childMoves);
}
return moves;
}
private List<Move> move(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
if (contains(node, movesConsidered)) return null;
if (contains(node, movesMade)) return null;
List<Move> shortest = null;
for (Node target : hosts) {
if (target.equals(host)) continue;
Move move = new Move(node, host, target);
List<Move> childMoves = makeRoomFor(node, target, hosts, append(movesConsidered, move), movesMade);
if (childMoves == null) continue;
if (shortest == null || shortest.size() > childMoves.size() + 1) {
shortest = new ArrayList<>(childMoves);
shortest.add(move);
}
}
return shortest;
}
private boolean contains(Node node, List<Move> moves) {
return moves.stream().anyMatch(move -> move.node().equals(node));
}
private NodeResources addResourcesOf(List<Node> nodes, NodeResources resources) {
for (Node node : nodes)
resources = resources.add(node.resources());
return resources;
}
private Iterator<List<Node>> subsets(NodeList nodes, int maxSize) {
return new SubsetIterator(nodes.asList(), maxSize);
}
private List<Move> append(List<Move> a, List<Move> b) {
List<Move> list = new ArrayList<>();
list.addAll(a);
list.addAll(b);
return list;
}
private List<Move> append(List<Move> moves, Move move) {
List<Move> list = new ArrayList<>(moves);
list.add(move);
return list;
}
private NodeResources freeCapacityWith(List<Move> moves, Node host) {
NodeResources resources = hostCapacity.freeCapacityOf(host);
for (Move move : moves) {
if ( ! move.toHost().equals(host)) continue;
resources = resources.subtract(move.node().resources());
}
for (Move move : moves) {
if ( ! move.fromHost().equals(host)) continue;
resources = resources.add(move.fromHost().resources());
}
return resources;
}
}
private static class SolutionKey {
private final Node node;
private final Node host;
private final List<Move> movesConsidered;
private final List<Move> movesMade;
private final int hash;
public SolutionKey(Node node, Node host, List<Move> movesConsidered, List<Move> movesMade) {
this.node = node;
this.host = host;
this.movesConsidered = movesConsidered;
this.movesMade = movesMade;
hash = Objects.hash(node, host, movesConsidered, movesMade);
}
@Override
public int hashCode() { return hash; }
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || o.getClass() != this.getClass()) return false;
SolutionKey other = (SolutionKey)o;
if ( ! other.node.equals(this.node)) return false;
if ( ! other.host.equals(this.host)) return false;
if ( ! other.movesConsidered.equals(this.movesConsidered)) return false;
if ( ! other.movesMade.equals(this.movesMade)) return false;
return true;
}
}
private static class SubsetIterator implements Iterator<List<Node>> {
private final List<Node> nodes;
private final int maxLength;
private int i = 0;
private List<Node> next = null;
public SubsetIterator(List<Node> nodes, int maxLength) {
this.nodes = new ArrayList<>(nodes.subList(0, Math.min(nodes.size(), 31)));
this.maxLength = maxLength;
}
@Override
public boolean hasNext() {
if (next != null) return true;
while (++i < 1<<nodes.size()) {
int ones = onesIn(i);
if (ones > maxLength) continue;
next = new ArrayList<>(ones);
for (int position = 0; position < nodes.size(); position++) {
if (hasOneAtPosition(position, i))
next.add(nodes.get(position));
}
return true;
}
return false;
}
@Override
public List<Node> next() {
if ( ! hasNext()) throw new IllegalStateException("No more elements");
var current = next;
next = null;
return current;
}
private boolean hasOneAtPosition(int position, int number) {
return (number & (1 << position)) > 0;
}
private int onesIn(int number) {
int ones = 0;
for (int position = 0; Math.pow(2, position) <= number; position++) {
if (hasOneAtPosition(position, number))
ones++;
}
return ones;
}
}
} | class SpareCapacityMaintainer extends NodeRepositoryMaintainer {
private final int maxIterations;
private final Deployer deployer;
private final Metric metric;
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval) {
this(deployer, nodeRepository, metric, interval,
10_000
);
}
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval,
int maxIterations) {
super(nodeRepository, interval);
this.deployer = deployer;
this.metric = metric;
this.maxIterations = maxIterations;
}
@Override
protected void maintain() {
if ( ! nodeRepository().zone().getCloud().allowHostSharing()) return;
CapacityChecker capacityChecker = new CapacityChecker(nodeRepository());
List<Node> overcommittedHosts = capacityChecker.findOvercommittedHosts();
if (overcommittedHosts.size() != 0) {
log.log(Level.WARNING, String.format("%d nodes are overcommitted! [ %s ]",
overcommittedHosts.size(),
overcommittedHosts.stream().map(Node::hostname).collect(Collectors.joining(", "))));
}
metric.set("overcommittedHosts", overcommittedHosts.size(), null);
Optional<CapacityChecker.HostFailurePath> failurePath = capacityChecker.worstCaseHostLossLeadingToFailure();
if (failurePath.isPresent()) {
int spareHostCapacity = failurePath.get().hostsCausingFailure.size() - 1;
if (spareHostCapacity == 0) {
Move move = findMitigatingMove(failurePath.get());
if (moving(move)) {
spareHostCapacity++;
}
}
metric.set("spareHostCapacity", spareHostCapacity, null);
}
}
private boolean moving(Move move) {
if (move.isEmpty()) return false;
if (move.node().allocation().get().membership().retired()) return true;
return move.execute(false, Agent.SpareCapacityMaintainer, deployer, metric, nodeRepository());
}
private static class CapacitySolver {
private final HostCapacity hostCapacity;
private final int maxIterations;
private int iterations = 0;
CapacitySolver(HostCapacity hostCapacity, int maxIterations) {
this.hostCapacity = hostCapacity;
this.maxIterations = maxIterations;
}
/** The map of subproblem solutions already found. The value is null when there is no solution. */
private Map<SolutionKey, List<Move>> solutions = new HashMap<>();
/**
* Finds the shortest sequence of moves which makes room for the given node on the given host,
* assuming the given moves already made over the given hosts' current allocation.
*
* @param node the node to make room for
* @param host the target host to make room on
* @param hosts the hosts onto which we can move nodes
* @param movesConsidered the moves already being considered to add as part of this scenario
* (after any moves made by this)
* @param movesMade the moves already made in this scenario
* @return the list of movesMade with the moves needed for this appended, in the order they should be performed,
* or null if no sequence could be found
*/
List<Move> makeRoomFor(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
SolutionKey solutionKey = new SolutionKey(node, host, movesConsidered, movesMade);
List<Move> solution = solutions.get(solutionKey);
if (solution == null) {
solution = findRoomFor(node, host, hosts, movesConsidered, movesMade);
solutions.put(solutionKey, solution);
}
return solution;
}
private List<Move> findRoomFor(Node node, Node host, List<Node> hosts,
List<Move> movesConsidered, List<Move> movesMade) {
if (iterations++ > maxIterations)
return null;
if ( ! host.resources().satisfies(node.resources())) return null;
NodeResources freeCapacity = freeCapacityWith(movesMade, host);
if (freeCapacity.satisfies(node.resources())) return List.of();
List<Move> shortest = null;
for (var i = subsets(hostCapacity.allNodes().childrenOf(host), 5); i.hasNext(); ) {
List<Node> childrenToMove = i.next();
if ( ! addResourcesOf(childrenToMove, freeCapacity).satisfies(node.resources())) continue;
List<Move> moves = move(childrenToMove, host, hosts, movesConsidered, movesMade);
if (moves == null) continue;
if (shortest == null || moves.size() < shortest.size())
shortest = moves;
}
if (shortest == null) return null;
return append(movesMade, shortest);
}
private List<Move> move(List<Node> nodes, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
List<Move> moves = new ArrayList<>();
for (Node childToMove : nodes) {
List<Move> childMoves = move(childToMove, host, hosts, movesConsidered, append(movesMade, moves));
if (childMoves == null) return null;
moves.addAll(childMoves);
}
return moves;
}
private List<Move> move(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
if (contains(node, movesConsidered)) return null;
if (contains(node, movesMade)) return null;
List<Move> shortest = null;
for (Node target : hosts) {
if (target.equals(host)) continue;
Move move = new Move(node, host, target);
List<Move> childMoves = makeRoomFor(node, target, hosts, append(movesConsidered, move), movesMade);
if (childMoves == null) continue;
if (shortest == null || shortest.size() > childMoves.size() + 1) {
shortest = new ArrayList<>(childMoves);
shortest.add(move);
}
}
return shortest;
}
private boolean contains(Node node, List<Move> moves) {
return moves.stream().anyMatch(move -> move.node().equals(node));
}
private NodeResources addResourcesOf(List<Node> nodes, NodeResources resources) {
for (Node node : nodes)
resources = resources.add(node.resources());
return resources;
}
private Iterator<List<Node>> subsets(NodeList nodes, int maxSize) {
return new SubsetIterator(nodes.asList(), maxSize);
}
private List<Move> append(List<Move> a, List<Move> b) {
List<Move> list = new ArrayList<>();
list.addAll(a);
list.addAll(b);
return list;
}
private List<Move> append(List<Move> moves, Move move) {
List<Move> list = new ArrayList<>(moves);
list.add(move);
return list;
}
private NodeResources freeCapacityWith(List<Move> moves, Node host) {
NodeResources resources = hostCapacity.freeCapacityOf(host);
for (Move move : moves) {
if ( ! move.toHost().equals(host)) continue;
resources = resources.subtract(move.node().resources());
}
for (Move move : moves) {
if ( ! move.fromHost().equals(host)) continue;
resources = resources.add(move.node().resources());
}
return resources;
}
}
private static class SolutionKey {
private final Node node;
private final Node host;
private final List<Move> movesConsidered;
private final List<Move> movesMade;
private final int hash;
public SolutionKey(Node node, Node host, List<Move> movesConsidered, List<Move> movesMade) {
this.node = node;
this.host = host;
this.movesConsidered = movesConsidered;
this.movesMade = movesMade;
hash = Objects.hash(node, host, movesConsidered, movesMade);
}
@Override
public int hashCode() { return hash; }
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || o.getClass() != this.getClass()) return false;
SolutionKey other = (SolutionKey)o;
if ( ! other.node.equals(this.node)) return false;
if ( ! other.host.equals(this.host)) return false;
if ( ! other.movesConsidered.equals(this.movesConsidered)) return false;
if ( ! other.movesMade.equals(this.movesMade)) return false;
return true;
}
}
private static class SubsetIterator implements Iterator<List<Node>> {
private final List<Node> nodes;
private final int maxLength;
private int i = 0;
private List<Node> next = null;
public SubsetIterator(List<Node> nodes, int maxLength) {
this.nodes = new ArrayList<>(nodes.subList(0, Math.min(nodes.size(), 31)));
this.maxLength = maxLength;
}
@Override
public boolean hasNext() {
if (next != null) return true;
while (++i < 1<<nodes.size()) {
int ones = Integer.bitCount(i);
if (ones > maxLength) continue;
next = new ArrayList<>(ones);
for (int position = 0; position < nodes.size(); position++) {
if (hasOneAtPosition(position, i))
next.add(nodes.get(position));
}
return true;
}
return false;
}
@Override
public List<Node> next() {
if ( ! hasNext()) throw new IllegalStateException("No more elements");
var current = next;
next = null;
return current;
}
private boolean hasOneAtPosition(int position, int number) {
return (number & (1 << position)) > 0;
}
}
} |
If the shortest mitigation is empty it means that the situation can be mitigated in 0 moves, i.e it is already fine. This is an inconsistency that will only arise if some change happened to mitigate it between when the nodes were read by CapacityChecker and by this, or if either the CapacityChecker or this has a bug. I don't think we should prefer an unnecessary non-empty mitigation in this case, but arguably we could to signal it upwards such that we don't emit the alert in this case (and perhaps also log it). I'm uncertain on whether it's worth the extra complication. | private Move findMitigatingMove(CapacityChecker.HostFailurePath failurePath) {
Optional<Node> nodeWhichCantMove = failurePath.failureReason.tenant;
if (nodeWhichCantMove.isEmpty()) return Move.empty();
Node node = nodeWhichCantMove.get();
NodeList allNodes = nodeRepository().list();
HostCapacity hostCapacity = new HostCapacity(allNodes, nodeRepository().resourcesCalculator());
Set<Node> spareHosts = hostCapacity.findSpareHosts(allNodes.hosts().satisfies(node.resources()).asList(), 2);
List<Node> hosts = allNodes.hosts().except(spareHosts).asList();
CapacitySolver capacitySolver = new CapacitySolver(hostCapacity, maxIterations);
List<Move> shortestMitigation = null;
for (Node spareHost : spareHosts) {
List<Move> mitigation = capacitySolver.makeRoomFor(node, spareHost, hosts, List.of(), List.of());
if (mitigation == null) continue;
if (shortestMitigation == null || shortestMitigation.size() > mitigation.size())
shortestMitigation = mitigation;
}
if (shortestMitigation == null || shortestMitigation.isEmpty()) return Move.empty();
return shortestMitigation.get(0);
} | if (shortestMitigation == null || shortestMitigation.size() > mitigation.size()) | private Move findMitigatingMove(CapacityChecker.HostFailurePath failurePath) {
Optional<Node> nodeWhichCantMove = failurePath.failureReason.tenant;
if (nodeWhichCantMove.isEmpty()) return Move.empty();
Node node = nodeWhichCantMove.get();
NodeList allNodes = nodeRepository().list();
HostCapacity hostCapacity = new HostCapacity(allNodes, nodeRepository().resourcesCalculator());
Set<Node> spareHosts = hostCapacity.findSpareHosts(allNodes.hosts().satisfies(node.resources()).asList(), 2);
List<Node> hosts = allNodes.hosts().except(spareHosts).asList();
CapacitySolver capacitySolver = new CapacitySolver(hostCapacity, maxIterations);
List<Move> shortestMitigation = null;
for (Node spareHost : spareHosts) {
List<Move> mitigation = capacitySolver.makeRoomFor(node, spareHost, hosts, List.of(), List.of());
if (mitigation == null) continue;
if (shortestMitigation == null || shortestMitigation.size() > mitigation.size())
shortestMitigation = mitigation;
}
if (shortestMitigation == null || shortestMitigation.isEmpty()) return Move.empty();
return shortestMitigation.get(0);
} | class SpareCapacityMaintainer extends NodeRepositoryMaintainer {
private final int maxIterations;
private final Deployer deployer;
private final Metric metric;
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval) {
this(deployer, nodeRepository, metric, interval,
10_000
);
}
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval,
int maxIterations) {
super(nodeRepository, interval);
this.deployer = deployer;
this.metric = metric;
this.maxIterations = maxIterations;
}
@Override
protected void maintain() {
if ( ! nodeRepository().zone().getCloud().allowHostSharing()) return;
CapacityChecker capacityChecker = new CapacityChecker(nodeRepository());
List<Node> overcommittedHosts = capacityChecker.findOvercommittedHosts();
if (overcommittedHosts.size() != 0) {
log.log(Level.WARNING, String.format("%d nodes are overcommitted! [ %s ]",
overcommittedHosts.size(),
overcommittedHosts.stream().map(Node::hostname).collect(Collectors.joining(", "))));
}
metric.set("overcommittedHosts", overcommittedHosts.size(), null);
Optional<CapacityChecker.HostFailurePath> failurePath = capacityChecker.worstCaseHostLossLeadingToFailure();
if (failurePath.isPresent()) {
int spareHostCapacity = failurePath.get().hostsCausingFailure.size() - 1;
if (spareHostCapacity == 0) {
Move move = findMitigatingMove(failurePath.get());
if (moving(move)) {
spareHostCapacity++;
}
}
metric.set("spareHostCapacity", spareHostCapacity, null);
}
}
private boolean moving(Move move) {
if (move.isEmpty()) return false;
if (move.node().allocation().get().membership().retired()) return true;
return move.execute(false, Agent.SpareCapacityMaintainer, deployer, metric, nodeRepository());
}
private static class CapacitySolver {
private final HostCapacity hostCapacity;
private final int maxIterations;
private int iterations = 0;
CapacitySolver(HostCapacity hostCapacity, int maxIterations) {
this.hostCapacity = hostCapacity;
this.maxIterations = maxIterations;
}
/** The map of subproblem solutions already found. The value is null when there is no solution. */
private Map<SolutionKey, List<Move>> solutions = new HashMap<>();
/**
* Finds the shortest sequence of moves which makes room for the given node on the given host,
* assuming the given moves already made over the given hosts' current allocation.
*
* @param node the node to make room for
* @param host the target host to make room on
* @param hosts the hosts onto which we can move nodes
* @param movesConsidered the moves already being considered to add as part of this scenario
* (after any moves made by this)
* @param movesMade the moves already made in this scenario
* @return the list of movesMade with the moves needed for this appended, in the order they should be performed,
* or null if no sequence could be found
*/
List<Move> makeRoomFor(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
SolutionKey solutionKey = new SolutionKey(node, host, movesConsidered, movesMade);
List<Move> solution = solutions.get(solutionKey);
if (solution == null) {
solution = findRoomFor(node, host, hosts, movesConsidered, movesMade);
solutions.put(solutionKey, solution);
}
return solution;
}
private List<Move> findRoomFor(Node node, Node host, List<Node> hosts,
List<Move> movesConsidered, List<Move> movesMade) {
if (iterations++ > maxIterations)
return null;
if ( ! host.resources().satisfies(node.resources())) return null;
NodeResources freeCapacity = freeCapacityWith(movesMade, host);
if (freeCapacity.satisfies(node.resources())) return List.of();
List<Move> shortest = null;
for (var i = subsets(hostCapacity.allNodes().childrenOf(host), 5); i.hasNext(); ) {
List<Node> childrenToMove = i.next();
if ( ! addResourcesOf(childrenToMove, freeCapacity).satisfies(node.resources())) continue;
List<Move> moves = move(childrenToMove, host, hosts, movesConsidered, movesMade);
if (moves == null) continue;
if (shortest == null || moves.size() < shortest.size())
shortest = moves;
}
if (shortest == null) return null;
return append(movesMade, shortest);
}
private List<Move> move(List<Node> nodes, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
List<Move> moves = new ArrayList<>();
for (Node childToMove : nodes) {
List<Move> childMoves = move(childToMove, host, hosts, movesConsidered, append(movesMade, moves));
if (childMoves == null) return null;
moves.addAll(childMoves);
}
return moves;
}
private List<Move> move(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
if (contains(node, movesConsidered)) return null;
if (contains(node, movesMade)) return null;
List<Move> shortest = null;
for (Node target : hosts) {
if (target.equals(host)) continue;
Move move = new Move(node, host, target);
List<Move> childMoves = makeRoomFor(node, target, hosts, append(movesConsidered, move), movesMade);
if (childMoves == null) continue;
if (shortest == null || shortest.size() > childMoves.size() + 1) {
shortest = new ArrayList<>(childMoves);
shortest.add(move);
}
}
return shortest;
}
private boolean contains(Node node, List<Move> moves) {
return moves.stream().anyMatch(move -> move.node().equals(node));
}
private NodeResources addResourcesOf(List<Node> nodes, NodeResources resources) {
for (Node node : nodes)
resources = resources.add(node.resources());
return resources;
}
private Iterator<List<Node>> subsets(NodeList nodes, int maxSize) {
return new SubsetIterator(nodes.asList(), maxSize);
}
private List<Move> append(List<Move> a, List<Move> b) {
List<Move> list = new ArrayList<>();
list.addAll(a);
list.addAll(b);
return list;
}
private List<Move> append(List<Move> moves, Move move) {
List<Move> list = new ArrayList<>(moves);
list.add(move);
return list;
}
private NodeResources freeCapacityWith(List<Move> moves, Node host) {
NodeResources resources = hostCapacity.freeCapacityOf(host);
for (Move move : moves) {
if ( ! move.toHost().equals(host)) continue;
resources = resources.subtract(move.node().resources());
}
for (Move move : moves) {
if ( ! move.fromHost().equals(host)) continue;
resources = resources.add(move.fromHost().resources());
}
return resources;
}
}
private static class SolutionKey {
private final Node node;
private final Node host;
private final List<Move> movesConsidered;
private final List<Move> movesMade;
private final int hash;
public SolutionKey(Node node, Node host, List<Move> movesConsidered, List<Move> movesMade) {
this.node = node;
this.host = host;
this.movesConsidered = movesConsidered;
this.movesMade = movesMade;
hash = Objects.hash(node, host, movesConsidered, movesMade);
}
@Override
public int hashCode() { return hash; }
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || o.getClass() != this.getClass()) return false;
SolutionKey other = (SolutionKey)o;
if ( ! other.node.equals(this.node)) return false;
if ( ! other.host.equals(this.host)) return false;
if ( ! other.movesConsidered.equals(this.movesConsidered)) return false;
if ( ! other.movesMade.equals(this.movesMade)) return false;
return true;
}
}
private static class SubsetIterator implements Iterator<List<Node>> {
private final List<Node> nodes;
private final int maxLength;
private int i = 0;
private List<Node> next = null;
public SubsetIterator(List<Node> nodes, int maxLength) {
this.nodes = new ArrayList<>(nodes.subList(0, Math.min(nodes.size(), 31)));
this.maxLength = maxLength;
}
@Override
public boolean hasNext() {
if (next != null) return true;
while (++i < 1<<nodes.size()) {
int ones = onesIn(i);
if (ones > maxLength) continue;
next = new ArrayList<>(ones);
for (int position = 0; position < nodes.size(); position++) {
if (hasOneAtPosition(position, i))
next.add(nodes.get(position));
}
return true;
}
return false;
}
@Override
public List<Node> next() {
if ( ! hasNext()) throw new IllegalStateException("No more elements");
var current = next;
next = null;
return current;
}
private boolean hasOneAtPosition(int position, int number) {
return (number & (1 << position)) > 0;
}
private int onesIn(int number) {
int ones = 0;
for (int position = 0; Math.pow(2, position) <= number; position++) {
if (hasOneAtPosition(position, number))
ones++;
}
return ones;
}
}
} | class SpareCapacityMaintainer extends NodeRepositoryMaintainer {
private final int maxIterations;
private final Deployer deployer;
private final Metric metric;
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval) {
this(deployer, nodeRepository, metric, interval,
10_000
);
}
public SpareCapacityMaintainer(Deployer deployer,
NodeRepository nodeRepository,
Metric metric,
Duration interval,
int maxIterations) {
super(nodeRepository, interval);
this.deployer = deployer;
this.metric = metric;
this.maxIterations = maxIterations;
}
@Override
protected void maintain() {
if ( ! nodeRepository().zone().getCloud().allowHostSharing()) return;
CapacityChecker capacityChecker = new CapacityChecker(nodeRepository());
List<Node> overcommittedHosts = capacityChecker.findOvercommittedHosts();
if (overcommittedHosts.size() != 0) {
log.log(Level.WARNING, String.format("%d nodes are overcommitted! [ %s ]",
overcommittedHosts.size(),
overcommittedHosts.stream().map(Node::hostname).collect(Collectors.joining(", "))));
}
metric.set("overcommittedHosts", overcommittedHosts.size(), null);
Optional<CapacityChecker.HostFailurePath> failurePath = capacityChecker.worstCaseHostLossLeadingToFailure();
if (failurePath.isPresent()) {
int spareHostCapacity = failurePath.get().hostsCausingFailure.size() - 1;
if (spareHostCapacity == 0) {
Move move = findMitigatingMove(failurePath.get());
if (moving(move)) {
spareHostCapacity++;
}
}
metric.set("spareHostCapacity", spareHostCapacity, null);
}
}
private boolean moving(Move move) {
if (move.isEmpty()) return false;
if (move.node().allocation().get().membership().retired()) return true;
return move.execute(false, Agent.SpareCapacityMaintainer, deployer, metric, nodeRepository());
}
private static class CapacitySolver {
private final HostCapacity hostCapacity;
private final int maxIterations;
private int iterations = 0;
CapacitySolver(HostCapacity hostCapacity, int maxIterations) {
this.hostCapacity = hostCapacity;
this.maxIterations = maxIterations;
}
/** The map of subproblem solutions already found. The value is null when there is no solution. */
private Map<SolutionKey, List<Move>> solutions = new HashMap<>();
/**
* Finds the shortest sequence of moves which makes room for the given node on the given host,
* assuming the given moves already made over the given hosts' current allocation.
*
* @param node the node to make room for
* @param host the target host to make room on
* @param hosts the hosts onto which we can move nodes
* @param movesConsidered the moves already being considered to add as part of this scenario
* (after any moves made by this)
* @param movesMade the moves already made in this scenario
* @return the list of movesMade with the moves needed for this appended, in the order they should be performed,
* or null if no sequence could be found
*/
List<Move> makeRoomFor(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
SolutionKey solutionKey = new SolutionKey(node, host, movesConsidered, movesMade);
List<Move> solution = solutions.get(solutionKey);
if (solution == null) {
solution = findRoomFor(node, host, hosts, movesConsidered, movesMade);
solutions.put(solutionKey, solution);
}
return solution;
}
private List<Move> findRoomFor(Node node, Node host, List<Node> hosts,
List<Move> movesConsidered, List<Move> movesMade) {
if (iterations++ > maxIterations)
return null;
if ( ! host.resources().satisfies(node.resources())) return null;
NodeResources freeCapacity = freeCapacityWith(movesMade, host);
if (freeCapacity.satisfies(node.resources())) return List.of();
List<Move> shortest = null;
for (var i = subsets(hostCapacity.allNodes().childrenOf(host), 5); i.hasNext(); ) {
List<Node> childrenToMove = i.next();
if ( ! addResourcesOf(childrenToMove, freeCapacity).satisfies(node.resources())) continue;
List<Move> moves = move(childrenToMove, host, hosts, movesConsidered, movesMade);
if (moves == null) continue;
if (shortest == null || moves.size() < shortest.size())
shortest = moves;
}
if (shortest == null) return null;
return append(movesMade, shortest);
}
private List<Move> move(List<Node> nodes, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
List<Move> moves = new ArrayList<>();
for (Node childToMove : nodes) {
List<Move> childMoves = move(childToMove, host, hosts, movesConsidered, append(movesMade, moves));
if (childMoves == null) return null;
moves.addAll(childMoves);
}
return moves;
}
private List<Move> move(Node node, Node host, List<Node> hosts, List<Move> movesConsidered, List<Move> movesMade) {
if (contains(node, movesConsidered)) return null;
if (contains(node, movesMade)) return null;
List<Move> shortest = null;
for (Node target : hosts) {
if (target.equals(host)) continue;
Move move = new Move(node, host, target);
List<Move> childMoves = makeRoomFor(node, target, hosts, append(movesConsidered, move), movesMade);
if (childMoves == null) continue;
if (shortest == null || shortest.size() > childMoves.size() + 1) {
shortest = new ArrayList<>(childMoves);
shortest.add(move);
}
}
return shortest;
}
private boolean contains(Node node, List<Move> moves) {
return moves.stream().anyMatch(move -> move.node().equals(node));
}
private NodeResources addResourcesOf(List<Node> nodes, NodeResources resources) {
for (Node node : nodes)
resources = resources.add(node.resources());
return resources;
}
private Iterator<List<Node>> subsets(NodeList nodes, int maxSize) {
return new SubsetIterator(nodes.asList(), maxSize);
}
private List<Move> append(List<Move> a, List<Move> b) {
List<Move> list = new ArrayList<>();
list.addAll(a);
list.addAll(b);
return list;
}
private List<Move> append(List<Move> moves, Move move) {
List<Move> list = new ArrayList<>(moves);
list.add(move);
return list;
}
private NodeResources freeCapacityWith(List<Move> moves, Node host) {
NodeResources resources = hostCapacity.freeCapacityOf(host);
for (Move move : moves) {
if ( ! move.toHost().equals(host)) continue;
resources = resources.subtract(move.node().resources());
}
for (Move move : moves) {
if ( ! move.fromHost().equals(host)) continue;
resources = resources.add(move.node().resources());
}
return resources;
}
}
private static class SolutionKey {
private final Node node;
private final Node host;
private final List<Move> movesConsidered;
private final List<Move> movesMade;
private final int hash;
public SolutionKey(Node node, Node host, List<Move> movesConsidered, List<Move> movesMade) {
this.node = node;
this.host = host;
this.movesConsidered = movesConsidered;
this.movesMade = movesMade;
hash = Objects.hash(node, host, movesConsidered, movesMade);
}
@Override
public int hashCode() { return hash; }
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || o.getClass() != this.getClass()) return false;
SolutionKey other = (SolutionKey)o;
if ( ! other.node.equals(this.node)) return false;
if ( ! other.host.equals(this.host)) return false;
if ( ! other.movesConsidered.equals(this.movesConsidered)) return false;
if ( ! other.movesMade.equals(this.movesMade)) return false;
return true;
}
}
private static class SubsetIterator implements Iterator<List<Node>> {
private final List<Node> nodes;
private final int maxLength;
private int i = 0;
private List<Node> next = null;
public SubsetIterator(List<Node> nodes, int maxLength) {
this.nodes = new ArrayList<>(nodes.subList(0, Math.min(nodes.size(), 31)));
this.maxLength = maxLength;
}
@Override
public boolean hasNext() {
if (next != null) return true;
while (++i < 1<<nodes.size()) {
int ones = Integer.bitCount(i);
if (ones > maxLength) continue;
next = new ArrayList<>(ones);
for (int position = 0; position < nodes.size(); position++) {
if (hasOneAtPosition(position, i))
next.add(nodes.get(position));
}
return true;
}
return false;
}
@Override
public List<Node> next() {
if ( ! hasNext()) throw new IllegalStateException("No more elements");
var current = next;
next = null;
return current;
}
private boolean hasOneAtPosition(int position, int number) {
return (number & (1 << position)) > 0;
}
}
} |
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/InputStream.html#readAllBytes() | public HttpResponse handle(HttpRequest httpRequest) {
String mode = property("mode", "help", httpRequest, String::valueOf);
TestDescriptor.TestCategory category = property("category", TestDescriptor.TestCategory.systemtest, httpRequest, TestDescriptor.TestCategory::valueOf);
try {
testRuntimeProvider.initialize(IOUtils.readBytes(httpRequest.getData(), 1000 * 1000));
} catch (IOException e) {
return new ErrorResponse(500, "testruntime-initialization", "Exception reading test config");
}
if ("help".equalsIgnoreCase(mode)) {
return new MessageResponse("Accepted modes: \n help \n list \n execute");
}
if (!"list".equalsIgnoreCase(mode) && !"execute".equalsIgnoreCase(mode)) {
return new ErrorResponse(400, "client error", "Unknown mode \"" + mode + "\"");
}
Bundle testBundle = junitRunner.findTestBundle("-tests");
TestDescriptor testDescriptor = junitRunner.loadTestDescriptor(testBundle);
List<Class<?>> testClasses = junitRunner.loadClasses(testBundle, testDescriptor, category);
String jsonResponse = junitRunner.executeTests(testClasses);
return new JsonResponse(200, jsonResponse);
} | testRuntimeProvider.initialize(IOUtils.readBytes(httpRequest.getData(), 1000 * 1000)); | public HttpResponse handle(HttpRequest httpRequest) {
String mode = property("mode", "help", httpRequest, String::valueOf);
TestDescriptor.TestCategory category = property("category", TestDescriptor.TestCategory.systemtest, httpRequest, TestDescriptor.TestCategory::valueOf);
try {
testRuntimeProvider.initialize(httpRequest.getData().readAllBytes());
} catch (IOException e) {
return new ErrorResponse(500, "testruntime-initialization", "Exception reading test config");
}
if ("help".equalsIgnoreCase(mode)) {
return new MessageResponse("Accepted modes: \n help \n list \n execute");
}
if (!"list".equalsIgnoreCase(mode) && !"execute".equalsIgnoreCase(mode)) {
return new ErrorResponse(400, "client error", "Unknown mode \"" + mode + "\"");
}
Bundle testBundle = junitRunner.findTestBundle("-tests");
TestDescriptor testDescriptor = junitRunner.loadTestDescriptor(testBundle);
List<Class<?>> testClasses = junitRunner.loadClasses(testBundle, testDescriptor, category);
String jsonResponse = junitRunner.executeTests(testClasses);
return new JsonResponse(200, jsonResponse);
} | class JunitHandler extends LoggingRequestHandler {
private final JunitRunner junitRunner;
private final TestRuntimeProvider testRuntimeProvider;
@Inject
public JunitHandler(Executor executor, AccessLog accessLog, JunitRunner junitRunner, TestRuntimeProvider testRuntimeProvider) {
super(executor, accessLog);
this.junitRunner = junitRunner;
this.testRuntimeProvider = testRuntimeProvider;
}
@Override
private static <VAL> VAL property(String name, VAL defaultValue, HttpRequest request, Function<String, VAL> converter) {
final String propertyString = request.getProperty(name);
if (propertyString != null) {
return converter.apply(propertyString);
}
return defaultValue;
}
} | class JunitHandler extends LoggingRequestHandler {
private final JunitRunner junitRunner;
private final TestRuntimeProvider testRuntimeProvider;
@Inject
public JunitHandler(Executor executor, AccessLog accessLog, JunitRunner junitRunner, TestRuntimeProvider testRuntimeProvider) {
super(executor, accessLog);
this.junitRunner = junitRunner;
this.testRuntimeProvider = testRuntimeProvider;
}
@Override
private static <VAL> VAL property(String name, VAL defaultValue, HttpRequest request, Function<String, VAL> converter) {
final String propertyString = request.getProperty(name);
if (propertyString != null) {
return converter.apply(propertyString);
}
return defaultValue;
}
} |
Can this be simplified to a single method in `JunitRunner`? | public HttpResponse handle(HttpRequest httpRequest) {
String mode = property("mode", "help", httpRequest, String::valueOf);
TestDescriptor.TestCategory category = property("category", TestDescriptor.TestCategory.systemtest, httpRequest, TestDescriptor.TestCategory::valueOf);
try {
testRuntimeProvider.initialize(IOUtils.readBytes(httpRequest.getData(), 1000 * 1000));
} catch (IOException e) {
return new ErrorResponse(500, "testruntime-initialization", "Exception reading test config");
}
if ("help".equalsIgnoreCase(mode)) {
return new MessageResponse("Accepted modes: \n help \n list \n execute");
}
if (!"list".equalsIgnoreCase(mode) && !"execute".equalsIgnoreCase(mode)) {
return new ErrorResponse(400, "client error", "Unknown mode \"" + mode + "\"");
}
Bundle testBundle = junitRunner.findTestBundle("-tests");
TestDescriptor testDescriptor = junitRunner.loadTestDescriptor(testBundle);
List<Class<?>> testClasses = junitRunner.loadClasses(testBundle, testDescriptor, category);
String jsonResponse = junitRunner.executeTests(testClasses);
return new JsonResponse(200, jsonResponse);
} | String jsonResponse = junitRunner.executeTests(testClasses); | public HttpResponse handle(HttpRequest httpRequest) {
String mode = property("mode", "help", httpRequest, String::valueOf);
TestDescriptor.TestCategory category = property("category", TestDescriptor.TestCategory.systemtest, httpRequest, TestDescriptor.TestCategory::valueOf);
try {
testRuntimeProvider.initialize(httpRequest.getData().readAllBytes());
} catch (IOException e) {
return new ErrorResponse(500, "testruntime-initialization", "Exception reading test config");
}
if ("help".equalsIgnoreCase(mode)) {
return new MessageResponse("Accepted modes: \n help \n list \n execute");
}
if (!"list".equalsIgnoreCase(mode) && !"execute".equalsIgnoreCase(mode)) {
return new ErrorResponse(400, "client error", "Unknown mode \"" + mode + "\"");
}
Bundle testBundle = junitRunner.findTestBundle("-tests");
TestDescriptor testDescriptor = junitRunner.loadTestDescriptor(testBundle);
List<Class<?>> testClasses = junitRunner.loadClasses(testBundle, testDescriptor, category);
String jsonResponse = junitRunner.executeTests(testClasses);
return new JsonResponse(200, jsonResponse);
} | class JunitHandler extends LoggingRequestHandler {
private final JunitRunner junitRunner;
private final TestRuntimeProvider testRuntimeProvider;
@Inject
public JunitHandler(Executor executor, AccessLog accessLog, JunitRunner junitRunner, TestRuntimeProvider testRuntimeProvider) {
super(executor, accessLog);
this.junitRunner = junitRunner;
this.testRuntimeProvider = testRuntimeProvider;
}
@Override
private static <VAL> VAL property(String name, VAL defaultValue, HttpRequest request, Function<String, VAL> converter) {
final String propertyString = request.getProperty(name);
if (propertyString != null) {
return converter.apply(propertyString);
}
return defaultValue;
}
} | class JunitHandler extends LoggingRequestHandler {
private final JunitRunner junitRunner;
private final TestRuntimeProvider testRuntimeProvider;
@Inject
public JunitHandler(Executor executor, AccessLog accessLog, JunitRunner junitRunner, TestRuntimeProvider testRuntimeProvider) {
super(executor, accessLog);
this.junitRunner = junitRunner;
this.testRuntimeProvider = testRuntimeProvider;
}
@Override
private static <VAL> VAL property(String name, VAL defaultValue, HttpRequest request, Function<String, VAL> converter) {
final String propertyString = request.getProperty(name);
if (propertyString != null) {
return converter.apply(propertyString);
}
return defaultValue;
}
} |
Maybe move location of manifest file as a constant in `TestDescriptor` | public TestDescriptor loadTestDescriptor(Bundle bundle) {
URL resource = bundle.getEntry("META-INF/testClasses.json");
TestDescriptor testDescriptor;
try {
var jsonDescriptor = IOUtils.readAll(resource.openStream(), Charset.defaultCharset()).trim();
testDescriptor = TestDescriptor.fromJsonString(jsonDescriptor);
logger.info( "Test classes in bundle :" + testDescriptor.toString());
return testDescriptor;
} catch (IOException e) {
throw new RuntimeException("Could not load META-INF/testClasses.json [" + e.getMessage() + "]");
}
} | URL resource = bundle.getEntry("META-INF/testClasses.json"); | public TestDescriptor loadTestDescriptor(Bundle bundle) {
URL resource = bundle.getEntry(TestDescriptor.DEFAULT_FILENAME);
TestDescriptor testDescriptor;
try {
var jsonDescriptor = IOUtils.readAll(resource.openStream(), Charset.defaultCharset()).trim();
testDescriptor = TestDescriptor.fromJsonString(jsonDescriptor);
logger.info( "Test classes in bundle :" + testDescriptor.toString());
return testDescriptor;
} catch (IOException e) {
throw new RuntimeException("Could not load " + TestDescriptor.DEFAULT_FILENAME + " [" + e.getMessage() + "]");
}
} | class JunitRunner extends AbstractComponent {
private static final Logger logger = Logger.getLogger(JunitRunner.class.getName());
private final BundleContext bundleContext;
@Inject
public JunitRunner(OsgiFramework osgiFramework) {
var tmp = osgiFramework.bundleContext();
try {
var field = tmp.getClass().getDeclaredField("wrapped");
field.setAccessible(true);
bundleContext = (BundleContext) field.get(tmp);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public Bundle findTestBundle(String bundleNameSuffix) {
return Stream.of(bundleContext.getBundles())
.filter(bundle -> bundle.getSymbolicName().endsWith(bundleNameSuffix))
.findAny()
.orElseThrow(() -> new RuntimeException("No bundle on classpath with name ending on " + bundleNameSuffix));
}
public List<Class<?>> loadClasses(Bundle bundle, TestDescriptor testDescriptor, TestDescriptor.TestCategory testCategory) {
List<Class<?>> testClasses = testDescriptor.getConfiguredTests(testCategory).stream()
.map(className -> loadClass(bundle, className))
.collect(Collectors.toList());
StringBuffer buffer = new StringBuffer();
testClasses.forEach(cl -> buffer.append("\t").append(cl.toString()).append(" / ").append(cl.getClassLoader().toString()).append("\n"));
logger.info("Loaded testClasses: \n" + buffer.toString());
return testClasses;
}
private Class<?> loadClass(Bundle bundle, String className) {
try {
return bundle.loadClass(className);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Could not find class: " + className + " in bundle " + bundle.getSymbolicName(), e);
}
}
public String executeTests(List<Class<?>> testClasses) {
LauncherDiscoveryRequest discoveryRequest = LauncherDiscoveryRequestBuilder.request()
.selectors(
testClasses.stream().map(DiscoverySelectors::selectClass).collect(Collectors.toList())
)
.configurationParameter(LauncherConstants.CAPTURE_STDERR_PROPERTY_NAME,"true")
.configurationParameter(LauncherConstants.CAPTURE_STDOUT_PROPERTY_NAME,"true")
.build();
var launcherConfig = LauncherConfig.builder()
.addTestEngines(new JupiterTestEngine())
.build();
Launcher launcher = LauncherFactory.create(launcherConfig);
var logLines = new ArrayList<String>();
var logListener = LoggingListener.forBiConsumer((t, m) -> log(logLines, m.get(), t));
var summaryListener = new SummaryGeneratingListener();
launcher.registerTestExecutionListeners(logListener, summaryListener);
launcher.execute(discoveryRequest);
var report = summaryListener.getSummary();
return createJsonTestReport(report, logLines);
}
private String createJsonTestReport(TestExecutionSummary report, List<String> logLines) {
var slime = new Slime();
var root = slime.setObject();
var summary = root.setObject("summary");
summary.setLong("Total tests", report.getTestsFoundCount());
summary.setLong("Test success", report.getTestsSucceededCount());
summary.setLong("Test failed", report.getTestsFailedCount());
summary.setLong("Test ignored", report.getTestsSkippedCount());
summary.setLong("Test success", report.getTestsAbortedCount());
summary.setLong("Test started", report.getTestsStartedCount());
var failures = summary.setArray("failures");
report.getFailures().forEach(failure -> serializeFailure(failure, failures.addObject()));
var output = root.setArray("output");
logLines.forEach(output::addString);
return Exceptions.uncheck(() -> new String(SlimeUtils.toJsonBytes(slime), StandardCharsets.UTF_8));
}
private void serializeFailure(TestExecutionSummary.Failure failure, Cursor slime) {
var testIdentifier = failure.getTestIdentifier();
slime.setString("testName", testIdentifier.getUniqueId());
slime.setString("testError",failure.getException().getMessage());
slime.setString("exception", ExceptionUtils.getStackTraceAsString(failure.getException()));
}
private void log(List<String> logs, String message, Throwable t) {
logs.add(message);
if(t != null) {
logs.add(t.getMessage());
List.of(t.getStackTrace()).stream()
.map(StackTraceElement::toString)
.forEach(logs::add);
}
}
@Override
public void deconstruct() {
super.deconstruct();
}
} | class JunitRunner extends AbstractComponent {
private static final Logger logger = Logger.getLogger(JunitRunner.class.getName());
private final BundleContext bundleContext;
@Inject
public JunitRunner(OsgiFramework osgiFramework) {
var tmp = osgiFramework.bundleContext();
try {
var field = tmp.getClass().getDeclaredField("wrapped");
field.setAccessible(true);
bundleContext = (BundleContext) field.get(tmp);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public Bundle findTestBundle(String bundleNameSuffix) {
return Stream.of(bundleContext.getBundles())
.filter(bundle -> bundle.getSymbolicName().endsWith(bundleNameSuffix))
.findAny()
.orElseThrow(() -> new RuntimeException("No bundle on classpath with name ending on " + bundleNameSuffix));
}
public List<Class<?>> loadClasses(Bundle bundle, TestDescriptor testDescriptor, TestDescriptor.TestCategory testCategory) {
List<Class<?>> testClasses = testDescriptor.getConfiguredTests(testCategory).stream()
.map(className -> loadClass(bundle, className))
.collect(Collectors.toList());
StringBuffer buffer = new StringBuffer();
testClasses.forEach(cl -> buffer.append("\t").append(cl.toString()).append(" / ").append(cl.getClassLoader().toString()).append("\n"));
logger.info("Loaded testClasses: \n" + buffer.toString());
return testClasses;
}
private Class<?> loadClass(Bundle bundle, String className) {
try {
return bundle.loadClass(className);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Could not find class: " + className + " in bundle " + bundle.getSymbolicName(), e);
}
}
public String executeTests(List<Class<?>> testClasses) {
LauncherDiscoveryRequest discoveryRequest = LauncherDiscoveryRequestBuilder.request()
.selectors(
testClasses.stream().map(DiscoverySelectors::selectClass).collect(Collectors.toList())
)
.build();
var launcherConfig = LauncherConfig.builder()
.addTestEngines(new JupiterTestEngine())
.build();
Launcher launcher = LauncherFactory.create(launcherConfig);
var logLines = new ArrayList<String>();
var logListener = LoggingListener.forBiConsumer((t, m) -> log(logLines, m.get(), t));
var summaryListener = new SummaryGeneratingListener();
launcher.registerTestExecutionListeners(logListener, summaryListener);
launcher.execute(discoveryRequest);
var report = summaryListener.getSummary();
return createJsonTestReport(report, logLines);
}
private String createJsonTestReport(TestExecutionSummary report, List<String> logLines) {
var slime = new Slime();
var root = slime.setObject();
var summary = root.setObject("summary");
summary.setLong("Total tests", report.getTestsFoundCount());
summary.setLong("Test success", report.getTestsSucceededCount());
summary.setLong("Test failed", report.getTestsFailedCount());
summary.setLong("Test ignored", report.getTestsSkippedCount());
summary.setLong("Test success", report.getTestsAbortedCount());
summary.setLong("Test started", report.getTestsStartedCount());
var failures = summary.setArray("failures");
report.getFailures().forEach(failure -> serializeFailure(failure, failures.addObject()));
var output = root.setArray("output");
logLines.forEach(output::addString);
return Exceptions.uncheck(() -> new String(SlimeUtils.toJsonBytes(slime), StandardCharsets.UTF_8));
}
private void serializeFailure(TestExecutionSummary.Failure failure, Cursor slime) {
var testIdentifier = failure.getTestIdentifier();
slime.setString("testName", testIdentifier.getUniqueId());
slime.setString("testError",failure.getException().getMessage());
slime.setString("exception", ExceptionUtils.getStackTraceAsString(failure.getException()));
}
private void log(List<String> logs, String message, Throwable t) {
logs.add(message);
if(t != null) {
logs.add(t.getMessage());
List.of(t.getStackTrace()).stream()
.map(StackTraceElement::toString)
.forEach(logs::add);
}
}
@Override
public void deconstruct() {
super.deconstruct();
}
} |
Make filename more generic (e.g. `testBundleDescriptor.json`) ? | public TestDescriptor loadTestDescriptor(Bundle bundle) {
URL resource = bundle.getEntry("META-INF/testClasses.json");
TestDescriptor testDescriptor;
try {
var jsonDescriptor = IOUtils.readAll(resource.openStream(), Charset.defaultCharset()).trim();
testDescriptor = TestDescriptor.fromJsonString(jsonDescriptor);
logger.info( "Test classes in bundle :" + testDescriptor.toString());
return testDescriptor;
} catch (IOException e) {
throw new RuntimeException("Could not load META-INF/testClasses.json [" + e.getMessage() + "]");
}
} | URL resource = bundle.getEntry("META-INF/testClasses.json"); | public TestDescriptor loadTestDescriptor(Bundle bundle) {
URL resource = bundle.getEntry(TestDescriptor.DEFAULT_FILENAME);
TestDescriptor testDescriptor;
try {
var jsonDescriptor = IOUtils.readAll(resource.openStream(), Charset.defaultCharset()).trim();
testDescriptor = TestDescriptor.fromJsonString(jsonDescriptor);
logger.info( "Test classes in bundle :" + testDescriptor.toString());
return testDescriptor;
} catch (IOException e) {
throw new RuntimeException("Could not load " + TestDescriptor.DEFAULT_FILENAME + " [" + e.getMessage() + "]");
}
} | class JunitRunner extends AbstractComponent {
private static final Logger logger = Logger.getLogger(JunitRunner.class.getName());
private final BundleContext bundleContext;
@Inject
public JunitRunner(OsgiFramework osgiFramework) {
var tmp = osgiFramework.bundleContext();
try {
var field = tmp.getClass().getDeclaredField("wrapped");
field.setAccessible(true);
bundleContext = (BundleContext) field.get(tmp);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public Bundle findTestBundle(String bundleNameSuffix) {
return Stream.of(bundleContext.getBundles())
.filter(bundle -> bundle.getSymbolicName().endsWith(bundleNameSuffix))
.findAny()
.orElseThrow(() -> new RuntimeException("No bundle on classpath with name ending on " + bundleNameSuffix));
}
public List<Class<?>> loadClasses(Bundle bundle, TestDescriptor testDescriptor, TestDescriptor.TestCategory testCategory) {
List<Class<?>> testClasses = testDescriptor.getConfiguredTests(testCategory).stream()
.map(className -> loadClass(bundle, className))
.collect(Collectors.toList());
StringBuffer buffer = new StringBuffer();
testClasses.forEach(cl -> buffer.append("\t").append(cl.toString()).append(" / ").append(cl.getClassLoader().toString()).append("\n"));
logger.info("Loaded testClasses: \n" + buffer.toString());
return testClasses;
}
private Class<?> loadClass(Bundle bundle, String className) {
try {
return bundle.loadClass(className);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Could not find class: " + className + " in bundle " + bundle.getSymbolicName(), e);
}
}
public String executeTests(List<Class<?>> testClasses) {
LauncherDiscoveryRequest discoveryRequest = LauncherDiscoveryRequestBuilder.request()
.selectors(
testClasses.stream().map(DiscoverySelectors::selectClass).collect(Collectors.toList())
)
.configurationParameter(LauncherConstants.CAPTURE_STDERR_PROPERTY_NAME,"true")
.configurationParameter(LauncherConstants.CAPTURE_STDOUT_PROPERTY_NAME,"true")
.build();
var launcherConfig = LauncherConfig.builder()
.addTestEngines(new JupiterTestEngine())
.build();
Launcher launcher = LauncherFactory.create(launcherConfig);
var logLines = new ArrayList<String>();
var logListener = LoggingListener.forBiConsumer((t, m) -> log(logLines, m.get(), t));
var summaryListener = new SummaryGeneratingListener();
launcher.registerTestExecutionListeners(logListener, summaryListener);
launcher.execute(discoveryRequest);
var report = summaryListener.getSummary();
return createJsonTestReport(report, logLines);
}
private String createJsonTestReport(TestExecutionSummary report, List<String> logLines) {
var slime = new Slime();
var root = slime.setObject();
var summary = root.setObject("summary");
summary.setLong("Total tests", report.getTestsFoundCount());
summary.setLong("Test success", report.getTestsSucceededCount());
summary.setLong("Test failed", report.getTestsFailedCount());
summary.setLong("Test ignored", report.getTestsSkippedCount());
summary.setLong("Test success", report.getTestsAbortedCount());
summary.setLong("Test started", report.getTestsStartedCount());
var failures = summary.setArray("failures");
report.getFailures().forEach(failure -> serializeFailure(failure, failures.addObject()));
var output = root.setArray("output");
logLines.forEach(output::addString);
return Exceptions.uncheck(() -> new String(SlimeUtils.toJsonBytes(slime), StandardCharsets.UTF_8));
}
private void serializeFailure(TestExecutionSummary.Failure failure, Cursor slime) {
var testIdentifier = failure.getTestIdentifier();
slime.setString("testName", testIdentifier.getUniqueId());
slime.setString("testError",failure.getException().getMessage());
slime.setString("exception", ExceptionUtils.getStackTraceAsString(failure.getException()));
}
private void log(List<String> logs, String message, Throwable t) {
logs.add(message);
if(t != null) {
logs.add(t.getMessage());
List.of(t.getStackTrace()).stream()
.map(StackTraceElement::toString)
.forEach(logs::add);
}
}
@Override
public void deconstruct() {
super.deconstruct();
}
} | class JunitRunner extends AbstractComponent {
private static final Logger logger = Logger.getLogger(JunitRunner.class.getName());
private final BundleContext bundleContext;
@Inject
public JunitRunner(OsgiFramework osgiFramework) {
var tmp = osgiFramework.bundleContext();
try {
var field = tmp.getClass().getDeclaredField("wrapped");
field.setAccessible(true);
bundleContext = (BundleContext) field.get(tmp);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public Bundle findTestBundle(String bundleNameSuffix) {
return Stream.of(bundleContext.getBundles())
.filter(bundle -> bundle.getSymbolicName().endsWith(bundleNameSuffix))
.findAny()
.orElseThrow(() -> new RuntimeException("No bundle on classpath with name ending on " + bundleNameSuffix));
}
public List<Class<?>> loadClasses(Bundle bundle, TestDescriptor testDescriptor, TestDescriptor.TestCategory testCategory) {
List<Class<?>> testClasses = testDescriptor.getConfiguredTests(testCategory).stream()
.map(className -> loadClass(bundle, className))
.collect(Collectors.toList());
StringBuffer buffer = new StringBuffer();
testClasses.forEach(cl -> buffer.append("\t").append(cl.toString()).append(" / ").append(cl.getClassLoader().toString()).append("\n"));
logger.info("Loaded testClasses: \n" + buffer.toString());
return testClasses;
}
private Class<?> loadClass(Bundle bundle, String className) {
try {
return bundle.loadClass(className);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Could not find class: " + className + " in bundle " + bundle.getSymbolicName(), e);
}
}
public String executeTests(List<Class<?>> testClasses) {
LauncherDiscoveryRequest discoveryRequest = LauncherDiscoveryRequestBuilder.request()
.selectors(
testClasses.stream().map(DiscoverySelectors::selectClass).collect(Collectors.toList())
)
.build();
var launcherConfig = LauncherConfig.builder()
.addTestEngines(new JupiterTestEngine())
.build();
Launcher launcher = LauncherFactory.create(launcherConfig);
var logLines = new ArrayList<String>();
var logListener = LoggingListener.forBiConsumer((t, m) -> log(logLines, m.get(), t));
var summaryListener = new SummaryGeneratingListener();
launcher.registerTestExecutionListeners(logListener, summaryListener);
launcher.execute(discoveryRequest);
var report = summaryListener.getSummary();
return createJsonTestReport(report, logLines);
}
private String createJsonTestReport(TestExecutionSummary report, List<String> logLines) {
var slime = new Slime();
var root = slime.setObject();
var summary = root.setObject("summary");
summary.setLong("Total tests", report.getTestsFoundCount());
summary.setLong("Test success", report.getTestsSucceededCount());
summary.setLong("Test failed", report.getTestsFailedCount());
summary.setLong("Test ignored", report.getTestsSkippedCount());
summary.setLong("Test success", report.getTestsAbortedCount());
summary.setLong("Test started", report.getTestsStartedCount());
var failures = summary.setArray("failures");
report.getFailures().forEach(failure -> serializeFailure(failure, failures.addObject()));
var output = root.setArray("output");
logLines.forEach(output::addString);
return Exceptions.uncheck(() -> new String(SlimeUtils.toJsonBytes(slime), StandardCharsets.UTF_8));
}
private void serializeFailure(TestExecutionSummary.Failure failure, Cursor slime) {
var testIdentifier = failure.getTestIdentifier();
slime.setString("testName", testIdentifier.getUniqueId());
slime.setString("testError",failure.getException().getMessage());
slime.setString("exception", ExceptionUtils.getStackTraceAsString(failure.getException()));
}
private void log(List<String> logs, String message, Throwable t) {
logs.add(message);
if(t != null) {
logs.add(t.getMessage());
List.of(t.getStackTrace()).stream()
.map(StackTraceElement::toString)
.forEach(logs::add);
}
}
@Override
public void deconstruct() {
super.deconstruct();
}
} |
remove 'it'? | private void copyApp(File sourceDir, File destinationDir) throws IOException {
if (destinationDir.exists())
throw new RuntimeException("Destination dir " + destinationDir + " already exists");
if (! sourceDir.isDirectory())
throw new IllegalArgumentException(sourceDir.getAbsolutePath() + " is not a directory");
java.nio.file.Path tempDestinationDir = Files.createTempDirectory(destinationDir.getParentFile().toPath(), "app-package");
log.log(Level.FINE, "Copying dir " + sourceDir.getAbsolutePath() + " to " + tempDestinationDir.toFile().getAbsolutePath());
IOUtils.copyDirectory(sourceDir, tempDestinationDir.toFile());
log.log(Level.FINE, "Moving " + tempDestinationDir + " to " + destinationDir.getAbsolutePath());
Files.move(tempDestinationDir, destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE);
} | private void copyApp(File sourceDir, File destinationDir) throws IOException {
if (destinationDir.exists())
throw new RuntimeException("Destination dir " + destinationDir + " already exists");
if (! sourceDir.isDirectory())
throw new IllegalArgumentException(sourceDir.getAbsolutePath() + " is not a directory");
java.nio.file.Path tempDestinationDir = Files.createTempDirectory(destinationDir.getParentFile().toPath(), "app-package");
log.log(Level.FINE, "Copying dir " + sourceDir.getAbsolutePath() + " to " + tempDestinationDir.toFile().getAbsolutePath());
IOUtils.copyDirectory(sourceDir, tempDestinationDir.toFile());
log.log(Level.FINE, "Moving " + tempDestinationDir + " to " + destinationDir.getAbsolutePath());
Files.move(tempDestinationDir, destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE);
} | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSession = 0;
private final SessionCache<LocalSession> localSessionCache = new SessionCache<>();
private final SessionCache<RemoteSession> remoteSessionCache = new SessionCache<>();
private final Map<Long, SessionStateWatcher> sessionStateWatchers = new HashMap<>();
private final Duration sessionLifetime;
private final Clock clock;
private final Curator curator;
private final Executor zkWatcherExecutor;
private final TenantFileSystemDirs tenantFileSystemDirs;
private final BooleanFlag distributeApplicationPackage;
private final ReloadHandler reloadHandler;
private final MetricUpdater metrics;
private final Curator.DirectoryCache directoryCache;
private final TenantApplications applicationRepo;
private final SessionPreparer sessionPreparer;
private final Path sessionsPath;
private final TenantName tenantName;
private final GlobalComponentRegistry componentRegistry;
public SessionRepository(TenantName tenantName,
GlobalComponentRegistry componentRegistry,
TenantApplications applicationRepo,
ReloadHandler reloadHandler,
FlagSource flagSource,
SessionPreparer sessionPreparer) {
this.tenantName = tenantName;
this.componentRegistry = componentRegistry;
this.sessionsPath = TenantRepository.getSessionsPath(tenantName);
this.clock = componentRegistry.getClock();
this.curator = componentRegistry.getCurator();
this.sessionLifetime = Duration.ofSeconds(componentRegistry.getConfigserverConfig().sessionLifetime());
this.zkWatcherExecutor = command -> componentRegistry.getZkWatcherExecutor().execute(tenantName, command);
this.tenantFileSystemDirs = new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName);
this.applicationRepo = applicationRepo;
this.sessionPreparer = sessionPreparer;
this.distributeApplicationPackage = Flags.CONFIGSERVER_DISTRIBUTE_APPLICATION_PACKAGE.bindTo(flagSource);
this.reloadHandler = reloadHandler;
this.metrics = componentRegistry.getMetrics().getOrCreateMetricUpdater(Metrics.createDimensions(tenantName));
loadLocalSessions();
initializeRemoteSessions();
this.directoryCache = curator.createDirectoryCache(sessionsPath.getAbsolute(), false, false, componentRegistry.getZkCacheExecutor());
this.directoryCache.addListener(this::childEvent);
this.directoryCache.start();
}
public synchronized void addSession(LocalSession session) {
localSessionCache.addSession(session);
long sessionId = session.getSessionId();
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
RemoteSession remoteSession = new RemoteSession(tenantName, sessionId, componentRegistry, createSessionZooKeeperClient(sessionId));
addWatcher(sessionId, fileCache, remoteSession, Optional.of(session));
}
public LocalSession getLocalSession(long sessionId) {
return localSessionCache.getSession(sessionId);
}
public List<LocalSession> getLocalSessions() {
return localSessionCache.getSessions();
}
private void loadLocalSessions() {
File[] sessions = tenantFileSystemDirs.sessionsPath().listFiles(sessionApplicationsFilter);
if (sessions == null) {
return;
}
for (File session : sessions) {
try {
addSession(createSessionFromId(Long.parseLong(session.getName())));
} catch (IllegalArgumentException e) {
log.log(Level.WARNING, "Could not load session '" +
session.getAbsolutePath() + "':" + e.getMessage() + ", skipping it.");
}
}
}
public ConfigChangeActions prepareLocalSession(LocalSession session,
DeployLogger logger,
PrepareParams params,
Optional<ApplicationSet> currentActiveApplicationSet,
Path tenantPath,
Instant now) {
applicationRepo.createApplication(params.getApplicationId());
logger.log(Level.FINE, "Created application " + params.getApplicationId());
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
Curator.CompletionWaiter waiter = sessionZooKeeperClient.createPrepareWaiter();
ConfigChangeActions actions = sessionPreparer.prepare(applicationRepo.getHostValidator(), logger, params,
currentActiveApplicationSet, tenantPath, now,
getSessionAppDir(sessionId),
session.getApplicationPackage(), sessionZooKeeperClient);
session.setPrepared();
waiter.awaitCompletion(params.getTimeoutBudget().timeLeft());
return actions;
}
public void deleteExpiredSessions(Map<ApplicationId, Long> activeSessions) {
log.log(Level.FINE, "Purging old sessions");
try {
for (LocalSession candidate : localSessionCache.getSessions()) {
Instant createTime = candidate.getCreateTime();
log.log(Level.FINE, "Candidate session for deletion: " + candidate.getSessionId() + ", created: " + createTime);
if (hasExpired(candidate) && !isActiveSession(candidate)) {
deleteLocalSession(candidate);
} else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) {
ApplicationId applicationId = candidate.getApplicationId();
Long activeSession = activeSessions.get(applicationId);
if (activeSession == null || activeSession != candidate.getSessionId()) {
deleteLocalSession(candidate);
log.log(Level.INFO, "Deleted inactive session " + candidate.getSessionId() + " created " +
createTime + " for '" + applicationId + "'");
}
}
}
} catch (Throwable e) {
log.log(Level.WARNING, "Error when purging old sessions ", e);
}
log.log(Level.FINE, "Done purging old sessions");
}
private boolean hasExpired(LocalSession candidate) {
return (candidate.getCreateTime().plus(sessionLifetime).isBefore(clock.instant()));
}
private boolean isActiveSession(LocalSession candidate) {
return candidate.getStatus() == Session.Status.ACTIVATE;
}
public void deleteLocalSession(LocalSession session) {
long sessionId = session.getSessionId();
log.log(Level.FINE, "Deleting local session " + sessionId);
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
localSessionCache.removeSession(sessionId);
NestedTransaction transaction = new NestedTransaction();
deleteLocalSession(session, transaction);
transaction.commit();
}
/** Add transactions to delete this session to the given nested transaction */
public void deleteLocalSession(LocalSession session, NestedTransaction transaction) {
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
transaction.add(sessionZooKeeperClient.deleteTransaction(), FileTransaction.class);
transaction.add(FileTransaction.from(FileOperations.delete(getSessionAppDir(sessionId).getAbsolutePath())));
}
public void close() {
deleteAllSessions();
tenantFileSystemDirs.delete();
try {
if (directoryCache != null) {
directoryCache.close();
}
} catch (Exception e) {
log.log(Level.WARNING, "Exception when closing path cache", e);
} finally {
checkForRemovedSessions(new ArrayList<>());
}
}
private void deleteAllSessions() {
List<LocalSession> sessions = new ArrayList<>(localSessionCache.getSessions());
for (LocalSession session : sessions) {
deleteLocalSession(session);
}
}
public RemoteSession getRemoteSession(long sessionId) {
return remoteSessionCache.getSession(sessionId);
}
public List<Long> getRemoteSessions() {
return getSessionList(curator.getChildren(sessionsPath));
}
public void addRemoteSession(RemoteSession session) {
remoteSessionCache.addSession(session);
metrics.incAddedSessions();
}
public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) {
int deleted = 0;
for (long sessionId : getRemoteSessions()) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
if (session.getStatus() == Session.Status.ACTIVATE) continue;
if (sessionHasExpired(session.getCreateTime(), expiryTime, clock)) {
log.log(Level.INFO, "Remote session " + sessionId + " for " + tenantName + " has expired, deleting it");
session.delete();
deleted++;
}
}
return deleted;
}
private boolean sessionHasExpired(Instant created, Duration expiryTime, Clock clock) {
return (created.plus(expiryTime).isBefore(clock.instant()));
}
private List<Long> getSessionListFromDirectoryCache(List<ChildData> children) {
return getSessionList(children.stream()
.map(child -> Path.fromString(child.getPath()).getName())
.collect(Collectors.toList()));
}
private List<Long> getSessionList(List<String> children) {
return children.stream().map(Long::parseLong).collect(Collectors.toList());
}
private void initializeRemoteSessions() throws NumberFormatException {
getRemoteSessions().forEach(this::sessionAdded);
}
private synchronized void sessionsChanged() throws NumberFormatException {
List<Long> sessions = getSessionListFromDirectoryCache(directoryCache.getCurrentData());
checkForRemovedSessions(sessions);
checkForAddedSessions(sessions);
}
private void checkForRemovedSessions(List<Long> sessions) {
for (RemoteSession session : remoteSessionCache.getSessions())
if ( ! sessions.contains(session.getSessionId()))
sessionRemoved(session.getSessionId());
}
private void checkForAddedSessions(List<Long> sessions) {
for (Long sessionId : sessions)
if (remoteSessionCache.getSession(sessionId) == null)
sessionAdded(sessionId);
}
/**
* A session for which we don't have a watcher, i.e. hitherto unknown to us.
*
* @param sessionId session id for the new session
*/
public void sessionAdded(long sessionId) {
log.log(Level.FINE, () -> "Adding remote session to SessionRepository: " + sessionId);
RemoteSession remoteSession = createRemoteSession(sessionId);
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
fileCache.addListener(this::nodeChanged);
loadSessionIfActive(remoteSession);
addRemoteSession(remoteSession);
Optional<LocalSession> localSession = Optional.empty();
if (distributeApplicationPackage.value()) {
localSession = createLocalSessionUsingDistributedApplicationPackage(sessionId);
localSession.ifPresent(this::addSession);
}
addWatcher(sessionId, fileCache, remoteSession, localSession);
}
private void sessionRemoved(long sessionId) {
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
remoteSessionCache.removeSession(sessionId);
metrics.incRemovedSessions();
}
private void loadSessionIfActive(RemoteSession session) {
for (ApplicationId applicationId : applicationRepo.activeApplications()) {
if (applicationRepo.requireActiveSessionOf(applicationId) == session.getSessionId()) {
log.log(Level.FINE, () -> "Found active application for session " + session.getSessionId() + " , loading it");
reloadHandler.reloadConfig(session.ensureApplicationLoaded());
log.log(Level.INFO, session.logPre() + "Application activated successfully: " + applicationId + " (generation " + session.getSessionId() + ")");
return;
}
}
}
private void nodeChanged() {
zkWatcherExecutor.execute(() -> {
Multiset<Session.Status> sessionMetrics = HashMultiset.create();
for (RemoteSession session : remoteSessionCache.getSessions()) {
sessionMetrics.add(session.getStatus());
}
metrics.setNewSessions(sessionMetrics.count(Session.Status.NEW));
metrics.setPreparedSessions(sessionMetrics.count(Session.Status.PREPARE));
metrics.setActivatedSessions(sessionMetrics.count(Session.Status.ACTIVATE));
metrics.setDeactivatedSessions(sessionMetrics.count(Session.Status.DEACTIVATE));
});
}
@SuppressWarnings("unused")
private void childEvent(CuratorFramework ignored, PathChildrenCacheEvent event) {
zkWatcherExecutor.execute(() -> {
log.log(Level.FINE, () -> "Got child event: " + event);
switch (event.getType()) {
case CHILD_ADDED:
sessionsChanged();
synchronizeOnNew(getSessionListFromDirectoryCache(Collections.singletonList(event.getData())));
break;
case CHILD_REMOVED:
case CONNECTION_RECONNECTED:
sessionsChanged();
break;
}
});
}
private void synchronizeOnNew(List<Long> sessionList) {
for (long sessionId : sessionList) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
log.log(Level.FINE, () -> session.logPre() + "Confirming upload for session " + sessionId);
session.confirmUpload();
}
}
/**
* Creates a new deployment session from an application package.
*
* @param applicationDirectory a File pointing to an application.
* @param applicationId application id for this new session.
* @param timeoutBudget Timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSession(File applicationDirectory, ApplicationId applicationId,
TimeoutBudget timeoutBudget, Optional<Long> activeSessionId) {
return create(applicationDirectory, applicationId, activeSessionId, false, timeoutBudget);
}
public RemoteSession createRemoteSession(long sessionId) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new RemoteSession(tenantName, sessionId, componentRegistry, sessionZKClient);
}
private void ensureSessionPathDoesNotExist(long sessionId) {
Path sessionPath = getSessionPath(sessionId);
if (componentRegistry.getConfigCurator().exists(sessionPath.getAbsolute())) {
throw new IllegalArgumentException("Path " + sessionPath.getAbsolute() + " already exists in ZooKeeper");
}
}
private ApplicationPackage createApplication(File userDir,
File configApplicationDir,
ApplicationId applicationId,
long sessionId,
Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) {
long deployTimestamp = System.currentTimeMillis();
String user = System.getenv("USER");
if (user == null) {
user = "unknown";
}
DeployData deployData = new DeployData(user, userDir.getAbsolutePath(), applicationId, deployTimestamp,
internalRedeploy, sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSession));
return FilesApplicationPackage.fromFileWithDeployData(configApplicationDir, deployData);
}
private LocalSession createSessionFromApplication(ApplicationPackage applicationPackage,
long sessionId,
TimeoutBudget timeoutBudget,
Clock clock) {
log.log(Level.FINE, TenantRepository.logPre(tenantName) + "Creating session " + sessionId + " in ZooKeeper");
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
sessionZKClient.createNewSession(clock.instant());
Curator.CompletionWaiter waiter = sessionZKClient.getUploadWaiter();
LocalSession session = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
waiter.awaitCompletion(timeoutBudget.timeLeft());
return session;
}
/**
* Creates a new deployment session from an already existing session.
*
* @param existingSession the session to use as base
* @param logger a deploy logger where the deploy log will be written.
* @param internalRedeploy whether this session is for a system internal redeploy — not an application package change
* @param timeoutBudget timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSessionFromExisting(Session existingSession,
DeployLogger logger,
boolean internalRedeploy,
TimeoutBudget timeoutBudget) {
File existingApp = getSessionAppDir(existingSession.getSessionId());
ApplicationId existingApplicationId = existingSession.getApplicationId();
Optional<Long> activeSessionId = getActiveSessionId(existingApplicationId);
logger.log(Level.FINE, "Create new session for application id '" + existingApplicationId + "' from existing active session " + activeSessionId);
LocalSession session = create(existingApp, existingApplicationId, activeSessionId, internalRedeploy, timeoutBudget);
session.setApplicationId(existingApplicationId);
if (distributeApplicationPackage.value() && existingSession.getApplicationPackageReference() != null) {
session.setApplicationPackageReference(existingSession.getApplicationPackageReference());
}
session.setVespaVersion(existingSession.getVespaVersion());
session.setDockerImageRepository(existingSession.getDockerImageRepository());
session.setAthenzDomain(existingSession.getAthenzDomain());
return session;
}
private LocalSession create(File applicationFile, ApplicationId applicationId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy, TimeoutBudget timeoutBudget) {
long sessionId = getNextSessionId();
try {
ensureSessionPathDoesNotExist(sessionId);
ApplicationPackage app = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, internalRedeploy);
return createSessionFromApplication(app, sessionId, timeoutBudget, clock);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
/**
* This method is used when creating a session based on a remote session and the distributed application package
* It does not wait for session being created on other servers
*/
private LocalSession createLocalSession(File applicationFile, ApplicationId applicationId, long sessionId) {
try {
Optional<Long> currentlyActiveSessionId = getActiveSessionId(applicationId);
ApplicationPackage applicationPackage = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, false);
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZooKeeperClient, applicationRepo);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
private ApplicationPackage createApplicationPackage(File applicationFile, ApplicationId applicationId,
long sessionId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) throws IOException {
File userApplicationDir = getSessionAppDir(sessionId);
copyApp(applicationFile, userApplicationDir);
ApplicationPackage applicationPackage = createApplication(applicationFile,
userApplicationDir,
applicationId,
sessionId,
currentlyActiveSessionId,
internalRedeploy);
applicationPackage.writeMetaData();
return applicationPackage;
}
/**
* Returns a new session instance for the given session id.
*/
LocalSession createSessionFromId(long sessionId) {
File sessionDir = getAndValidateExistingSessionAppDir(sessionId);
ApplicationPackage applicationPackage = FilesApplicationPackage.fromFile(sessionDir);
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
}
/**
* Returns a new session instance for the given session id.
*/
public Optional<LocalSession> createLocalSessionUsingDistributedApplicationPackage(long sessionId) {
if (applicationRepo.hasLocalSession(sessionId)) {
log.log(Level.FINE, "Local session for session id " + sessionId + " already exists");
return Optional.of(createSessionFromId(sessionId));
}
log.log(Level.INFO, "Creating local session for session id " + sessionId);
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
FileReference fileReference = sessionZKClient.readApplicationPackageReference();
log.log(Level.FINE, "File reference for session id " + sessionId + ": " + fileReference);
if (fileReference != null) {
File rootDir = new File(Defaults.getDefaults().underVespaHome(componentRegistry.getConfigserverConfig().fileReferencesDir()));
File sessionDir;
FileDirectory fileDirectory = new FileDirectory(rootDir);
try {
sessionDir = fileDirectory.getFile(fileReference);
} catch (IllegalArgumentException e) {
log.log(Level.INFO, "File reference for session id " + sessionId + ": " + fileReference + " not found in " + fileDirectory);
return Optional.empty();
}
ApplicationId applicationId = sessionZKClient.readApplicationId();
LocalSession localSession = createLocalSession(sessionDir, applicationId, sessionId);
addSession(localSession);
return Optional.of(localSession);
}
return Optional.empty();
}
private Optional<Long> getActiveSessionId(ApplicationId applicationId) {
List<ApplicationId> applicationIds = applicationRepo.activeApplications();
return applicationIds.contains(applicationId)
? Optional.of(applicationRepo.requireActiveSessionOf(applicationId))
: Optional.empty();
}
private long getNextSessionId() {
return new SessionCounter(componentRegistry.getConfigCurator(), tenantName).nextSessionId();
}
public Path getSessionPath(long sessionId) {
return sessionsPath.append(String.valueOf(sessionId));
}
Path getSessionStatePath(long sessionId) {
return getSessionPath(sessionId).append(ConfigCurator.SESSIONSTATE_ZK_SUBPATH);
}
private SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) {
String serverId = componentRegistry.getConfigserverConfig().serverId();
Optional<NodeFlavors> nodeFlavors = componentRegistry.getZone().nodeFlavors();
Path sessionPath = getSessionPath(sessionId);
return new SessionZooKeeperClient(curator, componentRegistry.getConfigCurator(), sessionPath, serverId, nodeFlavors);
}
private File getAndValidateExistingSessionAppDir(long sessionId) {
File appDir = getSessionAppDir(sessionId);
if (!appDir.exists() || !appDir.isDirectory()) {
throw new IllegalArgumentException("Unable to find correct application directory for session " + sessionId);
}
return appDir;
}
private File getSessionAppDir(long sessionId) {
return new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName).getUserApplicationDir(sessionId);
}
private void addWatcher(long sessionId, Curator.FileCache fileCache, RemoteSession remoteSession, Optional<LocalSession> localSession) {
if (sessionStateWatchers.containsKey(sessionId)) {
localSession.ifPresent(session -> sessionStateWatchers.get(sessionId).addLocalSession(session));
} else {
sessionStateWatchers.put(sessionId, new SessionStateWatcher(fileCache, reloadHandler, remoteSession,
localSession, metrics, zkWatcherExecutor, this));
}
}
@Override
public String toString() {
return getLocalSessions().toString();
}
public ReloadHandler getReloadHandler() { return reloadHandler; }
private static class FileTransaction extends AbstractTransaction {
public static FileTransaction from(FileOperation operation) {
FileTransaction transaction = new FileTransaction();
transaction.add(operation);
return transaction;
}
@Override
public void prepare() { }
@Override
public void commit() {
for (Operation operation : operations())
((FileOperation)operation).commit();
}
}
/** Factory for file operations */
private static class FileOperations {
/** Creates an operation which recursively deletes the given path */
public static DeleteOperation delete(String pathToDelete) {
return new DeleteOperation(pathToDelete);
}
}
private interface FileOperation extends Transaction.Operation {
void commit();
}
/**
* Recursively deletes this path and everything below.
* Succeeds with no action if the path does not exist.
*/
private static class DeleteOperation implements FileOperation {
private final String pathToDelete;
DeleteOperation(String pathToDelete) {
this.pathToDelete = pathToDelete;
}
@Override
public void commit() {
IOUtils.recursiveDeleteDir(new File(pathToDelete));
}
}
} | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSession = 0;
private final SessionCache<LocalSession> localSessionCache = new SessionCache<>();
private final SessionCache<RemoteSession> remoteSessionCache = new SessionCache<>();
private final Map<Long, SessionStateWatcher> sessionStateWatchers = new HashMap<>();
private final Duration sessionLifetime;
private final Clock clock;
private final Curator curator;
private final Executor zkWatcherExecutor;
private final TenantFileSystemDirs tenantFileSystemDirs;
private final BooleanFlag distributeApplicationPackage;
private final ReloadHandler reloadHandler;
private final MetricUpdater metrics;
private final Curator.DirectoryCache directoryCache;
private final TenantApplications applicationRepo;
private final SessionPreparer sessionPreparer;
private final Path sessionsPath;
private final TenantName tenantName;
private final GlobalComponentRegistry componentRegistry;
public SessionRepository(TenantName tenantName,
GlobalComponentRegistry componentRegistry,
TenantApplications applicationRepo,
ReloadHandler reloadHandler,
FlagSource flagSource,
SessionPreparer sessionPreparer) {
this.tenantName = tenantName;
this.componentRegistry = componentRegistry;
this.sessionsPath = TenantRepository.getSessionsPath(tenantName);
this.clock = componentRegistry.getClock();
this.curator = componentRegistry.getCurator();
this.sessionLifetime = Duration.ofSeconds(componentRegistry.getConfigserverConfig().sessionLifetime());
this.zkWatcherExecutor = command -> componentRegistry.getZkWatcherExecutor().execute(tenantName, command);
this.tenantFileSystemDirs = new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName);
this.applicationRepo = applicationRepo;
this.sessionPreparer = sessionPreparer;
this.distributeApplicationPackage = Flags.CONFIGSERVER_DISTRIBUTE_APPLICATION_PACKAGE.bindTo(flagSource);
this.reloadHandler = reloadHandler;
this.metrics = componentRegistry.getMetrics().getOrCreateMetricUpdater(Metrics.createDimensions(tenantName));
loadLocalSessions();
initializeRemoteSessions();
this.directoryCache = curator.createDirectoryCache(sessionsPath.getAbsolute(), false, false, componentRegistry.getZkCacheExecutor());
this.directoryCache.addListener(this::childEvent);
this.directoryCache.start();
}
public synchronized void addSession(LocalSession session) {
localSessionCache.addSession(session);
long sessionId = session.getSessionId();
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
RemoteSession remoteSession = new RemoteSession(tenantName, sessionId, componentRegistry, createSessionZooKeeperClient(sessionId));
addWatcher(sessionId, fileCache, remoteSession, Optional.of(session));
}
public LocalSession getLocalSession(long sessionId) {
return localSessionCache.getSession(sessionId);
}
public List<LocalSession> getLocalSessions() {
return localSessionCache.getSessions();
}
private void loadLocalSessions() {
File[] sessions = tenantFileSystemDirs.sessionsPath().listFiles(sessionApplicationsFilter);
if (sessions == null) {
return;
}
for (File session : sessions) {
try {
addSession(createSessionFromId(Long.parseLong(session.getName())));
} catch (IllegalArgumentException e) {
log.log(Level.WARNING, "Could not load session '" +
session.getAbsolutePath() + "':" + e.getMessage() + ", skipping it.");
}
}
}
public ConfigChangeActions prepareLocalSession(LocalSession session,
DeployLogger logger,
PrepareParams params,
Optional<ApplicationSet> currentActiveApplicationSet,
Path tenantPath,
Instant now) {
applicationRepo.createApplication(params.getApplicationId());
logger.log(Level.FINE, "Created application " + params.getApplicationId());
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
Curator.CompletionWaiter waiter = sessionZooKeeperClient.createPrepareWaiter();
ConfigChangeActions actions = sessionPreparer.prepare(applicationRepo.getHostValidator(), logger, params,
currentActiveApplicationSet, tenantPath, now,
getSessionAppDir(sessionId),
session.getApplicationPackage(), sessionZooKeeperClient);
session.setPrepared();
waiter.awaitCompletion(params.getTimeoutBudget().timeLeft());
return actions;
}
public void deleteExpiredSessions(Map<ApplicationId, Long> activeSessions) {
log.log(Level.FINE, "Purging old sessions");
try {
for (LocalSession candidate : localSessionCache.getSessions()) {
Instant createTime = candidate.getCreateTime();
log.log(Level.FINE, "Candidate session for deletion: " + candidate.getSessionId() + ", created: " + createTime);
if (hasExpired(candidate) && !isActiveSession(candidate)) {
deleteLocalSession(candidate);
} else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) {
ApplicationId applicationId = candidate.getApplicationId();
Long activeSession = activeSessions.get(applicationId);
if (activeSession == null || activeSession != candidate.getSessionId()) {
deleteLocalSession(candidate);
log.log(Level.INFO, "Deleted inactive session " + candidate.getSessionId() + " created " +
createTime + " for '" + applicationId + "'");
}
}
}
} catch (Throwable e) {
log.log(Level.WARNING, "Error when purging old sessions ", e);
}
log.log(Level.FINE, "Done purging old sessions");
}
private boolean hasExpired(LocalSession candidate) {
return (candidate.getCreateTime().plus(sessionLifetime).isBefore(clock.instant()));
}
private boolean isActiveSession(LocalSession candidate) {
return candidate.getStatus() == Session.Status.ACTIVATE;
}
public void deleteLocalSession(LocalSession session) {
long sessionId = session.getSessionId();
log.log(Level.FINE, "Deleting local session " + sessionId);
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
localSessionCache.removeSession(sessionId);
NestedTransaction transaction = new NestedTransaction();
deleteLocalSession(session, transaction);
transaction.commit();
}
/** Add transactions to delete this session to the given nested transaction */
public void deleteLocalSession(LocalSession session, NestedTransaction transaction) {
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
transaction.add(sessionZooKeeperClient.deleteTransaction(), FileTransaction.class);
transaction.add(FileTransaction.from(FileOperations.delete(getSessionAppDir(sessionId).getAbsolutePath())));
}
public void close() {
deleteAllSessions();
tenantFileSystemDirs.delete();
try {
if (directoryCache != null) {
directoryCache.close();
}
} catch (Exception e) {
log.log(Level.WARNING, "Exception when closing path cache", e);
} finally {
checkForRemovedSessions(new ArrayList<>());
}
}
private void deleteAllSessions() {
List<LocalSession> sessions = new ArrayList<>(localSessionCache.getSessions());
for (LocalSession session : sessions) {
deleteLocalSession(session);
}
}
public RemoteSession getRemoteSession(long sessionId) {
return remoteSessionCache.getSession(sessionId);
}
public List<Long> getRemoteSessions() {
return getSessionList(curator.getChildren(sessionsPath));
}
public void addRemoteSession(RemoteSession session) {
remoteSessionCache.addSession(session);
metrics.incAddedSessions();
}
public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) {
int deleted = 0;
for (long sessionId : getRemoteSessions()) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
if (session.getStatus() == Session.Status.ACTIVATE) continue;
if (sessionHasExpired(session.getCreateTime(), expiryTime, clock)) {
log.log(Level.INFO, "Remote session " + sessionId + " for " + tenantName + " has expired, deleting it");
session.delete();
deleted++;
}
}
return deleted;
}
private boolean sessionHasExpired(Instant created, Duration expiryTime, Clock clock) {
return (created.plus(expiryTime).isBefore(clock.instant()));
}
private List<Long> getSessionListFromDirectoryCache(List<ChildData> children) {
return getSessionList(children.stream()
.map(child -> Path.fromString(child.getPath()).getName())
.collect(Collectors.toList()));
}
private List<Long> getSessionList(List<String> children) {
return children.stream().map(Long::parseLong).collect(Collectors.toList());
}
private void initializeRemoteSessions() throws NumberFormatException {
getRemoteSessions().forEach(this::sessionAdded);
}
private synchronized void sessionsChanged() throws NumberFormatException {
List<Long> sessions = getSessionListFromDirectoryCache(directoryCache.getCurrentData());
checkForRemovedSessions(sessions);
checkForAddedSessions(sessions);
}
private void checkForRemovedSessions(List<Long> sessions) {
for (RemoteSession session : remoteSessionCache.getSessions())
if ( ! sessions.contains(session.getSessionId()))
sessionRemoved(session.getSessionId());
}
private void checkForAddedSessions(List<Long> sessions) {
for (Long sessionId : sessions)
if (remoteSessionCache.getSession(sessionId) == null)
sessionAdded(sessionId);
}
/**
* A session for which we don't have a watcher, i.e. hitherto unknown to us.
*
* @param sessionId session id for the new session
*/
public void sessionAdded(long sessionId) {
log.log(Level.FINE, () -> "Adding remote session to SessionRepository: " + sessionId);
RemoteSession remoteSession = createRemoteSession(sessionId);
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
fileCache.addListener(this::nodeChanged);
loadSessionIfActive(remoteSession);
addRemoteSession(remoteSession);
Optional<LocalSession> localSession = Optional.empty();
if (distributeApplicationPackage.value()) {
localSession = createLocalSessionUsingDistributedApplicationPackage(sessionId);
localSession.ifPresent(this::addSession);
}
addWatcher(sessionId, fileCache, remoteSession, localSession);
}
private void sessionRemoved(long sessionId) {
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
remoteSessionCache.removeSession(sessionId);
metrics.incRemovedSessions();
}
private void loadSessionIfActive(RemoteSession session) {
for (ApplicationId applicationId : applicationRepo.activeApplications()) {
if (applicationRepo.requireActiveSessionOf(applicationId) == session.getSessionId()) {
log.log(Level.FINE, () -> "Found active application for session " + session.getSessionId() + " , loading it");
reloadHandler.reloadConfig(session.ensureApplicationLoaded());
log.log(Level.INFO, session.logPre() + "Application activated successfully: " + applicationId + " (generation " + session.getSessionId() + ")");
return;
}
}
}
private void nodeChanged() {
zkWatcherExecutor.execute(() -> {
Multiset<Session.Status> sessionMetrics = HashMultiset.create();
for (RemoteSession session : remoteSessionCache.getSessions()) {
sessionMetrics.add(session.getStatus());
}
metrics.setNewSessions(sessionMetrics.count(Session.Status.NEW));
metrics.setPreparedSessions(sessionMetrics.count(Session.Status.PREPARE));
metrics.setActivatedSessions(sessionMetrics.count(Session.Status.ACTIVATE));
metrics.setDeactivatedSessions(sessionMetrics.count(Session.Status.DEACTIVATE));
});
}
@SuppressWarnings("unused")
private void childEvent(CuratorFramework ignored, PathChildrenCacheEvent event) {
zkWatcherExecutor.execute(() -> {
log.log(Level.FINE, () -> "Got child event: " + event);
switch (event.getType()) {
case CHILD_ADDED:
sessionsChanged();
synchronizeOnNew(getSessionListFromDirectoryCache(Collections.singletonList(event.getData())));
break;
case CHILD_REMOVED:
case CONNECTION_RECONNECTED:
sessionsChanged();
break;
}
});
}
private void synchronizeOnNew(List<Long> sessionList) {
for (long sessionId : sessionList) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
log.log(Level.FINE, () -> session.logPre() + "Confirming upload for session " + sessionId);
session.confirmUpload();
}
}
/**
* Creates a new deployment session from an application package.
*
* @param applicationDirectory a File pointing to an application.
* @param applicationId application id for this new session.
* @param timeoutBudget Timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSession(File applicationDirectory, ApplicationId applicationId,
TimeoutBudget timeoutBudget, Optional<Long> activeSessionId) {
return create(applicationDirectory, applicationId, activeSessionId, false, timeoutBudget);
}
public RemoteSession createRemoteSession(long sessionId) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new RemoteSession(tenantName, sessionId, componentRegistry, sessionZKClient);
}
private void ensureSessionPathDoesNotExist(long sessionId) {
Path sessionPath = getSessionPath(sessionId);
if (componentRegistry.getConfigCurator().exists(sessionPath.getAbsolute())) {
throw new IllegalArgumentException("Path " + sessionPath.getAbsolute() + " already exists in ZooKeeper");
}
}
private ApplicationPackage createApplication(File userDir,
File configApplicationDir,
ApplicationId applicationId,
long sessionId,
Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) {
long deployTimestamp = System.currentTimeMillis();
String user = System.getenv("USER");
if (user == null) {
user = "unknown";
}
DeployData deployData = new DeployData(user, userDir.getAbsolutePath(), applicationId, deployTimestamp,
internalRedeploy, sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSession));
return FilesApplicationPackage.fromFileWithDeployData(configApplicationDir, deployData);
}
private LocalSession createSessionFromApplication(ApplicationPackage applicationPackage,
long sessionId,
TimeoutBudget timeoutBudget,
Clock clock) {
log.log(Level.FINE, TenantRepository.logPre(tenantName) + "Creating session " + sessionId + " in ZooKeeper");
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
sessionZKClient.createNewSession(clock.instant());
Curator.CompletionWaiter waiter = sessionZKClient.getUploadWaiter();
LocalSession session = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
waiter.awaitCompletion(timeoutBudget.timeLeft());
return session;
}
/**
* Creates a new deployment session from an already existing session.
*
* @param existingSession the session to use as base
* @param logger a deploy logger where the deploy log will be written.
* @param internalRedeploy whether this session is for a system internal redeploy — not an application package change
* @param timeoutBudget timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSessionFromExisting(Session existingSession,
DeployLogger logger,
boolean internalRedeploy,
TimeoutBudget timeoutBudget) {
File existingApp = getSessionAppDir(existingSession.getSessionId());
ApplicationId existingApplicationId = existingSession.getApplicationId();
Optional<Long> activeSessionId = getActiveSessionId(existingApplicationId);
logger.log(Level.FINE, "Create new session for application id '" + existingApplicationId + "' from existing active session " + activeSessionId);
LocalSession session = create(existingApp, existingApplicationId, activeSessionId, internalRedeploy, timeoutBudget);
session.setApplicationId(existingApplicationId);
if (distributeApplicationPackage.value() && existingSession.getApplicationPackageReference() != null) {
session.setApplicationPackageReference(existingSession.getApplicationPackageReference());
}
session.setVespaVersion(existingSession.getVespaVersion());
session.setDockerImageRepository(existingSession.getDockerImageRepository());
session.setAthenzDomain(existingSession.getAthenzDomain());
return session;
}
private LocalSession create(File applicationFile, ApplicationId applicationId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy, TimeoutBudget timeoutBudget) {
long sessionId = getNextSessionId();
try {
ensureSessionPathDoesNotExist(sessionId);
ApplicationPackage app = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, internalRedeploy);
return createSessionFromApplication(app, sessionId, timeoutBudget, clock);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
/**
* This method is used when creating a session based on a remote session and the distributed application package
* It does not wait for session being created on other servers
*/
private LocalSession createLocalSession(File applicationFile, ApplicationId applicationId, long sessionId) {
try {
Optional<Long> currentlyActiveSessionId = getActiveSessionId(applicationId);
ApplicationPackage applicationPackage = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, false);
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZooKeeperClient, applicationRepo);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
private ApplicationPackage createApplicationPackage(File applicationFile, ApplicationId applicationId,
long sessionId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) throws IOException {
File userApplicationDir = getSessionAppDir(sessionId);
copyApp(applicationFile, userApplicationDir);
ApplicationPackage applicationPackage = createApplication(applicationFile,
userApplicationDir,
applicationId,
sessionId,
currentlyActiveSessionId,
internalRedeploy);
applicationPackage.writeMetaData();
return applicationPackage;
}
/**
* Returns a new session instance for the given session id.
*/
LocalSession createSessionFromId(long sessionId) {
File sessionDir = getAndValidateExistingSessionAppDir(sessionId);
ApplicationPackage applicationPackage = FilesApplicationPackage.fromFile(sessionDir);
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
}
/**
* Returns a new session instance for the given session id.
*/
public Optional<LocalSession> createLocalSessionUsingDistributedApplicationPackage(long sessionId) {
if (applicationRepo.hasLocalSession(sessionId)) {
log.log(Level.FINE, "Local session for session id " + sessionId + " already exists");
return Optional.of(createSessionFromId(sessionId));
}
log.log(Level.INFO, "Creating local session for session id " + sessionId);
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
FileReference fileReference = sessionZKClient.readApplicationPackageReference();
log.log(Level.FINE, "File reference for session id " + sessionId + ": " + fileReference);
if (fileReference != null) {
File rootDir = new File(Defaults.getDefaults().underVespaHome(componentRegistry.getConfigserverConfig().fileReferencesDir()));
File sessionDir;
FileDirectory fileDirectory = new FileDirectory(rootDir);
try {
sessionDir = fileDirectory.getFile(fileReference);
} catch (IllegalArgumentException e) {
log.log(Level.INFO, "File reference for session id " + sessionId + ": " + fileReference + " not found in " + fileDirectory);
return Optional.empty();
}
ApplicationId applicationId = sessionZKClient.readApplicationId();
LocalSession localSession = createLocalSession(sessionDir, applicationId, sessionId);
addSession(localSession);
return Optional.of(localSession);
}
return Optional.empty();
}
private Optional<Long> getActiveSessionId(ApplicationId applicationId) {
List<ApplicationId> applicationIds = applicationRepo.activeApplications();
return applicationIds.contains(applicationId)
? Optional.of(applicationRepo.requireActiveSessionOf(applicationId))
: Optional.empty();
}
private long getNextSessionId() {
return new SessionCounter(componentRegistry.getConfigCurator(), tenantName).nextSessionId();
}
public Path getSessionPath(long sessionId) {
return sessionsPath.append(String.valueOf(sessionId));
}
Path getSessionStatePath(long sessionId) {
return getSessionPath(sessionId).append(ConfigCurator.SESSIONSTATE_ZK_SUBPATH);
}
private SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) {
String serverId = componentRegistry.getConfigserverConfig().serverId();
Optional<NodeFlavors> nodeFlavors = componentRegistry.getZone().nodeFlavors();
Path sessionPath = getSessionPath(sessionId);
return new SessionZooKeeperClient(curator, componentRegistry.getConfigCurator(), sessionPath, serverId, nodeFlavors);
}
private File getAndValidateExistingSessionAppDir(long sessionId) {
File appDir = getSessionAppDir(sessionId);
if (!appDir.exists() || !appDir.isDirectory()) {
throw new IllegalArgumentException("Unable to find correct application directory for session " + sessionId);
}
return appDir;
}
private File getSessionAppDir(long sessionId) {
return new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName).getUserApplicationDir(sessionId);
}
private void addWatcher(long sessionId, Curator.FileCache fileCache, RemoteSession remoteSession, Optional<LocalSession> localSession) {
if (sessionStateWatchers.containsKey(sessionId)) {
localSession.ifPresent(session -> sessionStateWatchers.get(sessionId).addLocalSession(session));
} else {
sessionStateWatchers.put(sessionId, new SessionStateWatcher(fileCache, reloadHandler, remoteSession,
localSession, metrics, zkWatcherExecutor, this));
}
}
@Override
public String toString() {
return getLocalSessions().toString();
}
public ReloadHandler getReloadHandler() { return reloadHandler; }
private static class FileTransaction extends AbstractTransaction {
public static FileTransaction from(FileOperation operation) {
FileTransaction transaction = new FileTransaction();
transaction.add(operation);
return transaction;
}
@Override
public void prepare() { }
@Override
public void commit() {
for (Operation operation : operations())
((FileOperation)operation).commit();
}
}
/** Factory for file operations */
private static class FileOperations {
/** Creates an operation which recursively deletes the given path */
public static DeleteOperation delete(String pathToDelete) {
return new DeleteOperation(pathToDelete);
}
}
private interface FileOperation extends Transaction.Operation {
void commit();
}
/**
* Recursively deletes this path and everything below.
* Succeeds with no action if the path does not exist.
*/
private static class DeleteOperation implements FileOperation {
private final String pathToDelete;
DeleteOperation(String pathToDelete) {
this.pathToDelete = pathToDelete;
}
@Override
public void commit() {
IOUtils.recursiveDeleteDir(new File(pathToDelete));
}
}
} | |
thanks, will fix later | private void copyApp(File sourceDir, File destinationDir) throws IOException {
if (destinationDir.exists())
throw new RuntimeException("Destination dir " + destinationDir + " already exists");
if (! sourceDir.isDirectory())
throw new IllegalArgumentException(sourceDir.getAbsolutePath() + " is not a directory");
java.nio.file.Path tempDestinationDir = Files.createTempDirectory(destinationDir.getParentFile().toPath(), "app-package");
log.log(Level.FINE, "Copying dir " + sourceDir.getAbsolutePath() + " to " + tempDestinationDir.toFile().getAbsolutePath());
IOUtils.copyDirectory(sourceDir, tempDestinationDir.toFile());
log.log(Level.FINE, "Moving " + tempDestinationDir + " to " + destinationDir.getAbsolutePath());
Files.move(tempDestinationDir, destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE);
} | private void copyApp(File sourceDir, File destinationDir) throws IOException {
if (destinationDir.exists())
throw new RuntimeException("Destination dir " + destinationDir + " already exists");
if (! sourceDir.isDirectory())
throw new IllegalArgumentException(sourceDir.getAbsolutePath() + " is not a directory");
java.nio.file.Path tempDestinationDir = Files.createTempDirectory(destinationDir.getParentFile().toPath(), "app-package");
log.log(Level.FINE, "Copying dir " + sourceDir.getAbsolutePath() + " to " + tempDestinationDir.toFile().getAbsolutePath());
IOUtils.copyDirectory(sourceDir, tempDestinationDir.toFile());
log.log(Level.FINE, "Moving " + tempDestinationDir + " to " + destinationDir.getAbsolutePath());
Files.move(tempDestinationDir, destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE);
} | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSession = 0;
private final SessionCache<LocalSession> localSessionCache = new SessionCache<>();
private final SessionCache<RemoteSession> remoteSessionCache = new SessionCache<>();
private final Map<Long, SessionStateWatcher> sessionStateWatchers = new HashMap<>();
private final Duration sessionLifetime;
private final Clock clock;
private final Curator curator;
private final Executor zkWatcherExecutor;
private final TenantFileSystemDirs tenantFileSystemDirs;
private final BooleanFlag distributeApplicationPackage;
private final ReloadHandler reloadHandler;
private final MetricUpdater metrics;
private final Curator.DirectoryCache directoryCache;
private final TenantApplications applicationRepo;
private final SessionPreparer sessionPreparer;
private final Path sessionsPath;
private final TenantName tenantName;
private final GlobalComponentRegistry componentRegistry;
public SessionRepository(TenantName tenantName,
GlobalComponentRegistry componentRegistry,
TenantApplications applicationRepo,
ReloadHandler reloadHandler,
FlagSource flagSource,
SessionPreparer sessionPreparer) {
this.tenantName = tenantName;
this.componentRegistry = componentRegistry;
this.sessionsPath = TenantRepository.getSessionsPath(tenantName);
this.clock = componentRegistry.getClock();
this.curator = componentRegistry.getCurator();
this.sessionLifetime = Duration.ofSeconds(componentRegistry.getConfigserverConfig().sessionLifetime());
this.zkWatcherExecutor = command -> componentRegistry.getZkWatcherExecutor().execute(tenantName, command);
this.tenantFileSystemDirs = new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName);
this.applicationRepo = applicationRepo;
this.sessionPreparer = sessionPreparer;
this.distributeApplicationPackage = Flags.CONFIGSERVER_DISTRIBUTE_APPLICATION_PACKAGE.bindTo(flagSource);
this.reloadHandler = reloadHandler;
this.metrics = componentRegistry.getMetrics().getOrCreateMetricUpdater(Metrics.createDimensions(tenantName));
loadLocalSessions();
initializeRemoteSessions();
this.directoryCache = curator.createDirectoryCache(sessionsPath.getAbsolute(), false, false, componentRegistry.getZkCacheExecutor());
this.directoryCache.addListener(this::childEvent);
this.directoryCache.start();
}
public synchronized void addSession(LocalSession session) {
localSessionCache.addSession(session);
long sessionId = session.getSessionId();
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
RemoteSession remoteSession = new RemoteSession(tenantName, sessionId, componentRegistry, createSessionZooKeeperClient(sessionId));
addWatcher(sessionId, fileCache, remoteSession, Optional.of(session));
}
public LocalSession getLocalSession(long sessionId) {
return localSessionCache.getSession(sessionId);
}
public List<LocalSession> getLocalSessions() {
return localSessionCache.getSessions();
}
private void loadLocalSessions() {
File[] sessions = tenantFileSystemDirs.sessionsPath().listFiles(sessionApplicationsFilter);
if (sessions == null) {
return;
}
for (File session : sessions) {
try {
addSession(createSessionFromId(Long.parseLong(session.getName())));
} catch (IllegalArgumentException e) {
log.log(Level.WARNING, "Could not load session '" +
session.getAbsolutePath() + "':" + e.getMessage() + ", skipping it.");
}
}
}
public ConfigChangeActions prepareLocalSession(LocalSession session,
DeployLogger logger,
PrepareParams params,
Optional<ApplicationSet> currentActiveApplicationSet,
Path tenantPath,
Instant now) {
applicationRepo.createApplication(params.getApplicationId());
logger.log(Level.FINE, "Created application " + params.getApplicationId());
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
Curator.CompletionWaiter waiter = sessionZooKeeperClient.createPrepareWaiter();
ConfigChangeActions actions = sessionPreparer.prepare(applicationRepo.getHostValidator(), logger, params,
currentActiveApplicationSet, tenantPath, now,
getSessionAppDir(sessionId),
session.getApplicationPackage(), sessionZooKeeperClient);
session.setPrepared();
waiter.awaitCompletion(params.getTimeoutBudget().timeLeft());
return actions;
}
public void deleteExpiredSessions(Map<ApplicationId, Long> activeSessions) {
log.log(Level.FINE, "Purging old sessions");
try {
for (LocalSession candidate : localSessionCache.getSessions()) {
Instant createTime = candidate.getCreateTime();
log.log(Level.FINE, "Candidate session for deletion: " + candidate.getSessionId() + ", created: " + createTime);
if (hasExpired(candidate) && !isActiveSession(candidate)) {
deleteLocalSession(candidate);
} else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) {
ApplicationId applicationId = candidate.getApplicationId();
Long activeSession = activeSessions.get(applicationId);
if (activeSession == null || activeSession != candidate.getSessionId()) {
deleteLocalSession(candidate);
log.log(Level.INFO, "Deleted inactive session " + candidate.getSessionId() + " created " +
createTime + " for '" + applicationId + "'");
}
}
}
} catch (Throwable e) {
log.log(Level.WARNING, "Error when purging old sessions ", e);
}
log.log(Level.FINE, "Done purging old sessions");
}
private boolean hasExpired(LocalSession candidate) {
return (candidate.getCreateTime().plus(sessionLifetime).isBefore(clock.instant()));
}
private boolean isActiveSession(LocalSession candidate) {
return candidate.getStatus() == Session.Status.ACTIVATE;
}
public void deleteLocalSession(LocalSession session) {
long sessionId = session.getSessionId();
log.log(Level.FINE, "Deleting local session " + sessionId);
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
localSessionCache.removeSession(sessionId);
NestedTransaction transaction = new NestedTransaction();
deleteLocalSession(session, transaction);
transaction.commit();
}
/** Add transactions to delete this session to the given nested transaction */
public void deleteLocalSession(LocalSession session, NestedTransaction transaction) {
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
transaction.add(sessionZooKeeperClient.deleteTransaction(), FileTransaction.class);
transaction.add(FileTransaction.from(FileOperations.delete(getSessionAppDir(sessionId).getAbsolutePath())));
}
public void close() {
deleteAllSessions();
tenantFileSystemDirs.delete();
try {
if (directoryCache != null) {
directoryCache.close();
}
} catch (Exception e) {
log.log(Level.WARNING, "Exception when closing path cache", e);
} finally {
checkForRemovedSessions(new ArrayList<>());
}
}
private void deleteAllSessions() {
List<LocalSession> sessions = new ArrayList<>(localSessionCache.getSessions());
for (LocalSession session : sessions) {
deleteLocalSession(session);
}
}
public RemoteSession getRemoteSession(long sessionId) {
return remoteSessionCache.getSession(sessionId);
}
public List<Long> getRemoteSessions() {
return getSessionList(curator.getChildren(sessionsPath));
}
public void addRemoteSession(RemoteSession session) {
remoteSessionCache.addSession(session);
metrics.incAddedSessions();
}
public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) {
int deleted = 0;
for (long sessionId : getRemoteSessions()) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
if (session.getStatus() == Session.Status.ACTIVATE) continue;
if (sessionHasExpired(session.getCreateTime(), expiryTime, clock)) {
log.log(Level.INFO, "Remote session " + sessionId + " for " + tenantName + " has expired, deleting it");
session.delete();
deleted++;
}
}
return deleted;
}
private boolean sessionHasExpired(Instant created, Duration expiryTime, Clock clock) {
return (created.plus(expiryTime).isBefore(clock.instant()));
}
private List<Long> getSessionListFromDirectoryCache(List<ChildData> children) {
return getSessionList(children.stream()
.map(child -> Path.fromString(child.getPath()).getName())
.collect(Collectors.toList()));
}
private List<Long> getSessionList(List<String> children) {
return children.stream().map(Long::parseLong).collect(Collectors.toList());
}
private void initializeRemoteSessions() throws NumberFormatException {
getRemoteSessions().forEach(this::sessionAdded);
}
private synchronized void sessionsChanged() throws NumberFormatException {
List<Long> sessions = getSessionListFromDirectoryCache(directoryCache.getCurrentData());
checkForRemovedSessions(sessions);
checkForAddedSessions(sessions);
}
private void checkForRemovedSessions(List<Long> sessions) {
for (RemoteSession session : remoteSessionCache.getSessions())
if ( ! sessions.contains(session.getSessionId()))
sessionRemoved(session.getSessionId());
}
private void checkForAddedSessions(List<Long> sessions) {
for (Long sessionId : sessions)
if (remoteSessionCache.getSession(sessionId) == null)
sessionAdded(sessionId);
}
/**
* A session for which we don't have a watcher, i.e. hitherto unknown to us.
*
* @param sessionId session id for the new session
*/
public void sessionAdded(long sessionId) {
log.log(Level.FINE, () -> "Adding remote session to SessionRepository: " + sessionId);
RemoteSession remoteSession = createRemoteSession(sessionId);
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
fileCache.addListener(this::nodeChanged);
loadSessionIfActive(remoteSession);
addRemoteSession(remoteSession);
Optional<LocalSession> localSession = Optional.empty();
if (distributeApplicationPackage.value()) {
localSession = createLocalSessionUsingDistributedApplicationPackage(sessionId);
localSession.ifPresent(this::addSession);
}
addWatcher(sessionId, fileCache, remoteSession, localSession);
}
private void sessionRemoved(long sessionId) {
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
remoteSessionCache.removeSession(sessionId);
metrics.incRemovedSessions();
}
private void loadSessionIfActive(RemoteSession session) {
for (ApplicationId applicationId : applicationRepo.activeApplications()) {
if (applicationRepo.requireActiveSessionOf(applicationId) == session.getSessionId()) {
log.log(Level.FINE, () -> "Found active application for session " + session.getSessionId() + " , loading it");
reloadHandler.reloadConfig(session.ensureApplicationLoaded());
log.log(Level.INFO, session.logPre() + "Application activated successfully: " + applicationId + " (generation " + session.getSessionId() + ")");
return;
}
}
}
private void nodeChanged() {
zkWatcherExecutor.execute(() -> {
Multiset<Session.Status> sessionMetrics = HashMultiset.create();
for (RemoteSession session : remoteSessionCache.getSessions()) {
sessionMetrics.add(session.getStatus());
}
metrics.setNewSessions(sessionMetrics.count(Session.Status.NEW));
metrics.setPreparedSessions(sessionMetrics.count(Session.Status.PREPARE));
metrics.setActivatedSessions(sessionMetrics.count(Session.Status.ACTIVATE));
metrics.setDeactivatedSessions(sessionMetrics.count(Session.Status.DEACTIVATE));
});
}
@SuppressWarnings("unused")
private void childEvent(CuratorFramework ignored, PathChildrenCacheEvent event) {
zkWatcherExecutor.execute(() -> {
log.log(Level.FINE, () -> "Got child event: " + event);
switch (event.getType()) {
case CHILD_ADDED:
sessionsChanged();
synchronizeOnNew(getSessionListFromDirectoryCache(Collections.singletonList(event.getData())));
break;
case CHILD_REMOVED:
case CONNECTION_RECONNECTED:
sessionsChanged();
break;
}
});
}
private void synchronizeOnNew(List<Long> sessionList) {
for (long sessionId : sessionList) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
log.log(Level.FINE, () -> session.logPre() + "Confirming upload for session " + sessionId);
session.confirmUpload();
}
}
/**
* Creates a new deployment session from an application package.
*
* @param applicationDirectory a File pointing to an application.
* @param applicationId application id for this new session.
* @param timeoutBudget Timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSession(File applicationDirectory, ApplicationId applicationId,
TimeoutBudget timeoutBudget, Optional<Long> activeSessionId) {
return create(applicationDirectory, applicationId, activeSessionId, false, timeoutBudget);
}
public RemoteSession createRemoteSession(long sessionId) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new RemoteSession(tenantName, sessionId, componentRegistry, sessionZKClient);
}
private void ensureSessionPathDoesNotExist(long sessionId) {
Path sessionPath = getSessionPath(sessionId);
if (componentRegistry.getConfigCurator().exists(sessionPath.getAbsolute())) {
throw new IllegalArgumentException("Path " + sessionPath.getAbsolute() + " already exists in ZooKeeper");
}
}
private ApplicationPackage createApplication(File userDir,
File configApplicationDir,
ApplicationId applicationId,
long sessionId,
Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) {
long deployTimestamp = System.currentTimeMillis();
String user = System.getenv("USER");
if (user == null) {
user = "unknown";
}
DeployData deployData = new DeployData(user, userDir.getAbsolutePath(), applicationId, deployTimestamp,
internalRedeploy, sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSession));
return FilesApplicationPackage.fromFileWithDeployData(configApplicationDir, deployData);
}
private LocalSession createSessionFromApplication(ApplicationPackage applicationPackage,
long sessionId,
TimeoutBudget timeoutBudget,
Clock clock) {
log.log(Level.FINE, TenantRepository.logPre(tenantName) + "Creating session " + sessionId + " in ZooKeeper");
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
sessionZKClient.createNewSession(clock.instant());
Curator.CompletionWaiter waiter = sessionZKClient.getUploadWaiter();
LocalSession session = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
waiter.awaitCompletion(timeoutBudget.timeLeft());
return session;
}
/**
* Creates a new deployment session from an already existing session.
*
* @param existingSession the session to use as base
* @param logger a deploy logger where the deploy log will be written.
* @param internalRedeploy whether this session is for a system internal redeploy — not an application package change
* @param timeoutBudget timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSessionFromExisting(Session existingSession,
DeployLogger logger,
boolean internalRedeploy,
TimeoutBudget timeoutBudget) {
File existingApp = getSessionAppDir(existingSession.getSessionId());
ApplicationId existingApplicationId = existingSession.getApplicationId();
Optional<Long> activeSessionId = getActiveSessionId(existingApplicationId);
logger.log(Level.FINE, "Create new session for application id '" + existingApplicationId + "' from existing active session " + activeSessionId);
LocalSession session = create(existingApp, existingApplicationId, activeSessionId, internalRedeploy, timeoutBudget);
session.setApplicationId(existingApplicationId);
if (distributeApplicationPackage.value() && existingSession.getApplicationPackageReference() != null) {
session.setApplicationPackageReference(existingSession.getApplicationPackageReference());
}
session.setVespaVersion(existingSession.getVespaVersion());
session.setDockerImageRepository(existingSession.getDockerImageRepository());
session.setAthenzDomain(existingSession.getAthenzDomain());
return session;
}
private LocalSession create(File applicationFile, ApplicationId applicationId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy, TimeoutBudget timeoutBudget) {
long sessionId = getNextSessionId();
try {
ensureSessionPathDoesNotExist(sessionId);
ApplicationPackage app = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, internalRedeploy);
return createSessionFromApplication(app, sessionId, timeoutBudget, clock);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
/**
* This method is used when creating a session based on a remote session and the distributed application package
* It does not wait for session being created on other servers
*/
private LocalSession createLocalSession(File applicationFile, ApplicationId applicationId, long sessionId) {
try {
Optional<Long> currentlyActiveSessionId = getActiveSessionId(applicationId);
ApplicationPackage applicationPackage = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, false);
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZooKeeperClient, applicationRepo);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
private ApplicationPackage createApplicationPackage(File applicationFile, ApplicationId applicationId,
long sessionId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) throws IOException {
File userApplicationDir = getSessionAppDir(sessionId);
copyApp(applicationFile, userApplicationDir);
ApplicationPackage applicationPackage = createApplication(applicationFile,
userApplicationDir,
applicationId,
sessionId,
currentlyActiveSessionId,
internalRedeploy);
applicationPackage.writeMetaData();
return applicationPackage;
}
/**
* Returns a new session instance for the given session id.
*/
LocalSession createSessionFromId(long sessionId) {
File sessionDir = getAndValidateExistingSessionAppDir(sessionId);
ApplicationPackage applicationPackage = FilesApplicationPackage.fromFile(sessionDir);
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
}
/**
* Returns a new session instance for the given session id.
*/
public Optional<LocalSession> createLocalSessionUsingDistributedApplicationPackage(long sessionId) {
if (applicationRepo.hasLocalSession(sessionId)) {
log.log(Level.FINE, "Local session for session id " + sessionId + " already exists");
return Optional.of(createSessionFromId(sessionId));
}
log.log(Level.INFO, "Creating local session for session id " + sessionId);
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
FileReference fileReference = sessionZKClient.readApplicationPackageReference();
log.log(Level.FINE, "File reference for session id " + sessionId + ": " + fileReference);
if (fileReference != null) {
File rootDir = new File(Defaults.getDefaults().underVespaHome(componentRegistry.getConfigserverConfig().fileReferencesDir()));
File sessionDir;
FileDirectory fileDirectory = new FileDirectory(rootDir);
try {
sessionDir = fileDirectory.getFile(fileReference);
} catch (IllegalArgumentException e) {
log.log(Level.INFO, "File reference for session id " + sessionId + ": " + fileReference + " not found in " + fileDirectory);
return Optional.empty();
}
ApplicationId applicationId = sessionZKClient.readApplicationId();
LocalSession localSession = createLocalSession(sessionDir, applicationId, sessionId);
addSession(localSession);
return Optional.of(localSession);
}
return Optional.empty();
}
private Optional<Long> getActiveSessionId(ApplicationId applicationId) {
List<ApplicationId> applicationIds = applicationRepo.activeApplications();
return applicationIds.contains(applicationId)
? Optional.of(applicationRepo.requireActiveSessionOf(applicationId))
: Optional.empty();
}
private long getNextSessionId() {
return new SessionCounter(componentRegistry.getConfigCurator(), tenantName).nextSessionId();
}
public Path getSessionPath(long sessionId) {
return sessionsPath.append(String.valueOf(sessionId));
}
Path getSessionStatePath(long sessionId) {
return getSessionPath(sessionId).append(ConfigCurator.SESSIONSTATE_ZK_SUBPATH);
}
private SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) {
String serverId = componentRegistry.getConfigserverConfig().serverId();
Optional<NodeFlavors> nodeFlavors = componentRegistry.getZone().nodeFlavors();
Path sessionPath = getSessionPath(sessionId);
return new SessionZooKeeperClient(curator, componentRegistry.getConfigCurator(), sessionPath, serverId, nodeFlavors);
}
private File getAndValidateExistingSessionAppDir(long sessionId) {
File appDir = getSessionAppDir(sessionId);
if (!appDir.exists() || !appDir.isDirectory()) {
throw new IllegalArgumentException("Unable to find correct application directory for session " + sessionId);
}
return appDir;
}
private File getSessionAppDir(long sessionId) {
return new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName).getUserApplicationDir(sessionId);
}
private void addWatcher(long sessionId, Curator.FileCache fileCache, RemoteSession remoteSession, Optional<LocalSession> localSession) {
if (sessionStateWatchers.containsKey(sessionId)) {
localSession.ifPresent(session -> sessionStateWatchers.get(sessionId).addLocalSession(session));
} else {
sessionStateWatchers.put(sessionId, new SessionStateWatcher(fileCache, reloadHandler, remoteSession,
localSession, metrics, zkWatcherExecutor, this));
}
}
@Override
public String toString() {
return getLocalSessions().toString();
}
public ReloadHandler getReloadHandler() { return reloadHandler; }
private static class FileTransaction extends AbstractTransaction {
public static FileTransaction from(FileOperation operation) {
FileTransaction transaction = new FileTransaction();
transaction.add(operation);
return transaction;
}
@Override
public void prepare() { }
@Override
public void commit() {
for (Operation operation : operations())
((FileOperation)operation).commit();
}
}
/** Factory for file operations */
private static class FileOperations {
/** Creates an operation which recursively deletes the given path */
public static DeleteOperation delete(String pathToDelete) {
return new DeleteOperation(pathToDelete);
}
}
private interface FileOperation extends Transaction.Operation {
void commit();
}
/**
* Recursively deletes this path and everything below.
* Succeeds with no action if the path does not exist.
*/
private static class DeleteOperation implements FileOperation {
private final String pathToDelete;
DeleteOperation(String pathToDelete) {
this.pathToDelete = pathToDelete;
}
@Override
public void commit() {
IOUtils.recursiveDeleteDir(new File(pathToDelete));
}
}
} | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSession = 0;
private final SessionCache<LocalSession> localSessionCache = new SessionCache<>();
private final SessionCache<RemoteSession> remoteSessionCache = new SessionCache<>();
private final Map<Long, SessionStateWatcher> sessionStateWatchers = new HashMap<>();
private final Duration sessionLifetime;
private final Clock clock;
private final Curator curator;
private final Executor zkWatcherExecutor;
private final TenantFileSystemDirs tenantFileSystemDirs;
private final BooleanFlag distributeApplicationPackage;
private final ReloadHandler reloadHandler;
private final MetricUpdater metrics;
private final Curator.DirectoryCache directoryCache;
private final TenantApplications applicationRepo;
private final SessionPreparer sessionPreparer;
private final Path sessionsPath;
private final TenantName tenantName;
private final GlobalComponentRegistry componentRegistry;
public SessionRepository(TenantName tenantName,
GlobalComponentRegistry componentRegistry,
TenantApplications applicationRepo,
ReloadHandler reloadHandler,
FlagSource flagSource,
SessionPreparer sessionPreparer) {
this.tenantName = tenantName;
this.componentRegistry = componentRegistry;
this.sessionsPath = TenantRepository.getSessionsPath(tenantName);
this.clock = componentRegistry.getClock();
this.curator = componentRegistry.getCurator();
this.sessionLifetime = Duration.ofSeconds(componentRegistry.getConfigserverConfig().sessionLifetime());
this.zkWatcherExecutor = command -> componentRegistry.getZkWatcherExecutor().execute(tenantName, command);
this.tenantFileSystemDirs = new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName);
this.applicationRepo = applicationRepo;
this.sessionPreparer = sessionPreparer;
this.distributeApplicationPackage = Flags.CONFIGSERVER_DISTRIBUTE_APPLICATION_PACKAGE.bindTo(flagSource);
this.reloadHandler = reloadHandler;
this.metrics = componentRegistry.getMetrics().getOrCreateMetricUpdater(Metrics.createDimensions(tenantName));
loadLocalSessions();
initializeRemoteSessions();
this.directoryCache = curator.createDirectoryCache(sessionsPath.getAbsolute(), false, false, componentRegistry.getZkCacheExecutor());
this.directoryCache.addListener(this::childEvent);
this.directoryCache.start();
}
public synchronized void addSession(LocalSession session) {
localSessionCache.addSession(session);
long sessionId = session.getSessionId();
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
RemoteSession remoteSession = new RemoteSession(tenantName, sessionId, componentRegistry, createSessionZooKeeperClient(sessionId));
addWatcher(sessionId, fileCache, remoteSession, Optional.of(session));
}
public LocalSession getLocalSession(long sessionId) {
return localSessionCache.getSession(sessionId);
}
public List<LocalSession> getLocalSessions() {
return localSessionCache.getSessions();
}
private void loadLocalSessions() {
File[] sessions = tenantFileSystemDirs.sessionsPath().listFiles(sessionApplicationsFilter);
if (sessions == null) {
return;
}
for (File session : sessions) {
try {
addSession(createSessionFromId(Long.parseLong(session.getName())));
} catch (IllegalArgumentException e) {
log.log(Level.WARNING, "Could not load session '" +
session.getAbsolutePath() + "':" + e.getMessage() + ", skipping it.");
}
}
}
public ConfigChangeActions prepareLocalSession(LocalSession session,
DeployLogger logger,
PrepareParams params,
Optional<ApplicationSet> currentActiveApplicationSet,
Path tenantPath,
Instant now) {
applicationRepo.createApplication(params.getApplicationId());
logger.log(Level.FINE, "Created application " + params.getApplicationId());
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
Curator.CompletionWaiter waiter = sessionZooKeeperClient.createPrepareWaiter();
ConfigChangeActions actions = sessionPreparer.prepare(applicationRepo.getHostValidator(), logger, params,
currentActiveApplicationSet, tenantPath, now,
getSessionAppDir(sessionId),
session.getApplicationPackage(), sessionZooKeeperClient);
session.setPrepared();
waiter.awaitCompletion(params.getTimeoutBudget().timeLeft());
return actions;
}
public void deleteExpiredSessions(Map<ApplicationId, Long> activeSessions) {
log.log(Level.FINE, "Purging old sessions");
try {
for (LocalSession candidate : localSessionCache.getSessions()) {
Instant createTime = candidate.getCreateTime();
log.log(Level.FINE, "Candidate session for deletion: " + candidate.getSessionId() + ", created: " + createTime);
if (hasExpired(candidate) && !isActiveSession(candidate)) {
deleteLocalSession(candidate);
} else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) {
ApplicationId applicationId = candidate.getApplicationId();
Long activeSession = activeSessions.get(applicationId);
if (activeSession == null || activeSession != candidate.getSessionId()) {
deleteLocalSession(candidate);
log.log(Level.INFO, "Deleted inactive session " + candidate.getSessionId() + " created " +
createTime + " for '" + applicationId + "'");
}
}
}
} catch (Throwable e) {
log.log(Level.WARNING, "Error when purging old sessions ", e);
}
log.log(Level.FINE, "Done purging old sessions");
}
private boolean hasExpired(LocalSession candidate) {
return (candidate.getCreateTime().plus(sessionLifetime).isBefore(clock.instant()));
}
private boolean isActiveSession(LocalSession candidate) {
return candidate.getStatus() == Session.Status.ACTIVATE;
}
public void deleteLocalSession(LocalSession session) {
long sessionId = session.getSessionId();
log.log(Level.FINE, "Deleting local session " + sessionId);
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
localSessionCache.removeSession(sessionId);
NestedTransaction transaction = new NestedTransaction();
deleteLocalSession(session, transaction);
transaction.commit();
}
/** Add transactions to delete this session to the given nested transaction */
public void deleteLocalSession(LocalSession session, NestedTransaction transaction) {
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
transaction.add(sessionZooKeeperClient.deleteTransaction(), FileTransaction.class);
transaction.add(FileTransaction.from(FileOperations.delete(getSessionAppDir(sessionId).getAbsolutePath())));
}
public void close() {
deleteAllSessions();
tenantFileSystemDirs.delete();
try {
if (directoryCache != null) {
directoryCache.close();
}
} catch (Exception e) {
log.log(Level.WARNING, "Exception when closing path cache", e);
} finally {
checkForRemovedSessions(new ArrayList<>());
}
}
private void deleteAllSessions() {
List<LocalSession> sessions = new ArrayList<>(localSessionCache.getSessions());
for (LocalSession session : sessions) {
deleteLocalSession(session);
}
}
public RemoteSession getRemoteSession(long sessionId) {
return remoteSessionCache.getSession(sessionId);
}
public List<Long> getRemoteSessions() {
return getSessionList(curator.getChildren(sessionsPath));
}
public void addRemoteSession(RemoteSession session) {
remoteSessionCache.addSession(session);
metrics.incAddedSessions();
}
public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) {
int deleted = 0;
for (long sessionId : getRemoteSessions()) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
if (session.getStatus() == Session.Status.ACTIVATE) continue;
if (sessionHasExpired(session.getCreateTime(), expiryTime, clock)) {
log.log(Level.INFO, "Remote session " + sessionId + " for " + tenantName + " has expired, deleting it");
session.delete();
deleted++;
}
}
return deleted;
}
private boolean sessionHasExpired(Instant created, Duration expiryTime, Clock clock) {
return (created.plus(expiryTime).isBefore(clock.instant()));
}
private List<Long> getSessionListFromDirectoryCache(List<ChildData> children) {
return getSessionList(children.stream()
.map(child -> Path.fromString(child.getPath()).getName())
.collect(Collectors.toList()));
}
private List<Long> getSessionList(List<String> children) {
return children.stream().map(Long::parseLong).collect(Collectors.toList());
}
private void initializeRemoteSessions() throws NumberFormatException {
getRemoteSessions().forEach(this::sessionAdded);
}
private synchronized void sessionsChanged() throws NumberFormatException {
List<Long> sessions = getSessionListFromDirectoryCache(directoryCache.getCurrentData());
checkForRemovedSessions(sessions);
checkForAddedSessions(sessions);
}
private void checkForRemovedSessions(List<Long> sessions) {
for (RemoteSession session : remoteSessionCache.getSessions())
if ( ! sessions.contains(session.getSessionId()))
sessionRemoved(session.getSessionId());
}
private void checkForAddedSessions(List<Long> sessions) {
for (Long sessionId : sessions)
if (remoteSessionCache.getSession(sessionId) == null)
sessionAdded(sessionId);
}
/**
* A session for which we don't have a watcher, i.e. hitherto unknown to us.
*
* @param sessionId session id for the new session
*/
public void sessionAdded(long sessionId) {
log.log(Level.FINE, () -> "Adding remote session to SessionRepository: " + sessionId);
RemoteSession remoteSession = createRemoteSession(sessionId);
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
fileCache.addListener(this::nodeChanged);
loadSessionIfActive(remoteSession);
addRemoteSession(remoteSession);
Optional<LocalSession> localSession = Optional.empty();
if (distributeApplicationPackage.value()) {
localSession = createLocalSessionUsingDistributedApplicationPackage(sessionId);
localSession.ifPresent(this::addSession);
}
addWatcher(sessionId, fileCache, remoteSession, localSession);
}
private void sessionRemoved(long sessionId) {
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
remoteSessionCache.removeSession(sessionId);
metrics.incRemovedSessions();
}
private void loadSessionIfActive(RemoteSession session) {
for (ApplicationId applicationId : applicationRepo.activeApplications()) {
if (applicationRepo.requireActiveSessionOf(applicationId) == session.getSessionId()) {
log.log(Level.FINE, () -> "Found active application for session " + session.getSessionId() + " , loading it");
reloadHandler.reloadConfig(session.ensureApplicationLoaded());
log.log(Level.INFO, session.logPre() + "Application activated successfully: " + applicationId + " (generation " + session.getSessionId() + ")");
return;
}
}
}
private void nodeChanged() {
zkWatcherExecutor.execute(() -> {
Multiset<Session.Status> sessionMetrics = HashMultiset.create();
for (RemoteSession session : remoteSessionCache.getSessions()) {
sessionMetrics.add(session.getStatus());
}
metrics.setNewSessions(sessionMetrics.count(Session.Status.NEW));
metrics.setPreparedSessions(sessionMetrics.count(Session.Status.PREPARE));
metrics.setActivatedSessions(sessionMetrics.count(Session.Status.ACTIVATE));
metrics.setDeactivatedSessions(sessionMetrics.count(Session.Status.DEACTIVATE));
});
}
@SuppressWarnings("unused")
private void childEvent(CuratorFramework ignored, PathChildrenCacheEvent event) {
zkWatcherExecutor.execute(() -> {
log.log(Level.FINE, () -> "Got child event: " + event);
switch (event.getType()) {
case CHILD_ADDED:
sessionsChanged();
synchronizeOnNew(getSessionListFromDirectoryCache(Collections.singletonList(event.getData())));
break;
case CHILD_REMOVED:
case CONNECTION_RECONNECTED:
sessionsChanged();
break;
}
});
}
private void synchronizeOnNew(List<Long> sessionList) {
for (long sessionId : sessionList) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
log.log(Level.FINE, () -> session.logPre() + "Confirming upload for session " + sessionId);
session.confirmUpload();
}
}
/**
* Creates a new deployment session from an application package.
*
* @param applicationDirectory a File pointing to an application.
* @param applicationId application id for this new session.
* @param timeoutBudget Timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSession(File applicationDirectory, ApplicationId applicationId,
TimeoutBudget timeoutBudget, Optional<Long> activeSessionId) {
return create(applicationDirectory, applicationId, activeSessionId, false, timeoutBudget);
}
public RemoteSession createRemoteSession(long sessionId) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new RemoteSession(tenantName, sessionId, componentRegistry, sessionZKClient);
}
private void ensureSessionPathDoesNotExist(long sessionId) {
Path sessionPath = getSessionPath(sessionId);
if (componentRegistry.getConfigCurator().exists(sessionPath.getAbsolute())) {
throw new IllegalArgumentException("Path " + sessionPath.getAbsolute() + " already exists in ZooKeeper");
}
}
private ApplicationPackage createApplication(File userDir,
File configApplicationDir,
ApplicationId applicationId,
long sessionId,
Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) {
long deployTimestamp = System.currentTimeMillis();
String user = System.getenv("USER");
if (user == null) {
user = "unknown";
}
DeployData deployData = new DeployData(user, userDir.getAbsolutePath(), applicationId, deployTimestamp,
internalRedeploy, sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSession));
return FilesApplicationPackage.fromFileWithDeployData(configApplicationDir, deployData);
}
private LocalSession createSessionFromApplication(ApplicationPackage applicationPackage,
long sessionId,
TimeoutBudget timeoutBudget,
Clock clock) {
log.log(Level.FINE, TenantRepository.logPre(tenantName) + "Creating session " + sessionId + " in ZooKeeper");
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
sessionZKClient.createNewSession(clock.instant());
Curator.CompletionWaiter waiter = sessionZKClient.getUploadWaiter();
LocalSession session = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
waiter.awaitCompletion(timeoutBudget.timeLeft());
return session;
}
/**
* Creates a new deployment session from an already existing session.
*
* @param existingSession the session to use as base
* @param logger a deploy logger where the deploy log will be written.
* @param internalRedeploy whether this session is for a system internal redeploy — not an application package change
* @param timeoutBudget timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSessionFromExisting(Session existingSession,
DeployLogger logger,
boolean internalRedeploy,
TimeoutBudget timeoutBudget) {
File existingApp = getSessionAppDir(existingSession.getSessionId());
ApplicationId existingApplicationId = existingSession.getApplicationId();
Optional<Long> activeSessionId = getActiveSessionId(existingApplicationId);
logger.log(Level.FINE, "Create new session for application id '" + existingApplicationId + "' from existing active session " + activeSessionId);
LocalSession session = create(existingApp, existingApplicationId, activeSessionId, internalRedeploy, timeoutBudget);
session.setApplicationId(existingApplicationId);
if (distributeApplicationPackage.value() && existingSession.getApplicationPackageReference() != null) {
session.setApplicationPackageReference(existingSession.getApplicationPackageReference());
}
session.setVespaVersion(existingSession.getVespaVersion());
session.setDockerImageRepository(existingSession.getDockerImageRepository());
session.setAthenzDomain(existingSession.getAthenzDomain());
return session;
}
private LocalSession create(File applicationFile, ApplicationId applicationId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy, TimeoutBudget timeoutBudget) {
long sessionId = getNextSessionId();
try {
ensureSessionPathDoesNotExist(sessionId);
ApplicationPackage app = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, internalRedeploy);
return createSessionFromApplication(app, sessionId, timeoutBudget, clock);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
/**
* This method is used when creating a session based on a remote session and the distributed application package
* It does not wait for session being created on other servers
*/
private LocalSession createLocalSession(File applicationFile, ApplicationId applicationId, long sessionId) {
try {
Optional<Long> currentlyActiveSessionId = getActiveSessionId(applicationId);
ApplicationPackage applicationPackage = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, false);
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZooKeeperClient, applicationRepo);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
private ApplicationPackage createApplicationPackage(File applicationFile, ApplicationId applicationId,
long sessionId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) throws IOException {
File userApplicationDir = getSessionAppDir(sessionId);
copyApp(applicationFile, userApplicationDir);
ApplicationPackage applicationPackage = createApplication(applicationFile,
userApplicationDir,
applicationId,
sessionId,
currentlyActiveSessionId,
internalRedeploy);
applicationPackage.writeMetaData();
return applicationPackage;
}
/**
* Returns a new session instance for the given session id.
*/
LocalSession createSessionFromId(long sessionId) {
File sessionDir = getAndValidateExistingSessionAppDir(sessionId);
ApplicationPackage applicationPackage = FilesApplicationPackage.fromFile(sessionDir);
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
}
/**
* Returns a new session instance for the given session id.
*/
public Optional<LocalSession> createLocalSessionUsingDistributedApplicationPackage(long sessionId) {
if (applicationRepo.hasLocalSession(sessionId)) {
log.log(Level.FINE, "Local session for session id " + sessionId + " already exists");
return Optional.of(createSessionFromId(sessionId));
}
log.log(Level.INFO, "Creating local session for session id " + sessionId);
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
FileReference fileReference = sessionZKClient.readApplicationPackageReference();
log.log(Level.FINE, "File reference for session id " + sessionId + ": " + fileReference);
if (fileReference != null) {
File rootDir = new File(Defaults.getDefaults().underVespaHome(componentRegistry.getConfigserverConfig().fileReferencesDir()));
File sessionDir;
FileDirectory fileDirectory = new FileDirectory(rootDir);
try {
sessionDir = fileDirectory.getFile(fileReference);
} catch (IllegalArgumentException e) {
log.log(Level.INFO, "File reference for session id " + sessionId + ": " + fileReference + " not found in " + fileDirectory);
return Optional.empty();
}
ApplicationId applicationId = sessionZKClient.readApplicationId();
LocalSession localSession = createLocalSession(sessionDir, applicationId, sessionId);
addSession(localSession);
return Optional.of(localSession);
}
return Optional.empty();
}
private Optional<Long> getActiveSessionId(ApplicationId applicationId) {
List<ApplicationId> applicationIds = applicationRepo.activeApplications();
return applicationIds.contains(applicationId)
? Optional.of(applicationRepo.requireActiveSessionOf(applicationId))
: Optional.empty();
}
private long getNextSessionId() {
return new SessionCounter(componentRegistry.getConfigCurator(), tenantName).nextSessionId();
}
public Path getSessionPath(long sessionId) {
return sessionsPath.append(String.valueOf(sessionId));
}
Path getSessionStatePath(long sessionId) {
return getSessionPath(sessionId).append(ConfigCurator.SESSIONSTATE_ZK_SUBPATH);
}
private SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) {
String serverId = componentRegistry.getConfigserverConfig().serverId();
Optional<NodeFlavors> nodeFlavors = componentRegistry.getZone().nodeFlavors();
Path sessionPath = getSessionPath(sessionId);
return new SessionZooKeeperClient(curator, componentRegistry.getConfigCurator(), sessionPath, serverId, nodeFlavors);
}
private File getAndValidateExistingSessionAppDir(long sessionId) {
File appDir = getSessionAppDir(sessionId);
if (!appDir.exists() || !appDir.isDirectory()) {
throw new IllegalArgumentException("Unable to find correct application directory for session " + sessionId);
}
return appDir;
}
private File getSessionAppDir(long sessionId) {
return new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName).getUserApplicationDir(sessionId);
}
private void addWatcher(long sessionId, Curator.FileCache fileCache, RemoteSession remoteSession, Optional<LocalSession> localSession) {
if (sessionStateWatchers.containsKey(sessionId)) {
localSession.ifPresent(session -> sessionStateWatchers.get(sessionId).addLocalSession(session));
} else {
sessionStateWatchers.put(sessionId, new SessionStateWatcher(fileCache, reloadHandler, remoteSession,
localSession, metrics, zkWatcherExecutor, this));
}
}
@Override
public String toString() {
return getLocalSessions().toString();
}
public ReloadHandler getReloadHandler() { return reloadHandler; }
private static class FileTransaction extends AbstractTransaction {
public static FileTransaction from(FileOperation operation) {
FileTransaction transaction = new FileTransaction();
transaction.add(operation);
return transaction;
}
@Override
public void prepare() { }
@Override
public void commit() {
for (Operation operation : operations())
((FileOperation)operation).commit();
}
}
/** Factory for file operations */
private static class FileOperations {
/** Creates an operation which recursively deletes the given path */
public static DeleteOperation delete(String pathToDelete) {
return new DeleteOperation(pathToDelete);
}
}
private interface FileOperation extends Transaction.Operation {
void commit();
}
/**
* Recursively deletes this path and everything below.
* Succeeds with no action if the path does not exist.
*/
private static class DeleteOperation implements FileOperation {
private final String pathToDelete;
DeleteOperation(String pathToDelete) {
this.pathToDelete = pathToDelete;
}
@Override
public void commit() {
IOUtils.recursiveDeleteDir(new File(pathToDelete));
}
}
} | |
Consider pulling this out into a separate test since it's not really port override related (though networking related) | public void testPortOverride() {
StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder();
DistributorCluster cluster =
parse("<cluster id=\"storage\" distributor-base-port=\"14065\">" +
" <documents/>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>");
cluster.getChildren().get("0").getConfig(builder);
StorCommunicationmanagerConfig config = new StorCommunicationmanagerConfig(builder);
assertTrue(config.mbus().dispatch_on_encode());
assertEquals(14066, config.rpcport());
} | assertTrue(config.mbus().dispatch_on_encode()); | public void testPortOverride() {
StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder();
DistributorCluster cluster =
parse("<cluster id=\"storage\" distributor-base-port=\"14065\">" +
" <documents/>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>");
cluster.getChildren().get("0").getConfig(builder);
StorCommunicationmanagerConfig config = new StorCommunicationmanagerConfig(builder);
assertTrue(config.mbus().dispatch_on_encode());
assertEquals(14066, config.rpcport());
} | class DistributorTest {
ContentCluster parseCluster(String xml) {
try {
List<String> searchDefs = ApplicationPackageUtils.generateSchemas("music", "movies", "bunnies");
MockRoot root = ContentClusterUtils.createMockRoot(searchDefs);
return ContentClusterUtils.createCluster(xml, root);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
DistributorCluster parse(String xml) {
return parseCluster(xml).getDistributorNodes();
}
@Test
public void testBasics() {
StorServerConfig.Builder builder = new StorServerConfig.Builder();
parse("<content id=\"foofighters\"><documents/>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>\n").
getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertTrue(config.is_distributor());
assertEquals("foofighters", config.cluster_name());
}
@Test
public void testRevertDefaultOffForSearch() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents/>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertFalse(conf.enable_revert());
}
@Test
public void testSplitAndJoin() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents/>" +
" <tuning>\n" +
" <bucket-splitting max-documents=\"2K\" max-size=\"25M\" minimum-bits=\"8\" />\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(2048, conf.splitcount());
assertEquals(1024, conf.joincount());
assertEquals(26214400, conf.splitsize());
assertEquals(13107200, conf.joinsize());
assertEquals(8, conf.minsplitcount());
assertFalse(conf.inlinebucketsplitting());
}
@Test
public void testThatGroupsAreCountedInWhenComputingSplitBits() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
ContentCluster cluster = parseCluster("<cluster id=\"storage\">\n" +
" <documents/>" +
" <tuning>" +
" <distribution type=\"legacy\"/>" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>");
cluster.getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(1024, conf.splitcount());
assertEquals(512, conf.joincount());
assertEquals(33544432, conf.splitsize());
assertEquals(16000000, conf.joinsize());
assertEquals(8, conf.minsplitcount());
assertTrue(conf.inlinebucketsplitting());
cluster = parseCluster("<cluster id=\"storage\">\n" +
" <redundancy>2</redundancy>" +
" <documents/>" +
" <tuning>" +
" <distribution type=\"legacy\"/>" +
" </tuning>\n" +
" <group>" +
" <distribution partitions=\"1|*\"/>" +
" <group name=\"a\" distribution-key=\"0\">" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
" <group name=\"b\" distribution-key=\"1\">" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>" +
" </group>" +
" </group>" +
"</cluster>");
cluster.getConfig(builder);
conf = new StorDistributormanagerConfig(builder);
assertEquals(1024, conf.splitcount());
assertEquals(512, conf.joincount());
assertEquals(33544432, conf.splitsize());
assertEquals(16000000, conf.joinsize());
assertEquals(1, conf.minsplitcount());
assertTrue(conf.inlinebucketsplitting());
}
@Test
public void testMaxMergesPerNode() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
DistributorCluster dcluster = parse("<content id=\"storage\">\n" +
" <documents/>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>");
((ContentCluster) dcluster.getParent()).getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(16, conf.maximum_nodes_per_merge());
builder = new StorDistributormanagerConfig.Builder();
dcluster = parse("<content id=\"storage\">\n" +
" <documents/>" +
" <tuning>\n" +
" <merges max-nodes-per-merge=\"4\"/>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>");
((ContentCluster) dcluster.getParent()).getConfig(builder);
conf = new StorDistributormanagerConfig(builder);
assertEquals(4, conf.maximum_nodes_per_merge());
}
@Test
public void testGarbageCollectionSetExplicitly() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents garbage-collection=\"true\">\n" +
" <document type=\"music\"/>\n" +
" </documents>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(3600, conf.garbagecollection().interval());
assertEquals("not ((music))", conf.garbagecollection().selectiontoremove());
}
@Test
public void testGarbageCollectionInterval() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents garbage-collection=\"true\" garbage-collection-interval=\"30\">\n" +
" <document type=\"music\"/>\n" +
" </documents>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(30, conf.garbagecollection().interval());
}
@Test
public void testGarbageCollectionOffByDefault() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents>\n" +
" <document type=\"music\"/>\n" +
" </documents>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(0, conf.garbagecollection().interval());
assertEquals("", conf.garbagecollection().selectiontoremove());
}
@Test
public void testComplexGarbageCollectionSelectionForIndexedSearch() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"foo\">\n" +
" <documents garbage-collection=\"true\" selection=\"true\">" +
" <document type=\"music\" selection=\"music.year < now()\"/>\n" +
" <document type=\"movies\" selection=\"movies.year < now() - 1200\"/>\n" +
" </documents>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(3600, conf.garbagecollection().interval());
assertEquals(
"not ((true) and ((music and (music.year < now())) or (movies and (movies.year < now() - 1200))))",
conf.garbagecollection().selectiontoremove());
}
@Test
public void testGarbageCollectionDisabledIfForced() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"foo\">\n" +
" <documents selection=\"true\" garbage-collection=\"false\" garbage-collection-interval=\"30\">\n" +
" <document type=\"music\" selection=\"music.year < now()\"/>\n" +
" <document type=\"movies\" selection=\"movies.year < now() - 1200\"/>\n" +
" </documents>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(0, conf.garbagecollection().interval());
assertEquals("", conf.garbagecollection().selectiontoremove());
}
@Test
private StorDistributormanagerConfig clusterXmlToConfig(String xml) {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse(xml).getConfig(builder);
return new StorDistributormanagerConfig(builder);
}
private String generateXmlForDocTypes(DocType... docTypes) {
return "<content id='storage'>\n" +
DocType.listToXml(docTypes) +
"\n</content>";
}
@Test
public void bucket_activation_disabled_if_no_documents_in_indexed_mode() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.storeOnly("music")));
assertTrue(config.disable_bucket_activation());
}
@Test
public void bucket_activation_enabled_with_single_indexed_document() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.index("music")));
assertFalse(config.disable_bucket_activation());
}
@Test
public void bucket_activation_enabled_with_multiple_indexed_documents() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.index("music"),
DocType.index("movies")));
assertFalse(config.disable_bucket_activation());
}
@Test
public void bucket_activation_enabled_if_at_least_one_document_indexed() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.storeOnly("music"),
DocType.streaming("bunnies"),
DocType.index("movies")));
assertFalse(config.disable_bucket_activation());
}
@Test
public void bucket_activation_disabled_for_single_streaming_type() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.streaming("music")));
assertTrue(config.disable_bucket_activation());
}
} | class DistributorTest {
ContentCluster parseCluster(String xml) {
try {
List<String> searchDefs = ApplicationPackageUtils.generateSchemas("music", "movies", "bunnies");
MockRoot root = ContentClusterUtils.createMockRoot(searchDefs);
return ContentClusterUtils.createCluster(xml, root);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
DistributorCluster parse(String xml) {
return parseCluster(xml).getDistributorNodes();
}
@Test
public void testBasics() {
StorServerConfig.Builder builder = new StorServerConfig.Builder();
parse("<content id=\"foofighters\"><documents/>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>\n").
getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertTrue(config.is_distributor());
assertEquals("foofighters", config.cluster_name());
}
@Test
public void testRevertDefaultOffForSearch() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents/>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertFalse(conf.enable_revert());
}
@Test
public void testSplitAndJoin() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents/>" +
" <tuning>\n" +
" <bucket-splitting max-documents=\"2K\" max-size=\"25M\" minimum-bits=\"8\" />\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(2048, conf.splitcount());
assertEquals(1024, conf.joincount());
assertEquals(26214400, conf.splitsize());
assertEquals(13107200, conf.joinsize());
assertEquals(8, conf.minsplitcount());
assertFalse(conf.inlinebucketsplitting());
}
@Test
public void testThatGroupsAreCountedInWhenComputingSplitBits() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
ContentCluster cluster = parseCluster("<cluster id=\"storage\">\n" +
" <documents/>" +
" <tuning>" +
" <distribution type=\"legacy\"/>" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>");
cluster.getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(1024, conf.splitcount());
assertEquals(512, conf.joincount());
assertEquals(33544432, conf.splitsize());
assertEquals(16000000, conf.joinsize());
assertEquals(8, conf.minsplitcount());
assertTrue(conf.inlinebucketsplitting());
cluster = parseCluster("<cluster id=\"storage\">\n" +
" <redundancy>2</redundancy>" +
" <documents/>" +
" <tuning>" +
" <distribution type=\"legacy\"/>" +
" </tuning>\n" +
" <group>" +
" <distribution partitions=\"1|*\"/>" +
" <group name=\"a\" distribution-key=\"0\">" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
" <group name=\"b\" distribution-key=\"1\">" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>" +
" </group>" +
" </group>" +
"</cluster>");
cluster.getConfig(builder);
conf = new StorDistributormanagerConfig(builder);
assertEquals(1024, conf.splitcount());
assertEquals(512, conf.joincount());
assertEquals(33544432, conf.splitsize());
assertEquals(16000000, conf.joinsize());
assertEquals(1, conf.minsplitcount());
assertTrue(conf.inlinebucketsplitting());
}
@Test
public void testMaxMergesPerNode() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
DistributorCluster dcluster = parse("<content id=\"storage\">\n" +
" <documents/>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>");
((ContentCluster) dcluster.getParent()).getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(16, conf.maximum_nodes_per_merge());
builder = new StorDistributormanagerConfig.Builder();
dcluster = parse("<content id=\"storage\">\n" +
" <documents/>" +
" <tuning>\n" +
" <merges max-nodes-per-merge=\"4\"/>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>");
((ContentCluster) dcluster.getParent()).getConfig(builder);
conf = new StorDistributormanagerConfig(builder);
assertEquals(4, conf.maximum_nodes_per_merge());
}
@Test
public void testGarbageCollectionSetExplicitly() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents garbage-collection=\"true\">\n" +
" <document type=\"music\"/>\n" +
" </documents>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(3600, conf.garbagecollection().interval());
assertEquals("not ((music))", conf.garbagecollection().selectiontoremove());
}
@Test
public void testGarbageCollectionInterval() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents garbage-collection=\"true\" garbage-collection-interval=\"30\">\n" +
" <document type=\"music\"/>\n" +
" </documents>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(30, conf.garbagecollection().interval());
}
@Test
public void testGarbageCollectionOffByDefault() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"storage\">\n" +
" <documents>\n" +
" <document type=\"music\"/>\n" +
" </documents>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(0, conf.garbagecollection().interval());
assertEquals("", conf.garbagecollection().selectiontoremove());
}
@Test
public void testComplexGarbageCollectionSelectionForIndexedSearch() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"foo\">\n" +
" <documents garbage-collection=\"true\" selection=\"true\">" +
" <document type=\"music\" selection=\"music.year < now()\"/>\n" +
" <document type=\"movies\" selection=\"movies.year < now() - 1200\"/>\n" +
" </documents>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(3600, conf.garbagecollection().interval());
assertEquals(
"not ((true) and ((music and (music.year < now())) or (movies and (movies.year < now() - 1200))))",
conf.garbagecollection().selectiontoremove());
}
@Test
public void testGarbageCollectionDisabledIfForced() {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse("<cluster id=\"foo\">\n" +
" <documents selection=\"true\" garbage-collection=\"false\" garbage-collection-interval=\"30\">\n" +
" <document type=\"music\" selection=\"music.year < now()\"/>\n" +
" <document type=\"movies\" selection=\"movies.year < now() - 1200\"/>\n" +
" </documents>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>").getConfig(builder);
StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder);
assertEquals(0, conf.garbagecollection().interval());
assertEquals("", conf.garbagecollection().selectiontoremove());
}
@Test
@Test
public void testCommunicationManagerDefaults() {
StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder();
DistributorCluster cluster =
parse("<cluster id=\"storage\">" +
" <documents/>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>");
cluster.getChildren().get("0").getConfig(builder);
StorCommunicationmanagerConfig config = new StorCommunicationmanagerConfig(builder);
assertTrue(config.mbus().dispatch_on_encode());
assertFalse(config.mbus().dispatch_on_decode());
assertEquals(4, config.mbus().num_threads());
assertEquals(StorCommunicationmanagerConfig.Mbus.Optimize_for.LATENCY, config.mbus().optimize_for());
}
private StorDistributormanagerConfig clusterXmlToConfig(String xml) {
StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder();
parse(xml).getConfig(builder);
return new StorDistributormanagerConfig(builder);
}
private String generateXmlForDocTypes(DocType... docTypes) {
return "<content id='storage'>\n" +
DocType.listToXml(docTypes) +
"\n</content>";
}
@Test
public void bucket_activation_disabled_if_no_documents_in_indexed_mode() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.storeOnly("music")));
assertTrue(config.disable_bucket_activation());
}
@Test
public void bucket_activation_enabled_with_single_indexed_document() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.index("music")));
assertFalse(config.disable_bucket_activation());
}
@Test
public void bucket_activation_enabled_with_multiple_indexed_documents() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.index("music"),
DocType.index("movies")));
assertFalse(config.disable_bucket_activation());
}
@Test
public void bucket_activation_enabled_if_at_least_one_document_indexed() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.storeOnly("music"),
DocType.streaming("bunnies"),
DocType.index("movies")));
assertFalse(config.disable_bucket_activation());
}
@Test
public void bucket_activation_disabled_for_single_streaming_type() {
StorDistributormanagerConfig config = clusterXmlToConfig(
generateXmlForDocTypes(DocType.streaming("music")));
assertTrue(config.disable_bucket_activation());
}
} |
Why not use a for loop on line 118 instead to avoid this hack? | public boolean deleteRecursively(TaskContext context) {
final int limit = 20;
int[] numDeleted = { 0 };
List<Path> deletedPaths = new ArrayList<>();
try {
forEach(attributes -> {
if (attributes.unixPath().deleteRecursively()) {
if (numDeleted[0]++ <= limit) deletedPaths.add(attributes.path());
}
});
} finally {
if (numDeleted[0] > limit) {
context.log(logger, "Deleted " + numDeleted[0] + " paths under " + basePath);
} else if (deletedPaths.size() > 0) {
List<Path> paths = deletedPaths.stream()
.map(basePath::relativize)
.sorted()
.collect(Collectors.toList());
context.log(logger, "Deleted these paths in " + basePath + ": " + paths);
}
}
return deletedPaths.size() > 0;
} | int[] numDeleted = { 0 }; | public boolean deleteRecursively(TaskContext context) {
final int maxNumberOfDeletedPathsToLog = 20;
MutableInteger numDeleted = new MutableInteger(0);
List<Path> deletedPaths = new ArrayList<>();
try {
forEach(attributes -> {
if (attributes.unixPath().deleteRecursively()) {
if (numDeleted.next() <= maxNumberOfDeletedPathsToLog) deletedPaths.add(attributes.path());
}
});
} finally {
if (numDeleted.get() > maxNumberOfDeletedPathsToLog) {
context.log(logger, "Deleted " + numDeleted.get() + " paths under " + basePath);
} else if (deletedPaths.size() > 0) {
List<Path> paths = deletedPaths.stream()
.map(basePath::relativize)
.sorted()
.collect(Collectors.toList());
context.log(logger, "Deleted these paths in " + basePath + ": " + paths);
}
}
return deletedPaths.size() > 0;
} | class FileFinder {
private static final Logger logger = Logger.getLogger(FileFinder.class.getName());
private final Path basePath;
private final Set<Path> pruned = new HashSet<>();
private Predicate<FileAttributes> matcher;
private int maxDepth = Integer.MAX_VALUE;
private FileFinder(Path basePath, Predicate<FileAttributes> initialMatcher) {
this.basePath = basePath;
this.matcher = initialMatcher;
}
/** Creates a FileFinder at the given basePath */
public static FileFinder from(Path basePath) {
return new FileFinder(basePath, attrs -> true);
}
/** Creates a FileFinder at the given basePath that will match all files */
public static FileFinder files(Path basePath) {
return new FileFinder(basePath, FileAttributes::isRegularFile);
}
/** Creates a FileFinder at the given basePath that will match all directories */
public static FileFinder directories(Path basePath) {
return new FileFinder(basePath, FileAttributes::isDirectory);
}
/**
* Predicate that will be used to match files and directories under the base path.
*
* NOTE: Consecutive calls to this method are ANDed (this include the initial filter from
* {@link
*/
public FileFinder match(Predicate<FileAttributes> matcher) {
this.matcher = this.matcher.and(matcher);
return this;
}
/**
* Path for which whole directory tree will be skipped, including the path itself.
* The path must be under {@code basePath} or be relative to {@code basePath}.
*/
public FileFinder prune(Path path) {
if (!path.isAbsolute())
path = basePath.resolve(path);
if (!path.startsWith(basePath))
throw new IllegalArgumentException("Prune path " + path + " is not under base path " + basePath);
this.pruned.add(path);
return this;
}
/** Convenience method for pruning multiple paths, see {@link
public FileFinder prune(Collection<Path> paths) {
paths.forEach(this::prune);
return this;
}
/**
* Maximum depth (relative to basePath) where contents should be matched with the given filters.
* Default is unlimited.
*/
public FileFinder maxDepth(int maxDepth) {
this.maxDepth = maxDepth;
return this;
}
/**
* Recursively deletes all matching elements
*
* @return true iff anything was matched and deleted
*/
public List<FileAttributes> list() {
LinkedList<FileAttributes> list = new LinkedList<>();
forEach(list::add);
return list;
}
public Stream<FileAttributes> stream() {
return list().stream();
}
public void forEachPath(Consumer<Path> action) {
forEach(attributes -> action.accept(attributes.path()));
}
/** Applies a given consumer to all the matching {@link FileFinder.FileAttributes} */
public void forEach(Consumer<FileAttributes> action) {
applyForEachToMatching(basePath, matcher, maxDepth, action);
}
/**
* <p> This method walks a file tree rooted at a given starting file. The file tree traversal is
* <em>depth-first</em>: The filter function is applied in pre-order (NLR), but the given
* {@link Consumer} will be called in post-order (LRN).
*/
private void applyForEachToMatching(Path basePath, Predicate<FileAttributes> matcher,
int maxDepth, Consumer<FileAttributes> action) {
try {
Files.walkFileTree(basePath, Set.of(), maxDepth, new SimpleFileVisitor<>() {
private final Stack<FileAttributes> matchingDirectoryStack = new Stack<>();
private int currentLevel = -1;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (pruned.contains(dir)) return FileVisitResult.SKIP_SUBTREE;
currentLevel++;
FileAttributes attributes = new FileAttributes(dir, attrs);
if (currentLevel > 0 && matcher.test(attributes))
matchingDirectoryStack.push(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (attrs.isDirectory()) {
preVisitDirectory(file, attrs);
return postVisitDirectory(file, null);
}
FileAttributes attributes = new FileAttributes(file, attrs);
if (matcher.test(attributes))
action.accept(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
if (!matchingDirectoryStack.isEmpty())
action.accept(matchingDirectoryStack.pop());
currentLevel--;
return FileVisitResult.CONTINUE;
}
});
} catch (NoSuchFileException ignored) {
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static class FileAttributes {
private final Path path;
private final BasicFileAttributes attributes;
public FileAttributes(Path path, BasicFileAttributes attributes) {
this.path = path;
this.attributes = attributes;
}
public Path path() { return path; }
public UnixPath unixPath() { return new UnixPath(path); }
public String filename() { return path.getFileName().toString(); }
public Instant lastModifiedTime() { return attributes.lastModifiedTime().toInstant(); }
public boolean isRegularFile() { return attributes.isRegularFile(); }
public boolean isDirectory() { return attributes.isDirectory(); }
public long size() { return attributes.size(); }
}
public static Predicate<FileAttributes> olderThan(Duration duration) {
return attrs -> Duration.between(attrs.lastModifiedTime(), Instant.now()).compareTo(duration) > 0;
}
public static Predicate<FileAttributes> youngerThan(Duration duration) {
return olderThan(duration).negate();
}
public static Predicate<FileAttributes> largerThan(long sizeInBytes) {
return attrs -> attrs.size() > sizeInBytes;
}
public static Predicate<FileAttributes> smallerThan(long sizeInBytes) {
return largerThan(sizeInBytes).negate();
}
public static Predicate<FileAttributes> nameMatches(Pattern pattern) {
return attrs -> pattern.matcher(attrs.filename()).matches();
}
public static Predicate<FileAttributes> nameStartsWith(String string) {
return attrs -> attrs.filename().startsWith(string);
}
public static Predicate<FileAttributes> nameEndsWith(String string) {
return attrs -> attrs.filename().endsWith(string);
}
public static Predicate<FileAttributes> all() {
return attrs -> true;
}
} | class FileFinder {
private static final Logger logger = Logger.getLogger(FileFinder.class.getName());
private final Path basePath;
private final Set<Path> pruned = new HashSet<>();
private Predicate<FileAttributes> matcher;
private int maxDepth = Integer.MAX_VALUE;
private FileFinder(Path basePath, Predicate<FileAttributes> initialMatcher) {
this.basePath = basePath;
this.matcher = initialMatcher;
}
/** Creates a FileFinder at the given basePath */
public static FileFinder from(Path basePath) {
return new FileFinder(basePath, attrs -> true);
}
/** Creates a FileFinder at the given basePath that will match all files */
public static FileFinder files(Path basePath) {
return new FileFinder(basePath, FileAttributes::isRegularFile);
}
/** Creates a FileFinder at the given basePath that will match all directories */
public static FileFinder directories(Path basePath) {
return new FileFinder(basePath, FileAttributes::isDirectory);
}
/**
* Predicate that will be used to match files and directories under the base path.
*
* NOTE: Consecutive calls to this method are ANDed (this include the initial filter from
* {@link
*/
public FileFinder match(Predicate<FileAttributes> matcher) {
this.matcher = this.matcher.and(matcher);
return this;
}
/**
* Path for which whole directory tree will be skipped, including the path itself.
* The path must be under {@code basePath} or be relative to {@code basePath}.
*/
public FileFinder prune(Path path) {
if (!path.isAbsolute())
path = basePath.resolve(path);
if (!path.startsWith(basePath))
throw new IllegalArgumentException("Prune path " + path + " is not under base path " + basePath);
this.pruned.add(path);
return this;
}
/** Convenience method for pruning multiple paths, see {@link
public FileFinder prune(Collection<Path> paths) {
paths.forEach(this::prune);
return this;
}
/**
* Maximum depth (relative to basePath) where contents should be matched with the given filters.
* Default is unlimited.
*/
public FileFinder maxDepth(int maxDepth) {
this.maxDepth = maxDepth;
return this;
}
/**
* Recursively deletes all matching elements
*
* @return true iff anything was matched and deleted
*/
public List<FileAttributes> list() {
LinkedList<FileAttributes> list = new LinkedList<>();
forEach(list::add);
return list;
}
public Stream<FileAttributes> stream() {
return list().stream();
}
public void forEachPath(Consumer<Path> action) {
forEach(attributes -> action.accept(attributes.path()));
}
/** Applies a given consumer to all the matching {@link FileFinder.FileAttributes} */
public void forEach(Consumer<FileAttributes> action) {
applyForEachToMatching(basePath, matcher, maxDepth, action);
}
/**
* <p> This method walks a file tree rooted at a given starting file. The file tree traversal is
* <em>depth-first</em>: The filter function is applied in pre-order (NLR), but the given
* {@link Consumer} will be called in post-order (LRN).
*/
private void applyForEachToMatching(Path basePath, Predicate<FileAttributes> matcher,
int maxDepth, Consumer<FileAttributes> action) {
try {
Files.walkFileTree(basePath, Set.of(), maxDepth, new SimpleFileVisitor<>() {
private final Stack<FileAttributes> matchingDirectoryStack = new Stack<>();
private int currentLevel = -1;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (pruned.contains(dir)) return FileVisitResult.SKIP_SUBTREE;
currentLevel++;
FileAttributes attributes = new FileAttributes(dir, attrs);
if (currentLevel > 0 && matcher.test(attributes))
matchingDirectoryStack.push(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (attrs.isDirectory()) {
preVisitDirectory(file, attrs);
return postVisitDirectory(file, null);
}
FileAttributes attributes = new FileAttributes(file, attrs);
if (matcher.test(attributes))
action.accept(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
if (!matchingDirectoryStack.isEmpty())
action.accept(matchingDirectoryStack.pop());
currentLevel--;
return FileVisitResult.CONTINUE;
}
});
} catch (NoSuchFileException ignored) {
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static class FileAttributes {
private final Path path;
private final BasicFileAttributes attributes;
public FileAttributes(Path path, BasicFileAttributes attributes) {
this.path = path;
this.attributes = attributes;
}
public Path path() { return path; }
public UnixPath unixPath() { return new UnixPath(path); }
public String filename() { return path.getFileName().toString(); }
public Instant lastModifiedTime() { return attributes.lastModifiedTime().toInstant(); }
public boolean isRegularFile() { return attributes.isRegularFile(); }
public boolean isDirectory() { return attributes.isDirectory(); }
public long size() { return attributes.size(); }
}
public static Predicate<FileAttributes> olderThan(Duration duration) {
return attrs -> Duration.between(attrs.lastModifiedTime(), Instant.now()).compareTo(duration) > 0;
}
public static Predicate<FileAttributes> youngerThan(Duration duration) {
return olderThan(duration).negate();
}
public static Predicate<FileAttributes> largerThan(long sizeInBytes) {
return attrs -> attrs.size() > sizeInBytes;
}
public static Predicate<FileAttributes> smallerThan(long sizeInBytes) {
return largerThan(sizeInBytes).negate();
}
public static Predicate<FileAttributes> nameMatches(Pattern pattern) {
return attrs -> pattern.matcher(attrs.filename()).matches();
}
public static Predicate<FileAttributes> nameStartsWith(String string) {
return attrs -> attrs.filename().startsWith(string);
}
public static Predicate<FileAttributes> nameEndsWith(String string) {
return attrs -> attrs.filename().endsWith(string);
}
public static Predicate<FileAttributes> all() {
return attrs -> true;
}
} |
Maybe worth a comment saying why there is a limit? | public boolean deleteRecursively(TaskContext context) {
final int limit = 20;
int[] numDeleted = { 0 };
List<Path> deletedPaths = new ArrayList<>();
try {
forEach(attributes -> {
if (attributes.unixPath().deleteRecursively()) {
if (numDeleted[0]++ <= limit) deletedPaths.add(attributes.path());
}
});
} finally {
if (numDeleted[0] > limit) {
context.log(logger, "Deleted " + numDeleted[0] + " paths under " + basePath);
} else if (deletedPaths.size() > 0) {
List<Path> paths = deletedPaths.stream()
.map(basePath::relativize)
.sorted()
.collect(Collectors.toList());
context.log(logger, "Deleted these paths in " + basePath + ": " + paths);
}
}
return deletedPaths.size() > 0;
} | final int limit = 20; | public boolean deleteRecursively(TaskContext context) {
final int maxNumberOfDeletedPathsToLog = 20;
MutableInteger numDeleted = new MutableInteger(0);
List<Path> deletedPaths = new ArrayList<>();
try {
forEach(attributes -> {
if (attributes.unixPath().deleteRecursively()) {
if (numDeleted.next() <= maxNumberOfDeletedPathsToLog) deletedPaths.add(attributes.path());
}
});
} finally {
if (numDeleted.get() > maxNumberOfDeletedPathsToLog) {
context.log(logger, "Deleted " + numDeleted.get() + " paths under " + basePath);
} else if (deletedPaths.size() > 0) {
List<Path> paths = deletedPaths.stream()
.map(basePath::relativize)
.sorted()
.collect(Collectors.toList());
context.log(logger, "Deleted these paths in " + basePath + ": " + paths);
}
}
return deletedPaths.size() > 0;
} | class FileFinder {
private static final Logger logger = Logger.getLogger(FileFinder.class.getName());
private final Path basePath;
private final Set<Path> pruned = new HashSet<>();
private Predicate<FileAttributes> matcher;
private int maxDepth = Integer.MAX_VALUE;
private FileFinder(Path basePath, Predicate<FileAttributes> initialMatcher) {
this.basePath = basePath;
this.matcher = initialMatcher;
}
/** Creates a FileFinder at the given basePath */
public static FileFinder from(Path basePath) {
return new FileFinder(basePath, attrs -> true);
}
/** Creates a FileFinder at the given basePath that will match all files */
public static FileFinder files(Path basePath) {
return new FileFinder(basePath, FileAttributes::isRegularFile);
}
/** Creates a FileFinder at the given basePath that will match all directories */
public static FileFinder directories(Path basePath) {
return new FileFinder(basePath, FileAttributes::isDirectory);
}
/**
* Predicate that will be used to match files and directories under the base path.
*
* NOTE: Consecutive calls to this method are ANDed (this include the initial filter from
* {@link
*/
public FileFinder match(Predicate<FileAttributes> matcher) {
this.matcher = this.matcher.and(matcher);
return this;
}
/**
* Path for which whole directory tree will be skipped, including the path itself.
* The path must be under {@code basePath} or be relative to {@code basePath}.
*/
public FileFinder prune(Path path) {
if (!path.isAbsolute())
path = basePath.resolve(path);
if (!path.startsWith(basePath))
throw new IllegalArgumentException("Prune path " + path + " is not under base path " + basePath);
this.pruned.add(path);
return this;
}
/** Convenience method for pruning multiple paths, see {@link
public FileFinder prune(Collection<Path> paths) {
paths.forEach(this::prune);
return this;
}
/**
* Maximum depth (relative to basePath) where contents should be matched with the given filters.
* Default is unlimited.
*/
public FileFinder maxDepth(int maxDepth) {
this.maxDepth = maxDepth;
return this;
}
/**
* Recursively deletes all matching elements
*
* @return true iff anything was matched and deleted
*/
public List<FileAttributes> list() {
LinkedList<FileAttributes> list = new LinkedList<>();
forEach(list::add);
return list;
}
public Stream<FileAttributes> stream() {
return list().stream();
}
public void forEachPath(Consumer<Path> action) {
forEach(attributes -> action.accept(attributes.path()));
}
/** Applies a given consumer to all the matching {@link FileFinder.FileAttributes} */
public void forEach(Consumer<FileAttributes> action) {
applyForEachToMatching(basePath, matcher, maxDepth, action);
}
/**
* <p> This method walks a file tree rooted at a given starting file. The file tree traversal is
* <em>depth-first</em>: The filter function is applied in pre-order (NLR), but the given
* {@link Consumer} will be called in post-order (LRN).
*/
private void applyForEachToMatching(Path basePath, Predicate<FileAttributes> matcher,
int maxDepth, Consumer<FileAttributes> action) {
try {
Files.walkFileTree(basePath, Set.of(), maxDepth, new SimpleFileVisitor<>() {
private final Stack<FileAttributes> matchingDirectoryStack = new Stack<>();
private int currentLevel = -1;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (pruned.contains(dir)) return FileVisitResult.SKIP_SUBTREE;
currentLevel++;
FileAttributes attributes = new FileAttributes(dir, attrs);
if (currentLevel > 0 && matcher.test(attributes))
matchingDirectoryStack.push(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (attrs.isDirectory()) {
preVisitDirectory(file, attrs);
return postVisitDirectory(file, null);
}
FileAttributes attributes = new FileAttributes(file, attrs);
if (matcher.test(attributes))
action.accept(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
if (!matchingDirectoryStack.isEmpty())
action.accept(matchingDirectoryStack.pop());
currentLevel--;
return FileVisitResult.CONTINUE;
}
});
} catch (NoSuchFileException ignored) {
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static class FileAttributes {
private final Path path;
private final BasicFileAttributes attributes;
public FileAttributes(Path path, BasicFileAttributes attributes) {
this.path = path;
this.attributes = attributes;
}
public Path path() { return path; }
public UnixPath unixPath() { return new UnixPath(path); }
public String filename() { return path.getFileName().toString(); }
public Instant lastModifiedTime() { return attributes.lastModifiedTime().toInstant(); }
public boolean isRegularFile() { return attributes.isRegularFile(); }
public boolean isDirectory() { return attributes.isDirectory(); }
public long size() { return attributes.size(); }
}
public static Predicate<FileAttributes> olderThan(Duration duration) {
return attrs -> Duration.between(attrs.lastModifiedTime(), Instant.now()).compareTo(duration) > 0;
}
public static Predicate<FileAttributes> youngerThan(Duration duration) {
return olderThan(duration).negate();
}
public static Predicate<FileAttributes> largerThan(long sizeInBytes) {
return attrs -> attrs.size() > sizeInBytes;
}
public static Predicate<FileAttributes> smallerThan(long sizeInBytes) {
return largerThan(sizeInBytes).negate();
}
public static Predicate<FileAttributes> nameMatches(Pattern pattern) {
return attrs -> pattern.matcher(attrs.filename()).matches();
}
public static Predicate<FileAttributes> nameStartsWith(String string) {
return attrs -> attrs.filename().startsWith(string);
}
public static Predicate<FileAttributes> nameEndsWith(String string) {
return attrs -> attrs.filename().endsWith(string);
}
public static Predicate<FileAttributes> all() {
return attrs -> true;
}
} | class FileFinder {
private static final Logger logger = Logger.getLogger(FileFinder.class.getName());
private final Path basePath;
private final Set<Path> pruned = new HashSet<>();
private Predicate<FileAttributes> matcher;
private int maxDepth = Integer.MAX_VALUE;
private FileFinder(Path basePath, Predicate<FileAttributes> initialMatcher) {
this.basePath = basePath;
this.matcher = initialMatcher;
}
/** Creates a FileFinder at the given basePath */
public static FileFinder from(Path basePath) {
return new FileFinder(basePath, attrs -> true);
}
/** Creates a FileFinder at the given basePath that will match all files */
public static FileFinder files(Path basePath) {
return new FileFinder(basePath, FileAttributes::isRegularFile);
}
/** Creates a FileFinder at the given basePath that will match all directories */
public static FileFinder directories(Path basePath) {
return new FileFinder(basePath, FileAttributes::isDirectory);
}
/**
* Predicate that will be used to match files and directories under the base path.
*
* NOTE: Consecutive calls to this method are ANDed (this include the initial filter from
* {@link
*/
public FileFinder match(Predicate<FileAttributes> matcher) {
this.matcher = this.matcher.and(matcher);
return this;
}
/**
* Path for which whole directory tree will be skipped, including the path itself.
* The path must be under {@code basePath} or be relative to {@code basePath}.
*/
public FileFinder prune(Path path) {
if (!path.isAbsolute())
path = basePath.resolve(path);
if (!path.startsWith(basePath))
throw new IllegalArgumentException("Prune path " + path + " is not under base path " + basePath);
this.pruned.add(path);
return this;
}
/** Convenience method for pruning multiple paths, see {@link
public FileFinder prune(Collection<Path> paths) {
paths.forEach(this::prune);
return this;
}
/**
* Maximum depth (relative to basePath) where contents should be matched with the given filters.
* Default is unlimited.
*/
public FileFinder maxDepth(int maxDepth) {
this.maxDepth = maxDepth;
return this;
}
/**
* Recursively deletes all matching elements
*
* @return true iff anything was matched and deleted
*/
public List<FileAttributes> list() {
LinkedList<FileAttributes> list = new LinkedList<>();
forEach(list::add);
return list;
}
public Stream<FileAttributes> stream() {
return list().stream();
}
public void forEachPath(Consumer<Path> action) {
forEach(attributes -> action.accept(attributes.path()));
}
/** Applies a given consumer to all the matching {@link FileFinder.FileAttributes} */
public void forEach(Consumer<FileAttributes> action) {
applyForEachToMatching(basePath, matcher, maxDepth, action);
}
/**
* <p> This method walks a file tree rooted at a given starting file. The file tree traversal is
* <em>depth-first</em>: The filter function is applied in pre-order (NLR), but the given
* {@link Consumer} will be called in post-order (LRN).
*/
private void applyForEachToMatching(Path basePath, Predicate<FileAttributes> matcher,
int maxDepth, Consumer<FileAttributes> action) {
try {
Files.walkFileTree(basePath, Set.of(), maxDepth, new SimpleFileVisitor<>() {
private final Stack<FileAttributes> matchingDirectoryStack = new Stack<>();
private int currentLevel = -1;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (pruned.contains(dir)) return FileVisitResult.SKIP_SUBTREE;
currentLevel++;
FileAttributes attributes = new FileAttributes(dir, attrs);
if (currentLevel > 0 && matcher.test(attributes))
matchingDirectoryStack.push(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (attrs.isDirectory()) {
preVisitDirectory(file, attrs);
return postVisitDirectory(file, null);
}
FileAttributes attributes = new FileAttributes(file, attrs);
if (matcher.test(attributes))
action.accept(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
if (!matchingDirectoryStack.isEmpty())
action.accept(matchingDirectoryStack.pop());
currentLevel--;
return FileVisitResult.CONTINUE;
}
});
} catch (NoSuchFileException ignored) {
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static class FileAttributes {
private final Path path;
private final BasicFileAttributes attributes;
public FileAttributes(Path path, BasicFileAttributes attributes) {
this.path = path;
this.attributes = attributes;
}
public Path path() { return path; }
public UnixPath unixPath() { return new UnixPath(path); }
public String filename() { return path.getFileName().toString(); }
public Instant lastModifiedTime() { return attributes.lastModifiedTime().toInstant(); }
public boolean isRegularFile() { return attributes.isRegularFile(); }
public boolean isDirectory() { return attributes.isDirectory(); }
public long size() { return attributes.size(); }
}
public static Predicate<FileAttributes> olderThan(Duration duration) {
return attrs -> Duration.between(attrs.lastModifiedTime(), Instant.now()).compareTo(duration) > 0;
}
public static Predicate<FileAttributes> youngerThan(Duration duration) {
return olderThan(duration).negate();
}
public static Predicate<FileAttributes> largerThan(long sizeInBytes) {
return attrs -> attrs.size() > sizeInBytes;
}
public static Predicate<FileAttributes> smallerThan(long sizeInBytes) {
return largerThan(sizeInBytes).negate();
}
public static Predicate<FileAttributes> nameMatches(Pattern pattern) {
return attrs -> pattern.matcher(attrs.filename()).matches();
}
public static Predicate<FileAttributes> nameStartsWith(String string) {
return attrs -> attrs.filename().startsWith(string);
}
public static Predicate<FileAttributes> nameEndsWith(String string) {
return attrs -> attrs.filename().endsWith(string);
}
public static Predicate<FileAttributes> all() {
return attrs -> true;
}
} |
At its core, this class only has a way a method to run a lambda on a matching file via `java.nio.file.Files::walkFileTree`, I don't see any simple way to create an `Iterable` out of that? | public boolean deleteRecursively(TaskContext context) {
final int limit = 20;
int[] numDeleted = { 0 };
List<Path> deletedPaths = new ArrayList<>();
try {
forEach(attributes -> {
if (attributes.unixPath().deleteRecursively()) {
if (numDeleted[0]++ <= limit) deletedPaths.add(attributes.path());
}
});
} finally {
if (numDeleted[0] > limit) {
context.log(logger, "Deleted " + numDeleted[0] + " paths under " + basePath);
} else if (deletedPaths.size() > 0) {
List<Path> paths = deletedPaths.stream()
.map(basePath::relativize)
.sorted()
.collect(Collectors.toList());
context.log(logger, "Deleted these paths in " + basePath + ": " + paths);
}
}
return deletedPaths.size() > 0;
} | int[] numDeleted = { 0 }; | public boolean deleteRecursively(TaskContext context) {
final int maxNumberOfDeletedPathsToLog = 20;
MutableInteger numDeleted = new MutableInteger(0);
List<Path> deletedPaths = new ArrayList<>();
try {
forEach(attributes -> {
if (attributes.unixPath().deleteRecursively()) {
if (numDeleted.next() <= maxNumberOfDeletedPathsToLog) deletedPaths.add(attributes.path());
}
});
} finally {
if (numDeleted.get() > maxNumberOfDeletedPathsToLog) {
context.log(logger, "Deleted " + numDeleted.get() + " paths under " + basePath);
} else if (deletedPaths.size() > 0) {
List<Path> paths = deletedPaths.stream()
.map(basePath::relativize)
.sorted()
.collect(Collectors.toList());
context.log(logger, "Deleted these paths in " + basePath + ": " + paths);
}
}
return deletedPaths.size() > 0;
} | class FileFinder {
private static final Logger logger = Logger.getLogger(FileFinder.class.getName());
private final Path basePath;
private final Set<Path> pruned = new HashSet<>();
private Predicate<FileAttributes> matcher;
private int maxDepth = Integer.MAX_VALUE;
private FileFinder(Path basePath, Predicate<FileAttributes> initialMatcher) {
this.basePath = basePath;
this.matcher = initialMatcher;
}
/** Creates a FileFinder at the given basePath */
public static FileFinder from(Path basePath) {
return new FileFinder(basePath, attrs -> true);
}
/** Creates a FileFinder at the given basePath that will match all files */
public static FileFinder files(Path basePath) {
return new FileFinder(basePath, FileAttributes::isRegularFile);
}
/** Creates a FileFinder at the given basePath that will match all directories */
public static FileFinder directories(Path basePath) {
return new FileFinder(basePath, FileAttributes::isDirectory);
}
/**
* Predicate that will be used to match files and directories under the base path.
*
* NOTE: Consecutive calls to this method are ANDed (this include the initial filter from
* {@link
*/
public FileFinder match(Predicate<FileAttributes> matcher) {
this.matcher = this.matcher.and(matcher);
return this;
}
/**
* Path for which whole directory tree will be skipped, including the path itself.
* The path must be under {@code basePath} or be relative to {@code basePath}.
*/
public FileFinder prune(Path path) {
if (!path.isAbsolute())
path = basePath.resolve(path);
if (!path.startsWith(basePath))
throw new IllegalArgumentException("Prune path " + path + " is not under base path " + basePath);
this.pruned.add(path);
return this;
}
/** Convenience method for pruning multiple paths, see {@link
public FileFinder prune(Collection<Path> paths) {
paths.forEach(this::prune);
return this;
}
/**
* Maximum depth (relative to basePath) where contents should be matched with the given filters.
* Default is unlimited.
*/
public FileFinder maxDepth(int maxDepth) {
this.maxDepth = maxDepth;
return this;
}
/**
* Recursively deletes all matching elements
*
* @return true iff anything was matched and deleted
*/
public List<FileAttributes> list() {
LinkedList<FileAttributes> list = new LinkedList<>();
forEach(list::add);
return list;
}
public Stream<FileAttributes> stream() {
return list().stream();
}
public void forEachPath(Consumer<Path> action) {
forEach(attributes -> action.accept(attributes.path()));
}
/** Applies a given consumer to all the matching {@link FileFinder.FileAttributes} */
public void forEach(Consumer<FileAttributes> action) {
applyForEachToMatching(basePath, matcher, maxDepth, action);
}
/**
* <p> This method walks a file tree rooted at a given starting file. The file tree traversal is
* <em>depth-first</em>: The filter function is applied in pre-order (NLR), but the given
* {@link Consumer} will be called in post-order (LRN).
*/
private void applyForEachToMatching(Path basePath, Predicate<FileAttributes> matcher,
int maxDepth, Consumer<FileAttributes> action) {
try {
Files.walkFileTree(basePath, Set.of(), maxDepth, new SimpleFileVisitor<>() {
private final Stack<FileAttributes> matchingDirectoryStack = new Stack<>();
private int currentLevel = -1;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (pruned.contains(dir)) return FileVisitResult.SKIP_SUBTREE;
currentLevel++;
FileAttributes attributes = new FileAttributes(dir, attrs);
if (currentLevel > 0 && matcher.test(attributes))
matchingDirectoryStack.push(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (attrs.isDirectory()) {
preVisitDirectory(file, attrs);
return postVisitDirectory(file, null);
}
FileAttributes attributes = new FileAttributes(file, attrs);
if (matcher.test(attributes))
action.accept(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
if (!matchingDirectoryStack.isEmpty())
action.accept(matchingDirectoryStack.pop());
currentLevel--;
return FileVisitResult.CONTINUE;
}
});
} catch (NoSuchFileException ignored) {
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static class FileAttributes {
private final Path path;
private final BasicFileAttributes attributes;
public FileAttributes(Path path, BasicFileAttributes attributes) {
this.path = path;
this.attributes = attributes;
}
public Path path() { return path; }
public UnixPath unixPath() { return new UnixPath(path); }
public String filename() { return path.getFileName().toString(); }
public Instant lastModifiedTime() { return attributes.lastModifiedTime().toInstant(); }
public boolean isRegularFile() { return attributes.isRegularFile(); }
public boolean isDirectory() { return attributes.isDirectory(); }
public long size() { return attributes.size(); }
}
public static Predicate<FileAttributes> olderThan(Duration duration) {
return attrs -> Duration.between(attrs.lastModifiedTime(), Instant.now()).compareTo(duration) > 0;
}
public static Predicate<FileAttributes> youngerThan(Duration duration) {
return olderThan(duration).negate();
}
public static Predicate<FileAttributes> largerThan(long sizeInBytes) {
return attrs -> attrs.size() > sizeInBytes;
}
public static Predicate<FileAttributes> smallerThan(long sizeInBytes) {
return largerThan(sizeInBytes).negate();
}
public static Predicate<FileAttributes> nameMatches(Pattern pattern) {
return attrs -> pattern.matcher(attrs.filename()).matches();
}
public static Predicate<FileAttributes> nameStartsWith(String string) {
return attrs -> attrs.filename().startsWith(string);
}
public static Predicate<FileAttributes> nameEndsWith(String string) {
return attrs -> attrs.filename().endsWith(string);
}
public static Predicate<FileAttributes> all() {
return attrs -> true;
}
} | class FileFinder {
private static final Logger logger = Logger.getLogger(FileFinder.class.getName());
private final Path basePath;
private final Set<Path> pruned = new HashSet<>();
private Predicate<FileAttributes> matcher;
private int maxDepth = Integer.MAX_VALUE;
private FileFinder(Path basePath, Predicate<FileAttributes> initialMatcher) {
this.basePath = basePath;
this.matcher = initialMatcher;
}
/** Creates a FileFinder at the given basePath */
public static FileFinder from(Path basePath) {
return new FileFinder(basePath, attrs -> true);
}
/** Creates a FileFinder at the given basePath that will match all files */
public static FileFinder files(Path basePath) {
return new FileFinder(basePath, FileAttributes::isRegularFile);
}
/** Creates a FileFinder at the given basePath that will match all directories */
public static FileFinder directories(Path basePath) {
return new FileFinder(basePath, FileAttributes::isDirectory);
}
/**
* Predicate that will be used to match files and directories under the base path.
*
* NOTE: Consecutive calls to this method are ANDed (this include the initial filter from
* {@link
*/
public FileFinder match(Predicate<FileAttributes> matcher) {
this.matcher = this.matcher.and(matcher);
return this;
}
/**
* Path for which whole directory tree will be skipped, including the path itself.
* The path must be under {@code basePath} or be relative to {@code basePath}.
*/
public FileFinder prune(Path path) {
if (!path.isAbsolute())
path = basePath.resolve(path);
if (!path.startsWith(basePath))
throw new IllegalArgumentException("Prune path " + path + " is not under base path " + basePath);
this.pruned.add(path);
return this;
}
/** Convenience method for pruning multiple paths, see {@link
public FileFinder prune(Collection<Path> paths) {
paths.forEach(this::prune);
return this;
}
/**
* Maximum depth (relative to basePath) where contents should be matched with the given filters.
* Default is unlimited.
*/
public FileFinder maxDepth(int maxDepth) {
this.maxDepth = maxDepth;
return this;
}
/**
* Recursively deletes all matching elements
*
* @return true iff anything was matched and deleted
*/
public List<FileAttributes> list() {
LinkedList<FileAttributes> list = new LinkedList<>();
forEach(list::add);
return list;
}
public Stream<FileAttributes> stream() {
return list().stream();
}
public void forEachPath(Consumer<Path> action) {
forEach(attributes -> action.accept(attributes.path()));
}
/** Applies a given consumer to all the matching {@link FileFinder.FileAttributes} */
public void forEach(Consumer<FileAttributes> action) {
applyForEachToMatching(basePath, matcher, maxDepth, action);
}
/**
* <p> This method walks a file tree rooted at a given starting file. The file tree traversal is
* <em>depth-first</em>: The filter function is applied in pre-order (NLR), but the given
* {@link Consumer} will be called in post-order (LRN).
*/
private void applyForEachToMatching(Path basePath, Predicate<FileAttributes> matcher,
int maxDepth, Consumer<FileAttributes> action) {
try {
Files.walkFileTree(basePath, Set.of(), maxDepth, new SimpleFileVisitor<>() {
private final Stack<FileAttributes> matchingDirectoryStack = new Stack<>();
private int currentLevel = -1;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (pruned.contains(dir)) return FileVisitResult.SKIP_SUBTREE;
currentLevel++;
FileAttributes attributes = new FileAttributes(dir, attrs);
if (currentLevel > 0 && matcher.test(attributes))
matchingDirectoryStack.push(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (attrs.isDirectory()) {
preVisitDirectory(file, attrs);
return postVisitDirectory(file, null);
}
FileAttributes attributes = new FileAttributes(file, attrs);
if (matcher.test(attributes))
action.accept(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
if (!matchingDirectoryStack.isEmpty())
action.accept(matchingDirectoryStack.pop());
currentLevel--;
return FileVisitResult.CONTINUE;
}
});
} catch (NoSuchFileException ignored) {
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static class FileAttributes {
private final Path path;
private final BasicFileAttributes attributes;
public FileAttributes(Path path, BasicFileAttributes attributes) {
this.path = path;
this.attributes = attributes;
}
public Path path() { return path; }
public UnixPath unixPath() { return new UnixPath(path); }
public String filename() { return path.getFileName().toString(); }
public Instant lastModifiedTime() { return attributes.lastModifiedTime().toInstant(); }
public boolean isRegularFile() { return attributes.isRegularFile(); }
public boolean isDirectory() { return attributes.isDirectory(); }
public long size() { return attributes.size(); }
}
public static Predicate<FileAttributes> olderThan(Duration duration) {
return attrs -> Duration.between(attrs.lastModifiedTime(), Instant.now()).compareTo(duration) > 0;
}
public static Predicate<FileAttributes> youngerThan(Duration duration) {
return olderThan(duration).negate();
}
public static Predicate<FileAttributes> largerThan(long sizeInBytes) {
return attrs -> attrs.size() > sizeInBytes;
}
public static Predicate<FileAttributes> smallerThan(long sizeInBytes) {
return largerThan(sizeInBytes).negate();
}
public static Predicate<FileAttributes> nameMatches(Pattern pattern) {
return attrs -> pattern.matcher(attrs.filename()).matches();
}
public static Predicate<FileAttributes> nameStartsWith(String string) {
return attrs -> attrs.filename().startsWith(string);
}
public static Predicate<FileAttributes> nameEndsWith(String string) {
return attrs -> attrs.filename().endsWith(string);
}
public static Predicate<FileAttributes> all() {
return attrs -> true;
}
} |
Renamed the variable to `maxNumberOfDeletedPathsToLog` | public boolean deleteRecursively(TaskContext context) {
final int limit = 20;
int[] numDeleted = { 0 };
List<Path> deletedPaths = new ArrayList<>();
try {
forEach(attributes -> {
if (attributes.unixPath().deleteRecursively()) {
if (numDeleted[0]++ <= limit) deletedPaths.add(attributes.path());
}
});
} finally {
if (numDeleted[0] > limit) {
context.log(logger, "Deleted " + numDeleted[0] + " paths under " + basePath);
} else if (deletedPaths.size() > 0) {
List<Path> paths = deletedPaths.stream()
.map(basePath::relativize)
.sorted()
.collect(Collectors.toList());
context.log(logger, "Deleted these paths in " + basePath + ": " + paths);
}
}
return deletedPaths.size() > 0;
} | final int limit = 20; | public boolean deleteRecursively(TaskContext context) {
final int maxNumberOfDeletedPathsToLog = 20;
MutableInteger numDeleted = new MutableInteger(0);
List<Path> deletedPaths = new ArrayList<>();
try {
forEach(attributes -> {
if (attributes.unixPath().deleteRecursively()) {
if (numDeleted.next() <= maxNumberOfDeletedPathsToLog) deletedPaths.add(attributes.path());
}
});
} finally {
if (numDeleted.get() > maxNumberOfDeletedPathsToLog) {
context.log(logger, "Deleted " + numDeleted.get() + " paths under " + basePath);
} else if (deletedPaths.size() > 0) {
List<Path> paths = deletedPaths.stream()
.map(basePath::relativize)
.sorted()
.collect(Collectors.toList());
context.log(logger, "Deleted these paths in " + basePath + ": " + paths);
}
}
return deletedPaths.size() > 0;
} | class FileFinder {
private static final Logger logger = Logger.getLogger(FileFinder.class.getName());
private final Path basePath;
private final Set<Path> pruned = new HashSet<>();
private Predicate<FileAttributes> matcher;
private int maxDepth = Integer.MAX_VALUE;
private FileFinder(Path basePath, Predicate<FileAttributes> initialMatcher) {
this.basePath = basePath;
this.matcher = initialMatcher;
}
/** Creates a FileFinder at the given basePath */
public static FileFinder from(Path basePath) {
return new FileFinder(basePath, attrs -> true);
}
/** Creates a FileFinder at the given basePath that will match all files */
public static FileFinder files(Path basePath) {
return new FileFinder(basePath, FileAttributes::isRegularFile);
}
/** Creates a FileFinder at the given basePath that will match all directories */
public static FileFinder directories(Path basePath) {
return new FileFinder(basePath, FileAttributes::isDirectory);
}
/**
* Predicate that will be used to match files and directories under the base path.
*
* NOTE: Consecutive calls to this method are ANDed (this include the initial filter from
* {@link
*/
public FileFinder match(Predicate<FileAttributes> matcher) {
this.matcher = this.matcher.and(matcher);
return this;
}
/**
* Path for which whole directory tree will be skipped, including the path itself.
* The path must be under {@code basePath} or be relative to {@code basePath}.
*/
public FileFinder prune(Path path) {
if (!path.isAbsolute())
path = basePath.resolve(path);
if (!path.startsWith(basePath))
throw new IllegalArgumentException("Prune path " + path + " is not under base path " + basePath);
this.pruned.add(path);
return this;
}
/** Convenience method for pruning multiple paths, see {@link
public FileFinder prune(Collection<Path> paths) {
paths.forEach(this::prune);
return this;
}
/**
* Maximum depth (relative to basePath) where contents should be matched with the given filters.
* Default is unlimited.
*/
public FileFinder maxDepth(int maxDepth) {
this.maxDepth = maxDepth;
return this;
}
/**
* Recursively deletes all matching elements
*
* @return true iff anything was matched and deleted
*/
public List<FileAttributes> list() {
LinkedList<FileAttributes> list = new LinkedList<>();
forEach(list::add);
return list;
}
public Stream<FileAttributes> stream() {
return list().stream();
}
public void forEachPath(Consumer<Path> action) {
forEach(attributes -> action.accept(attributes.path()));
}
/** Applies a given consumer to all the matching {@link FileFinder.FileAttributes} */
public void forEach(Consumer<FileAttributes> action) {
applyForEachToMatching(basePath, matcher, maxDepth, action);
}
/**
* <p> This method walks a file tree rooted at a given starting file. The file tree traversal is
* <em>depth-first</em>: The filter function is applied in pre-order (NLR), but the given
* {@link Consumer} will be called in post-order (LRN).
*/
private void applyForEachToMatching(Path basePath, Predicate<FileAttributes> matcher,
int maxDepth, Consumer<FileAttributes> action) {
try {
Files.walkFileTree(basePath, Set.of(), maxDepth, new SimpleFileVisitor<>() {
private final Stack<FileAttributes> matchingDirectoryStack = new Stack<>();
private int currentLevel = -1;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (pruned.contains(dir)) return FileVisitResult.SKIP_SUBTREE;
currentLevel++;
FileAttributes attributes = new FileAttributes(dir, attrs);
if (currentLevel > 0 && matcher.test(attributes))
matchingDirectoryStack.push(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (attrs.isDirectory()) {
preVisitDirectory(file, attrs);
return postVisitDirectory(file, null);
}
FileAttributes attributes = new FileAttributes(file, attrs);
if (matcher.test(attributes))
action.accept(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
if (!matchingDirectoryStack.isEmpty())
action.accept(matchingDirectoryStack.pop());
currentLevel--;
return FileVisitResult.CONTINUE;
}
});
} catch (NoSuchFileException ignored) {
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static class FileAttributes {
private final Path path;
private final BasicFileAttributes attributes;
public FileAttributes(Path path, BasicFileAttributes attributes) {
this.path = path;
this.attributes = attributes;
}
public Path path() { return path; }
public UnixPath unixPath() { return new UnixPath(path); }
public String filename() { return path.getFileName().toString(); }
public Instant lastModifiedTime() { return attributes.lastModifiedTime().toInstant(); }
public boolean isRegularFile() { return attributes.isRegularFile(); }
public boolean isDirectory() { return attributes.isDirectory(); }
public long size() { return attributes.size(); }
}
public static Predicate<FileAttributes> olderThan(Duration duration) {
return attrs -> Duration.between(attrs.lastModifiedTime(), Instant.now()).compareTo(duration) > 0;
}
public static Predicate<FileAttributes> youngerThan(Duration duration) {
return olderThan(duration).negate();
}
public static Predicate<FileAttributes> largerThan(long sizeInBytes) {
return attrs -> attrs.size() > sizeInBytes;
}
public static Predicate<FileAttributes> smallerThan(long sizeInBytes) {
return largerThan(sizeInBytes).negate();
}
public static Predicate<FileAttributes> nameMatches(Pattern pattern) {
return attrs -> pattern.matcher(attrs.filename()).matches();
}
public static Predicate<FileAttributes> nameStartsWith(String string) {
return attrs -> attrs.filename().startsWith(string);
}
public static Predicate<FileAttributes> nameEndsWith(String string) {
return attrs -> attrs.filename().endsWith(string);
}
public static Predicate<FileAttributes> all() {
return attrs -> true;
}
} | class FileFinder {
private static final Logger logger = Logger.getLogger(FileFinder.class.getName());
private final Path basePath;
private final Set<Path> pruned = new HashSet<>();
private Predicate<FileAttributes> matcher;
private int maxDepth = Integer.MAX_VALUE;
private FileFinder(Path basePath, Predicate<FileAttributes> initialMatcher) {
this.basePath = basePath;
this.matcher = initialMatcher;
}
/** Creates a FileFinder at the given basePath */
public static FileFinder from(Path basePath) {
return new FileFinder(basePath, attrs -> true);
}
/** Creates a FileFinder at the given basePath that will match all files */
public static FileFinder files(Path basePath) {
return new FileFinder(basePath, FileAttributes::isRegularFile);
}
/** Creates a FileFinder at the given basePath that will match all directories */
public static FileFinder directories(Path basePath) {
return new FileFinder(basePath, FileAttributes::isDirectory);
}
/**
* Predicate that will be used to match files and directories under the base path.
*
* NOTE: Consecutive calls to this method are ANDed (this include the initial filter from
* {@link
*/
public FileFinder match(Predicate<FileAttributes> matcher) {
this.matcher = this.matcher.and(matcher);
return this;
}
/**
* Path for which whole directory tree will be skipped, including the path itself.
* The path must be under {@code basePath} or be relative to {@code basePath}.
*/
public FileFinder prune(Path path) {
if (!path.isAbsolute())
path = basePath.resolve(path);
if (!path.startsWith(basePath))
throw new IllegalArgumentException("Prune path " + path + " is not under base path " + basePath);
this.pruned.add(path);
return this;
}
/** Convenience method for pruning multiple paths, see {@link
public FileFinder prune(Collection<Path> paths) {
paths.forEach(this::prune);
return this;
}
/**
* Maximum depth (relative to basePath) where contents should be matched with the given filters.
* Default is unlimited.
*/
public FileFinder maxDepth(int maxDepth) {
this.maxDepth = maxDepth;
return this;
}
/**
* Recursively deletes all matching elements
*
* @return true iff anything was matched and deleted
*/
public List<FileAttributes> list() {
LinkedList<FileAttributes> list = new LinkedList<>();
forEach(list::add);
return list;
}
public Stream<FileAttributes> stream() {
return list().stream();
}
public void forEachPath(Consumer<Path> action) {
forEach(attributes -> action.accept(attributes.path()));
}
/** Applies a given consumer to all the matching {@link FileFinder.FileAttributes} */
public void forEach(Consumer<FileAttributes> action) {
applyForEachToMatching(basePath, matcher, maxDepth, action);
}
/**
* <p> This method walks a file tree rooted at a given starting file. The file tree traversal is
* <em>depth-first</em>: The filter function is applied in pre-order (NLR), but the given
* {@link Consumer} will be called in post-order (LRN).
*/
private void applyForEachToMatching(Path basePath, Predicate<FileAttributes> matcher,
int maxDepth, Consumer<FileAttributes> action) {
try {
Files.walkFileTree(basePath, Set.of(), maxDepth, new SimpleFileVisitor<>() {
private final Stack<FileAttributes> matchingDirectoryStack = new Stack<>();
private int currentLevel = -1;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (pruned.contains(dir)) return FileVisitResult.SKIP_SUBTREE;
currentLevel++;
FileAttributes attributes = new FileAttributes(dir, attrs);
if (currentLevel > 0 && matcher.test(attributes))
matchingDirectoryStack.push(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (attrs.isDirectory()) {
preVisitDirectory(file, attrs);
return postVisitDirectory(file, null);
}
FileAttributes attributes = new FileAttributes(file, attrs);
if (matcher.test(attributes))
action.accept(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
if (!matchingDirectoryStack.isEmpty())
action.accept(matchingDirectoryStack.pop());
currentLevel--;
return FileVisitResult.CONTINUE;
}
});
} catch (NoSuchFileException ignored) {
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static class FileAttributes {
private final Path path;
private final BasicFileAttributes attributes;
public FileAttributes(Path path, BasicFileAttributes attributes) {
this.path = path;
this.attributes = attributes;
}
public Path path() { return path; }
public UnixPath unixPath() { return new UnixPath(path); }
public String filename() { return path.getFileName().toString(); }
public Instant lastModifiedTime() { return attributes.lastModifiedTime().toInstant(); }
public boolean isRegularFile() { return attributes.isRegularFile(); }
public boolean isDirectory() { return attributes.isDirectory(); }
public long size() { return attributes.size(); }
}
public static Predicate<FileAttributes> olderThan(Duration duration) {
return attrs -> Duration.between(attrs.lastModifiedTime(), Instant.now()).compareTo(duration) > 0;
}
public static Predicate<FileAttributes> youngerThan(Duration duration) {
return olderThan(duration).negate();
}
public static Predicate<FileAttributes> largerThan(long sizeInBytes) {
return attrs -> attrs.size() > sizeInBytes;
}
public static Predicate<FileAttributes> smallerThan(long sizeInBytes) {
return largerThan(sizeInBytes).negate();
}
public static Predicate<FileAttributes> nameMatches(Pattern pattern) {
return attrs -> pattern.matcher(attrs.filename()).matches();
}
public static Predicate<FileAttributes> nameStartsWith(String string) {
return attrs -> attrs.filename().startsWith(string);
}
public static Predicate<FileAttributes> nameEndsWith(String string) {
return attrs -> attrs.filename().endsWith(string);
}
public static Predicate<FileAttributes> all() {
return attrs -> true;
}
} |
Ah, right. Didn't look at the context. Then I suggest adding a comment, or using MutableInteger. | public boolean deleteRecursively(TaskContext context) {
final int limit = 20;
int[] numDeleted = { 0 };
List<Path> deletedPaths = new ArrayList<>();
try {
forEach(attributes -> {
if (attributes.unixPath().deleteRecursively()) {
if (numDeleted[0]++ <= limit) deletedPaths.add(attributes.path());
}
});
} finally {
if (numDeleted[0] > limit) {
context.log(logger, "Deleted " + numDeleted[0] + " paths under " + basePath);
} else if (deletedPaths.size() > 0) {
List<Path> paths = deletedPaths.stream()
.map(basePath::relativize)
.sorted()
.collect(Collectors.toList());
context.log(logger, "Deleted these paths in " + basePath + ": " + paths);
}
}
return deletedPaths.size() > 0;
} | int[] numDeleted = { 0 }; | public boolean deleteRecursively(TaskContext context) {
final int maxNumberOfDeletedPathsToLog = 20;
MutableInteger numDeleted = new MutableInteger(0);
List<Path> deletedPaths = new ArrayList<>();
try {
forEach(attributes -> {
if (attributes.unixPath().deleteRecursively()) {
if (numDeleted.next() <= maxNumberOfDeletedPathsToLog) deletedPaths.add(attributes.path());
}
});
} finally {
if (numDeleted.get() > maxNumberOfDeletedPathsToLog) {
context.log(logger, "Deleted " + numDeleted.get() + " paths under " + basePath);
} else if (deletedPaths.size() > 0) {
List<Path> paths = deletedPaths.stream()
.map(basePath::relativize)
.sorted()
.collect(Collectors.toList());
context.log(logger, "Deleted these paths in " + basePath + ": " + paths);
}
}
return deletedPaths.size() > 0;
} | class FileFinder {
private static final Logger logger = Logger.getLogger(FileFinder.class.getName());
private final Path basePath;
private final Set<Path> pruned = new HashSet<>();
private Predicate<FileAttributes> matcher;
private int maxDepth = Integer.MAX_VALUE;
private FileFinder(Path basePath, Predicate<FileAttributes> initialMatcher) {
this.basePath = basePath;
this.matcher = initialMatcher;
}
/** Creates a FileFinder at the given basePath */
public static FileFinder from(Path basePath) {
return new FileFinder(basePath, attrs -> true);
}
/** Creates a FileFinder at the given basePath that will match all files */
public static FileFinder files(Path basePath) {
return new FileFinder(basePath, FileAttributes::isRegularFile);
}
/** Creates a FileFinder at the given basePath that will match all directories */
public static FileFinder directories(Path basePath) {
return new FileFinder(basePath, FileAttributes::isDirectory);
}
/**
* Predicate that will be used to match files and directories under the base path.
*
* NOTE: Consecutive calls to this method are ANDed (this include the initial filter from
* {@link
*/
public FileFinder match(Predicate<FileAttributes> matcher) {
this.matcher = this.matcher.and(matcher);
return this;
}
/**
* Path for which whole directory tree will be skipped, including the path itself.
* The path must be under {@code basePath} or be relative to {@code basePath}.
*/
public FileFinder prune(Path path) {
if (!path.isAbsolute())
path = basePath.resolve(path);
if (!path.startsWith(basePath))
throw new IllegalArgumentException("Prune path " + path + " is not under base path " + basePath);
this.pruned.add(path);
return this;
}
/** Convenience method for pruning multiple paths, see {@link
public FileFinder prune(Collection<Path> paths) {
paths.forEach(this::prune);
return this;
}
/**
* Maximum depth (relative to basePath) where contents should be matched with the given filters.
* Default is unlimited.
*/
public FileFinder maxDepth(int maxDepth) {
this.maxDepth = maxDepth;
return this;
}
/**
* Recursively deletes all matching elements
*
* @return true iff anything was matched and deleted
*/
public List<FileAttributes> list() {
LinkedList<FileAttributes> list = new LinkedList<>();
forEach(list::add);
return list;
}
public Stream<FileAttributes> stream() {
return list().stream();
}
public void forEachPath(Consumer<Path> action) {
forEach(attributes -> action.accept(attributes.path()));
}
/** Applies a given consumer to all the matching {@link FileFinder.FileAttributes} */
public void forEach(Consumer<FileAttributes> action) {
applyForEachToMatching(basePath, matcher, maxDepth, action);
}
/**
* <p> This method walks a file tree rooted at a given starting file. The file tree traversal is
* <em>depth-first</em>: The filter function is applied in pre-order (NLR), but the given
* {@link Consumer} will be called in post-order (LRN).
*/
private void applyForEachToMatching(Path basePath, Predicate<FileAttributes> matcher,
int maxDepth, Consumer<FileAttributes> action) {
try {
Files.walkFileTree(basePath, Set.of(), maxDepth, new SimpleFileVisitor<>() {
private final Stack<FileAttributes> matchingDirectoryStack = new Stack<>();
private int currentLevel = -1;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (pruned.contains(dir)) return FileVisitResult.SKIP_SUBTREE;
currentLevel++;
FileAttributes attributes = new FileAttributes(dir, attrs);
if (currentLevel > 0 && matcher.test(attributes))
matchingDirectoryStack.push(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (attrs.isDirectory()) {
preVisitDirectory(file, attrs);
return postVisitDirectory(file, null);
}
FileAttributes attributes = new FileAttributes(file, attrs);
if (matcher.test(attributes))
action.accept(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
if (!matchingDirectoryStack.isEmpty())
action.accept(matchingDirectoryStack.pop());
currentLevel--;
return FileVisitResult.CONTINUE;
}
});
} catch (NoSuchFileException ignored) {
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static class FileAttributes {
private final Path path;
private final BasicFileAttributes attributes;
public FileAttributes(Path path, BasicFileAttributes attributes) {
this.path = path;
this.attributes = attributes;
}
public Path path() { return path; }
public UnixPath unixPath() { return new UnixPath(path); }
public String filename() { return path.getFileName().toString(); }
public Instant lastModifiedTime() { return attributes.lastModifiedTime().toInstant(); }
public boolean isRegularFile() { return attributes.isRegularFile(); }
public boolean isDirectory() { return attributes.isDirectory(); }
public long size() { return attributes.size(); }
}
public static Predicate<FileAttributes> olderThan(Duration duration) {
return attrs -> Duration.between(attrs.lastModifiedTime(), Instant.now()).compareTo(duration) > 0;
}
public static Predicate<FileAttributes> youngerThan(Duration duration) {
return olderThan(duration).negate();
}
public static Predicate<FileAttributes> largerThan(long sizeInBytes) {
return attrs -> attrs.size() > sizeInBytes;
}
public static Predicate<FileAttributes> smallerThan(long sizeInBytes) {
return largerThan(sizeInBytes).negate();
}
public static Predicate<FileAttributes> nameMatches(Pattern pattern) {
return attrs -> pattern.matcher(attrs.filename()).matches();
}
public static Predicate<FileAttributes> nameStartsWith(String string) {
return attrs -> attrs.filename().startsWith(string);
}
public static Predicate<FileAttributes> nameEndsWith(String string) {
return attrs -> attrs.filename().endsWith(string);
}
public static Predicate<FileAttributes> all() {
return attrs -> true;
}
} | class FileFinder {
private static final Logger logger = Logger.getLogger(FileFinder.class.getName());
private final Path basePath;
private final Set<Path> pruned = new HashSet<>();
private Predicate<FileAttributes> matcher;
private int maxDepth = Integer.MAX_VALUE;
private FileFinder(Path basePath, Predicate<FileAttributes> initialMatcher) {
this.basePath = basePath;
this.matcher = initialMatcher;
}
/** Creates a FileFinder at the given basePath */
public static FileFinder from(Path basePath) {
return new FileFinder(basePath, attrs -> true);
}
/** Creates a FileFinder at the given basePath that will match all files */
public static FileFinder files(Path basePath) {
return new FileFinder(basePath, FileAttributes::isRegularFile);
}
/** Creates a FileFinder at the given basePath that will match all directories */
public static FileFinder directories(Path basePath) {
return new FileFinder(basePath, FileAttributes::isDirectory);
}
/**
* Predicate that will be used to match files and directories under the base path.
*
* NOTE: Consecutive calls to this method are ANDed (this include the initial filter from
* {@link
*/
public FileFinder match(Predicate<FileAttributes> matcher) {
this.matcher = this.matcher.and(matcher);
return this;
}
/**
* Path for which whole directory tree will be skipped, including the path itself.
* The path must be under {@code basePath} or be relative to {@code basePath}.
*/
public FileFinder prune(Path path) {
if (!path.isAbsolute())
path = basePath.resolve(path);
if (!path.startsWith(basePath))
throw new IllegalArgumentException("Prune path " + path + " is not under base path " + basePath);
this.pruned.add(path);
return this;
}
/** Convenience method for pruning multiple paths, see {@link
public FileFinder prune(Collection<Path> paths) {
paths.forEach(this::prune);
return this;
}
/**
* Maximum depth (relative to basePath) where contents should be matched with the given filters.
* Default is unlimited.
*/
public FileFinder maxDepth(int maxDepth) {
this.maxDepth = maxDepth;
return this;
}
/**
* Recursively deletes all matching elements
*
* @return true iff anything was matched and deleted
*/
public List<FileAttributes> list() {
LinkedList<FileAttributes> list = new LinkedList<>();
forEach(list::add);
return list;
}
public Stream<FileAttributes> stream() {
return list().stream();
}
public void forEachPath(Consumer<Path> action) {
forEach(attributes -> action.accept(attributes.path()));
}
/** Applies a given consumer to all the matching {@link FileFinder.FileAttributes} */
public void forEach(Consumer<FileAttributes> action) {
applyForEachToMatching(basePath, matcher, maxDepth, action);
}
/**
* <p> This method walks a file tree rooted at a given starting file. The file tree traversal is
* <em>depth-first</em>: The filter function is applied in pre-order (NLR), but the given
* {@link Consumer} will be called in post-order (LRN).
*/
private void applyForEachToMatching(Path basePath, Predicate<FileAttributes> matcher,
int maxDepth, Consumer<FileAttributes> action) {
try {
Files.walkFileTree(basePath, Set.of(), maxDepth, new SimpleFileVisitor<>() {
private final Stack<FileAttributes> matchingDirectoryStack = new Stack<>();
private int currentLevel = -1;
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (pruned.contains(dir)) return FileVisitResult.SKIP_SUBTREE;
currentLevel++;
FileAttributes attributes = new FileAttributes(dir, attrs);
if (currentLevel > 0 && matcher.test(attributes))
matchingDirectoryStack.push(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (attrs.isDirectory()) {
preVisitDirectory(file, attrs);
return postVisitDirectory(file, null);
}
FileAttributes attributes = new FileAttributes(file, attrs);
if (matcher.test(attributes))
action.accept(attributes);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
if (!matchingDirectoryStack.isEmpty())
action.accept(matchingDirectoryStack.pop());
currentLevel--;
return FileVisitResult.CONTINUE;
}
});
} catch (NoSuchFileException ignored) {
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static class FileAttributes {
private final Path path;
private final BasicFileAttributes attributes;
public FileAttributes(Path path, BasicFileAttributes attributes) {
this.path = path;
this.attributes = attributes;
}
public Path path() { return path; }
public UnixPath unixPath() { return new UnixPath(path); }
public String filename() { return path.getFileName().toString(); }
public Instant lastModifiedTime() { return attributes.lastModifiedTime().toInstant(); }
public boolean isRegularFile() { return attributes.isRegularFile(); }
public boolean isDirectory() { return attributes.isDirectory(); }
public long size() { return attributes.size(); }
}
public static Predicate<FileAttributes> olderThan(Duration duration) {
return attrs -> Duration.between(attrs.lastModifiedTime(), Instant.now()).compareTo(duration) > 0;
}
public static Predicate<FileAttributes> youngerThan(Duration duration) {
return olderThan(duration).negate();
}
public static Predicate<FileAttributes> largerThan(long sizeInBytes) {
return attrs -> attrs.size() > sizeInBytes;
}
public static Predicate<FileAttributes> smallerThan(long sizeInBytes) {
return largerThan(sizeInBytes).negate();
}
public static Predicate<FileAttributes> nameMatches(Pattern pattern) {
return attrs -> pattern.matcher(attrs.filename()).matches();
}
public static Predicate<FileAttributes> nameStartsWith(String string) {
return attrs -> attrs.filename().startsWith(string);
}
public static Predicate<FileAttributes> nameEndsWith(String string) {
return attrs -> attrs.filename().endsWith(string);
}
public static Predicate<FileAttributes> all() {
return attrs -> true;
}
} |
"zone supports"? | public void testDevDeployment() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.dev)
.majorVersion(6)
.region("us-east-1")
.build();
var context = tester.newDeploymentContext();
ZoneId zone = ZoneId.from("dev", "us-east-1");
tester.controllerTester().zoneRegistry()
.setRoutingMethod(ZoneApiMock.from(zone), RoutingMethod.shared, RoutingMethod.sharedLayer4);
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), DeployOptions.none());
assertTrue("Application deployed and activated",
tester.configServer().application(context.instanceId(), zone).get().activated());
assertTrue("No job status added",
context.instanceJobs().isEmpty());
assertEquals("DeploymentSpec is not persisted", DeploymentSpec.empty, context.application().deploymentSpec());
Set<RoutingMethod> routingMethods = tester.controller().routing().endpointsOf(context.deploymentIdIn(zone))
.asList()
.stream()
.map(Endpoint::routingMethod)
.collect(Collectors.toSet());
assertThat(routingMethods, IsIterableContainingInAnyOrder.containsInAnyOrder(RoutingMethod.shared, RoutingMethod.sharedLayer4));
} | public void testDevDeployment() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.dev)
.majorVersion(6)
.region("us-east-1")
.build();
var context = tester.newDeploymentContext();
ZoneId zone = ZoneId.from("dev", "us-east-1");
tester.controllerTester().zoneRegistry()
.setRoutingMethod(ZoneApiMock.from(zone), RoutingMethod.shared, RoutingMethod.sharedLayer4);
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), DeployOptions.none());
assertTrue("Application deployed and activated",
tester.configServer().application(context.instanceId(), zone).get().activated());
assertTrue("No job status added",
context.instanceJobs().isEmpty());
assertEquals("DeploymentSpec is not persisted", DeploymentSpec.empty, context.application().deploymentSpec());
Set<RoutingMethod> routingMethods = tester.controller().routing().endpointsOf(context.deploymentIdIn(zone))
.asList()
.stream()
.map(Endpoint::routingMethod)
.collect(Collectors.toSet());
assertEquals(routingMethods, Set.of(RoutingMethod.shared, RoutingMethod.sharedLayer4));
} | class ControllerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
public void testDeployment() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
Version version1 = tester.configServer().initialVersion();
var context = tester.newDeploymentContext();
context.submit(applicationPackage);
assertEquals("Application version is known from completion of initial job",
ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1, "a@b", new Version("6.1"), Instant.ofEpochSecond(1)),
context.instance().change().application().get());
context.runJob(systemTest);
context.runJob(stagingTest);
ApplicationVersion applicationVersion = context.instance().change().application().get();
assertFalse("Application version has been set during deployment", applicationVersion.isUnknown());
tester.triggerJobs();
tester.clock().advance(Duration.ofSeconds(1));
context.timeOutUpgrade(productionUsWest1);
assertEquals(4, context.instanceJobs().size());
tester.triggerJobs();
tester.controllerTester().createNewController();
assertNotNull(tester.controller().tenants().get(TenantName.from("tenant1")));
assertNotNull(tester.controller().applications().requireInstance(context.instanceId()));
context.submit(applicationPackage);
context.runJob(systemTest);
context.runJob(stagingTest);
context.jobAborted(productionUsWest1);
context.runJob(productionUsWest1);
tester.triggerJobs();
context.runJob(productionUsEast3);
assertEquals(4, context.instanceJobs().size());
applicationPackage = new ApplicationPackageBuilder()
.instances("hellO")
.build();
try {
context.submit(applicationPackage);
fail("Expected exception due to illegal deployment spec.");
}
catch (IllegalArgumentException e) {
assertEquals("Invalid id 'hellO'. Tenant, application and instance names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.", e.getMessage());
}
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("deep-space-9")
.build();
try {
context.submit(applicationPackage);
fail("Expected exception due to illegal deployment spec.");
}
catch (IllegalArgumentException e) {
assertEquals("Zone prod.deep-space-9 in deployment spec was not found in this system!", e.getMessage());
}
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-east-3")
.build();
try {
assertTrue(context.instance().deployments().containsKey(ZoneId.from("prod", "us-west-1")));
context.submit(applicationPackage);
fail("Expected exception due to illegal production deployment removal");
}
catch (IllegalArgumentException e) {
assertEquals("deployment-removal: application 'tenant.application' is deployed in us-west-1, but does not include this zone in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval),
e.getMessage());
}
assertNotNull("Zone was not removed",
context.instance().deployments().get(productionUsWest1.zone(main)));
applicationPackage = new ApplicationPackageBuilder()
.allow(ValidationId.deploymentRemoval)
.upgradePolicy("default")
.environment(Environment.prod)
.region("us-east-3")
.build();
context.submit(applicationPackage);
assertNull("Zone was removed",
context.instance().deployments().get(productionUsWest1.zone(main)));
assertNull("Deployment job was removed", context.instanceJobs().get(productionUsWest1));
}
@Test
public void testGlobalRotations() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.region(zone1.region())
.region(zone2.region())
.endpoint("default", "default", zone1.region().value(), zone2.region().value())
.build();
context.submit(applicationPackage).deploy();
var deployment1 = context.deploymentIdIn(zone1);
var status1 = tester.controller().routing().globalRotationStatus(deployment1);
assertEquals(1, status1.size());
assertTrue("All upstreams are in", status1.values().stream().allMatch(es -> es.getStatus() == EndpointStatus.Status.in));
var newStatus = new EndpointStatus(EndpointStatus.Status.out, "unit-test", ControllerTest.class.getSimpleName(), tester.clock().instant().getEpochSecond());
tester.controller().routing().setGlobalRotationStatus(deployment1, newStatus);
status1 = tester.controller().routing().globalRotationStatus(deployment1);
assertEquals(1, status1.size());
assertTrue("All upstreams are out", status1.values().stream().allMatch(es -> es.getStatus() == EndpointStatus.Status.out));
assertTrue("Reason is set", status1.values().stream().allMatch(es -> es.getReason().equals("unit-test")));
var status2 = tester.controller().routing().globalRotationStatus(context.deploymentIdIn(zone2));
assertEquals(1, status2.size());
assertTrue("All upstreams are in", status2.values().stream().allMatch(es -> es.getStatus() == EndpointStatus.Status.in));
}
@Test
public void testDnsAliasRegistration() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
for (Deployment deployment : deployments) {
assertEquals("Rotation names are passed to config server in " + deployment.zone(),
Set.of("rotation-id-01",
"app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(deployment.zone())));
}
context.flushDnsUpdates();
assertEquals(1, tester.controllerTester().nameService().records().size());
var record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
}
@Test
public void testDnsAliasRegistrationLegacy() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
for (Deployment deployment : deployments) {
assertEquals("Rotation names are passed to config server in " + deployment.zone(),
Set.of("rotation-id-01",
"app1--tenant1.global.vespa.oath.cloud",
"app1.tenant1.global.vespa.yahooapis.com",
"app1--tenant1.global.vespa.yahooapis.com"),
tester.configServer().rotationNames().get(context.deploymentIdIn(deployment.zone())));
}
context.flushDnsUpdates();
assertEquals(3, tester.controllerTester().nameService().records().size());
Optional<Record> record = tester.controllerTester().findCname("app1--tenant1.global.vespa.yahooapis.com");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.yahooapis.com", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
record = tester.controllerTester().findCname("app1.tenant1.global.vespa.yahooapis.com");
assertTrue(record.isPresent());
assertEquals("app1.tenant1.global.vespa.yahooapis.com", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
}
@Test
public void testDnsAliasRegistrationWithEndpoints() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("foobar", "qrs", "us-west-1", "us-central-1")
.endpoint("default", "qrs", "us-west-1", "us-central-1")
.endpoint("all", "qrs")
.endpoint("west", "qrs", "us-west-1")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
var notWest = Set.of(
"rotation-id-01", "foobar--app1--tenant1.global.vespa.oath.cloud",
"rotation-id-02", "app1--tenant1.global.vespa.oath.cloud",
"rotation-id-03", "all--app1--tenant1.global.vespa.oath.cloud"
);
var west = Sets.union(notWest, Set.of("rotation-id-04", "west--app1--tenant1.global.vespa.oath.cloud"));
for (Deployment deployment : deployments) {
assertEquals("Rotation names are passed to config server in " + deployment.zone(),
ZoneId.from("prod.us-west-1").equals(deployment.zone()) ? west : notWest,
tester.configServer().rotationNames().get(context.deploymentIdIn(deployment.zone())));
}
context.flushDnsUpdates();
assertEquals(4, tester.controllerTester().nameService().records().size());
var record1 = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record1.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record1.get().name().asString());
assertEquals("rotation-fqdn-02.", record1.get().data().asString());
var record2 = tester.controllerTester().findCname("foobar--app1--tenant1.global.vespa.oath.cloud");
assertTrue(record2.isPresent());
assertEquals("foobar--app1--tenant1.global.vespa.oath.cloud", record2.get().name().asString());
assertEquals("rotation-fqdn-01.", record2.get().data().asString());
var record3 = tester.controllerTester().findCname("all--app1--tenant1.global.vespa.oath.cloud");
assertTrue(record3.isPresent());
assertEquals("all--app1--tenant1.global.vespa.oath.cloud", record3.get().name().asString());
assertEquals("rotation-fqdn-03.", record3.get().data().asString());
var record4 = tester.controllerTester().findCname("west--app1--tenant1.global.vespa.oath.cloud");
assertTrue(record4.isPresent());
assertEquals("west--app1--tenant1.global.vespa.oath.cloud", record4.get().name().asString());
assertEquals("rotation-fqdn-04.", record4.get().data().asString());
}
@Test
public void testDnsAliasRegistrationWithChangingEndpoints() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
var west = ZoneId.from("prod", "us-west-1");
var central = ZoneId.from("prod", "us-central-1");
var east = ZoneId.from("prod", "us-east-3");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage).deploy();
for (var zone : List.of(west, central)) {
assertEquals(
"Zone " + zone + " is a member of global endpoint",
Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone))
);
}
ApplicationPackage applicationPackage2 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value())
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage2).deploy();
for (var zone : List.of(west, central)) {
assertEquals(
"Zone " + zone + " is a member of global endpoint",
Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone))
);
}
assertEquals(
"Zone " + east + " is a member of global endpoint",
Set.of("rotation-id-02", "east--app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(east))
);
ApplicationPackage applicationPackage3 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value(), east.region().value())
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage3).deploy();
for (var zone : List.of(west, central, east)) {
assertEquals(
"Zone " + zone + " is a member of global endpoint",
zone.equals(east)
? Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud",
"rotation-id-02", "east--app1--tenant1.global.vespa.oath.cloud")
: Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone))
);
}
ApplicationPackage applicationPackage4 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value())
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
try {
context.submit(applicationPackage4);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant1.app1' has endpoints " +
"[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
"but does not include all of these in deployment.xml. Deploying given deployment.xml " +
"will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1] " +
"and add [endpoint 'default' (cluster qrs) -> us-central-1, us-west-1]. " +
ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
}
ApplicationPackage applicationPackage5 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
try {
context.submit(applicationPackage5);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant1.app1' has endpoints " +
"[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
"but does not include all of these in deployment.xml. Deploying given deployment.xml " +
"will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1]. " +
ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
}
ApplicationPackage applicationPackage6 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage6);
}
@Test
public void testUnassignRotations() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", "us-west-1", "us-central-1")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
ApplicationPackage applicationPackage2 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-central-1")
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage2).deploy();
assertEquals(List.of(), context.instance().rotations());
assertEquals(
Set.of(),
tester.configServer().rotationNames().get(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")))
);
}
@Test
public void testUpdatesExistingDnsAlias() {
{
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
assertEquals(1, tester.controllerTester().nameService().records().size());
Optional<Record> record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.allow(ValidationId.deploymentRemoval)
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage);
tester.applications().deleteApplication(context.application().id(),
tester.controllerTester().credentialsFor(context.application().id().tenant()));
try (RotationLock lock = tester.controller().routing().rotations().lock()) {
assertTrue("Rotation is unassigned",
tester.controller().routing().rotations().availableRotations(lock)
.containsKey(new RotationId("rotation-id-01")));
}
context.flushDnsUpdates();
record = tester.controllerTester().findCname("app1--tenant1.global.vespa.yahooapis.com");
assertTrue(record.isEmpty());
record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isEmpty());
record = tester.controllerTester().findCname("app1.tenant1.global.vespa.yahooapis.com");
assertTrue(record.isEmpty());
}
{
var context = tester.newDeploymentContext("tenant2", "app2", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
assertEquals(1, tester.controllerTester().nameService().records().size());
var record = tester.controllerTester().findCname("app2--tenant2.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app2--tenant2.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
}
{
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
assertEquals("rotation-id-02", context.instance().rotations().get(0).rotationId().asString());
assertEquals(2, tester.controllerTester().nameService().records().size());
var record1 = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record1.isPresent());
assertEquals("rotation-fqdn-02.", record1.get().data().asString());
var record2 = tester.controllerTester().findCname("app2--tenant2.global.vespa.oath.cloud");
assertTrue(record2.isPresent());
assertEquals("rotation-fqdn-01.", record2.get().data().asString());
}
}
@Test
public void testIntegrationTestDeployment() {
Version six = Version.fromString("6.1");
tester.controllerTester().zoneRegistry().setSystemName(SystemName.cd);
tester.controllerTester().zoneRegistry().setZones(ZoneApiMock.fromId("prod.cd-us-central-1"));
tester.configServer().bootstrap(List.of(ZoneId.from("prod.cd-us-central-1")), SystemApplication.all());
tester.controllerTester().upgradeSystem(six);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.majorVersion(6)
.region("cd-us-central-1")
.build();
var context = tester.newDeploymentContext();
ZoneId zone = ZoneId.from("prod", "cd-us-central-1");
DeployOptions options = new DeployOptions(true, Optional.empty(), false,
false);
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), options);
assertTrue("Application deployed and activated",
tester.configServer().application(context.instanceId(), zone).get().activated());
assertTrue("No job status added",
context.instanceJobs().isEmpty());
Version seven = Version.fromString("7.2");
tester.controllerTester().upgradeSystem(seven);
tester.upgrader().maintain();
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), options);
assertEquals(six, context.instance().deployments().get(zone).version());
}
@Test
@Test
public void testSuspension() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
context.submit(applicationPackage).deploy();
DeploymentId deployment1 = context.deploymentIdIn(ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
DeploymentId deployment2 = context.deploymentIdIn(ZoneId.from(Environment.prod, RegionName.from("us-east-3")));
assertFalse(tester.configServer().isSuspended(deployment1));
assertFalse(tester.configServer().isSuspended(deployment2));
tester.configServer().setSuspended(deployment1, true);
assertTrue(tester.configServer().isSuspended(deployment1));
assertFalse(tester.configServer().isSuspended(deployment2));
}
@Test
public void testDeletingApplicationThatHasAlreadyBeenDeleted() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-east-3")
.region("us-west-1")
.build();
ZoneId zone = ZoneId.from("prod", "us-west-1");
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), DeployOptions.none());
tester.controller().applications().deactivate(context.instanceId(), ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
tester.controller().applications().deactivate(context.instanceId(), ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
}
@Test
public void testDeployApplicationPackageWithApplicationDir() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build(true);
tester.newDeploymentContext().submit(applicationPackage);
}
@Test
public void testDeployApplicationWithWarnings() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
ZoneId zone = ZoneId.from("prod", "us-west-1");
int warnings = 3;
tester.configServer().generateWarnings(context.deploymentIdIn(zone), warnings);
context.submit(applicationPackage).deploy();
assertEquals(warnings, context.deployment(zone)
.metrics().warnings().get(DeploymentMetrics.Warning.all).intValue());
}
@Test
public void testDeploySelectivelyProvisionsCertificate() {
Function<Instance, Optional<EndpointCertificateMetadata>> certificate = (application) -> tester.controller().curator().readEndpointCertificateMetadata(application.id());
var context1 = tester.newDeploymentContext("tenant1", "app1", "default");
var prodZone = ZoneId.from("prod", "us-west-1");
var stagingZone = ZoneId.from("staging", "us-east-3");
var testZone = ZoneId.from("test", "us-east-1");
tester.controllerTester().zoneRegistry().exclusiveRoutingIn(ZoneApiMock.from(prodZone));
var applicationPackage = new ApplicationPackageBuilder().athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.environment(prodZone.environment())
.region(prodZone.region())
.build();
context1.submit(applicationPackage).deploy();
var cert = certificate.apply(context1.instance());
assertTrue("Provisions certificate in " + Environment.prod, cert.isPresent());
assertEquals(Stream.concat(Stream.of("vznqtz7a5ygwjkbhhj7ymxvlrekgt4l6g.vespa.oath.cloud",
"app1.tenant1.global.vespa.oath.cloud",
"*.app1.tenant1.global.vespa.oath.cloud"),
Stream.of(prodZone, testZone, stagingZone)
.flatMap(zone -> Stream.of("", "*.")
.map(prefix -> prefix + "app1.tenant1." + zone.region().value() +
(zone.environment() == Environment.prod ? "" : "." + zone.environment().value()) +
".vespa.oath.cloud")))
.collect(Collectors.toUnmodifiableList()),
tester.controllerTester().serviceRegistry().endpointCertificateMock().dnsNamesOf(context1.instanceId()));
context1.submit(applicationPackage).deploy();
assertEquals(cert, certificate.apply(context1.instance()));
var context2 = tester.newDeploymentContext("tenant1", "app2", "default");
var devZone = ZoneId.from("dev", "us-east-1");
tester.controller().applications().deploy(context2.instanceId(), devZone, Optional.of(applicationPackage), DeployOptions.none());
assertTrue("Application deployed and activated",
tester.configServer().application(context2.instanceId(), devZone).get().activated());
assertFalse("Does not provision certificate in zones with routing layer", certificate.apply(context2.instance()).isPresent());
}
@Test
public void testDeployWithCrossCloudEndpoints() {
tester.controllerTester().zoneRegistry().setZones(
ZoneApiMock.fromId("prod.us-west-1"),
ZoneApiMock.newBuilder().with(CloudName.from("aws")).withId("prod.aws-us-east-1").build()
);
var context = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder()
.region("aws-us-east-1")
.region("us-west-1")
.endpoint("default", "default")
.build();
try {
context.submit(applicationPackage);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("Endpoint 'default' in instance 'default' cannot contain regions in different clouds: [aws-us-east-1, us-west-1]", e.getMessage());
}
var applicationPackage2 = new ApplicationPackageBuilder()
.region("aws-us-east-1")
.region("us-west-1")
.endpoint("aws", "default", "aws-us-east-1")
.endpoint("foo", "default", "aws-us-east-1", "us-west-1")
.build();
try {
context.submit(applicationPackage2);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("Endpoint 'foo' in instance 'default' cannot contain regions in different clouds: [aws-us-east-1, us-west-1]", e.getMessage());
}
}
@Test
public void testDeployWithoutSourceRevision() {
var context = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.environment(Environment.prod)
.region("us-west-1")
.build();
context.submit(applicationPackage, Optional.empty())
.deploy();
assertEquals("Deployed application", 1, context.instance().deployments().size());
}
@Test
public void testDeployWithGlobalEndpointsAndMultipleRoutingMethods() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.endpoint("default", "default", zone1.region().value(), zone2.region().value())
.endpoint("east", "default", zone2.region().value())
.region(zone1.region())
.region(zone2.region())
.build();
tester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone1), RoutingMethod.shared,
RoutingMethod.sharedLayer4);
tester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone2), RoutingMethod.shared,
RoutingMethod.exclusive);
context.submit(applicationPackage).deploy();
var expectedRecords = List.of(
new Record(Record.Type.ALIAS,
RecordName.from("east.application.tenant.global.vespa.oath.cloud"),
new LatencyAliasTarget(HostName.from("lb-0--tenant:application:default--prod.us-east-3"),
"dns-zone-1", ZoneId.from("prod.us-east-3")).pack()),
new Record(Record.Type.CNAME,
RecordName.from("application--tenant.global.vespa.oath.cloud"),
RecordData.from("rotation-fqdn-01.")),
new Record(Record.Type.CNAME,
RecordName.from("application.tenant.us-east-3.vespa.oath.cloud"),
RecordData.from("lb-0--tenant:application:default--prod.us-east-3.")),
new Record(Record.Type.CNAME,
RecordName.from("east--application--tenant.global.vespa.oath.cloud"),
RecordData.from("rotation-fqdn-02.")));
assertEquals(expectedRecords, List.copyOf(tester.controllerTester().nameService().records()));
}
@Test
public void testDirectRoutingSupport() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
var applicationPackageBuilder = new ApplicationPackageBuilder()
.region(zone1.region())
.region(zone2.region());
tester.controllerTester().zoneRegistry()
.setRoutingMethod(ZoneApiMock.from(zone1), RoutingMethod.shared, RoutingMethod.sharedLayer4)
.setRoutingMethod(ZoneApiMock.from(zone2), RoutingMethod.shared, RoutingMethod.sharedLayer4);
Supplier<Set<RoutingMethod>> routingMethods = () -> tester.controller().routing().endpointsOf(context.deploymentIdIn(zone1))
.asList()
.stream()
.map(Endpoint::routingMethod)
.collect(Collectors.toSet());
((InMemoryFlagSource) tester.controller().flagSource()).withBooleanFlag(Flags.ALLOW_DIRECT_ROUTING.id(), false);
context.submit(applicationPackageBuilder.build()).deploy();
assertEquals(Set.of(RoutingMethod.shared), routingMethods.get());
context.submit(applicationPackageBuilder.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION).build())
.deploy();
assertEquals(Set.of(RoutingMethod.shared), routingMethods.get());
applicationPackageBuilder = applicationPackageBuilder.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"));
context.submit(applicationPackageBuilder.build()).deploy();
assertEquals(Set.of(RoutingMethod.shared), routingMethods.get());
((InMemoryFlagSource) tester.controller().flagSource()).withBooleanFlag(Flags.ALLOW_DIRECT_ROUTING.id(), true);
context.submit(applicationPackageBuilder.build()).deploy();
assertEquals(Set.of(RoutingMethod.shared, RoutingMethod.sharedLayer4), routingMethods.get());
applicationPackageBuilder = applicationPackageBuilder.endpoint("default", "default");
context.submit(applicationPackageBuilder.build()).deploy();
for (var zone : List.of(zone1, zone2)) {
assertEquals(Set.of("rotation-id-01",
"application.tenant.global.vespa.oath.cloud",
"application--tenant.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone)));
}
}
@Test
public void testChangeEndpointCluster() {
var context = tester.newDeploymentContext();
var west = ZoneId.from("prod", "us-west-1");
var east = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region(west.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage).deploy();
assertEquals(ClusterSpec.Id.from("foo"), tester.applications().requireInstance(context.instanceId())
.rotations().get(0).clusterId());
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "bar")
.region(west.region().value())
.region(east.region().value())
.build();
try {
context.submit(applicationPackage).deploy();
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant.application' has endpoints [endpoint " +
"'default' (cluster foo) -> us-east-3, us-west-1], but does not include all of these in " +
"deployment.xml. Deploying given deployment.xml will remove " +
"[endpoint 'default' (cluster foo) -> us-east-3, us-west-1] and add " +
"[endpoint 'default' (cluster bar) -> us-east-3, us-west-1]. To allow this add " +
"<allow until='yyyy-mm-dd'>global-endpoint-change</allow> to validation-overrides.xml, see " +
"https:
}
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "bar")
.region(west.region().value())
.region(east.region().value())
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage).deploy();
assertEquals(ClusterSpec.Id.from("bar"), tester.applications().requireInstance(context.instanceId())
.rotations().get(0).clusterId());
}
@Test
public void testReadableApplications() {
var db = new MockCuratorDb();
var tester = new DeploymentTester(new ControllerTester(db));
var app1 = tester.newDeploymentContext("t1", "a1", "default")
.submit()
.deploy();
var app2 = tester.newDeploymentContext("t2", "a2", "default")
.submit()
.deploy();
assertEquals(2, tester.applications().readable().size());
db.curator().set(Path.fromString("/controller/v1/applications/" + app2.application().id().serialized()),
new byte[]{(byte) 0xDE, (byte) 0xAD});
assertEquals(1, tester.applications().readable().size());
try {
tester.applications().asList();
fail("Expected exception");
} catch (Exception ignored) {
}
app1.submit().deploy();
}
} | class ControllerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
public void testDeployment() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
Version version1 = tester.configServer().initialVersion();
var context = tester.newDeploymentContext();
context.submit(applicationPackage);
assertEquals("Application version is known from completion of initial job",
ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1, "a@b", new Version("6.1"), Instant.ofEpochSecond(1)),
context.instance().change().application().get());
context.runJob(systemTest);
context.runJob(stagingTest);
ApplicationVersion applicationVersion = context.instance().change().application().get();
assertFalse("Application version has been set during deployment", applicationVersion.isUnknown());
tester.triggerJobs();
tester.clock().advance(Duration.ofSeconds(1));
context.timeOutUpgrade(productionUsWest1);
assertEquals(4, context.instanceJobs().size());
tester.triggerJobs();
tester.controllerTester().createNewController();
assertNotNull(tester.controller().tenants().get(TenantName.from("tenant1")));
assertNotNull(tester.controller().applications().requireInstance(context.instanceId()));
context.submit(applicationPackage);
context.runJob(systemTest);
context.runJob(stagingTest);
context.jobAborted(productionUsWest1);
context.runJob(productionUsWest1);
tester.triggerJobs();
context.runJob(productionUsEast3);
assertEquals(4, context.instanceJobs().size());
applicationPackage = new ApplicationPackageBuilder()
.instances("hellO")
.build();
try {
context.submit(applicationPackage);
fail("Expected exception due to illegal deployment spec.");
}
catch (IllegalArgumentException e) {
assertEquals("Invalid id 'hellO'. Tenant, application and instance names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.", e.getMessage());
}
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("deep-space-9")
.build();
try {
context.submit(applicationPackage);
fail("Expected exception due to illegal deployment spec.");
}
catch (IllegalArgumentException e) {
assertEquals("Zone prod.deep-space-9 in deployment spec was not found in this system!", e.getMessage());
}
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-east-3")
.build();
try {
assertTrue(context.instance().deployments().containsKey(ZoneId.from("prod", "us-west-1")));
context.submit(applicationPackage);
fail("Expected exception due to illegal production deployment removal");
}
catch (IllegalArgumentException e) {
assertEquals("deployment-removal: application 'tenant.application' is deployed in us-west-1, but does not include this zone in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval),
e.getMessage());
}
assertNotNull("Zone was not removed",
context.instance().deployments().get(productionUsWest1.zone(main)));
applicationPackage = new ApplicationPackageBuilder()
.allow(ValidationId.deploymentRemoval)
.upgradePolicy("default")
.environment(Environment.prod)
.region("us-east-3")
.build();
context.submit(applicationPackage);
assertNull("Zone was removed",
context.instance().deployments().get(productionUsWest1.zone(main)));
assertNull("Deployment job was removed", context.instanceJobs().get(productionUsWest1));
}
@Test
public void testGlobalRotations() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.region(zone1.region())
.region(zone2.region())
.endpoint("default", "default", zone1.region().value(), zone2.region().value())
.build();
context.submit(applicationPackage).deploy();
var deployment1 = context.deploymentIdIn(zone1);
var status1 = tester.controller().routing().globalRotationStatus(deployment1);
assertEquals(1, status1.size());
assertTrue("All upstreams are in", status1.values().stream().allMatch(es -> es.getStatus() == EndpointStatus.Status.in));
var newStatus = new EndpointStatus(EndpointStatus.Status.out, "unit-test", ControllerTest.class.getSimpleName(), tester.clock().instant().getEpochSecond());
tester.controller().routing().setGlobalRotationStatus(deployment1, newStatus);
status1 = tester.controller().routing().globalRotationStatus(deployment1);
assertEquals(1, status1.size());
assertTrue("All upstreams are out", status1.values().stream().allMatch(es -> es.getStatus() == EndpointStatus.Status.out));
assertTrue("Reason is set", status1.values().stream().allMatch(es -> es.getReason().equals("unit-test")));
var status2 = tester.controller().routing().globalRotationStatus(context.deploymentIdIn(zone2));
assertEquals(1, status2.size());
assertTrue("All upstreams are in", status2.values().stream().allMatch(es -> es.getStatus() == EndpointStatus.Status.in));
}
@Test
public void testDnsAliasRegistration() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
for (Deployment deployment : deployments) {
assertEquals("Rotation names are passed to config server in " + deployment.zone(),
Set.of("rotation-id-01",
"app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(deployment.zone())));
}
context.flushDnsUpdates();
assertEquals(1, tester.controllerTester().nameService().records().size());
var record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
}
@Test
public void testDnsAliasRegistrationLegacy() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
for (Deployment deployment : deployments) {
assertEquals("Rotation names are passed to config server in " + deployment.zone(),
Set.of("rotation-id-01",
"app1--tenant1.global.vespa.oath.cloud",
"app1.tenant1.global.vespa.yahooapis.com",
"app1--tenant1.global.vespa.yahooapis.com"),
tester.configServer().rotationNames().get(context.deploymentIdIn(deployment.zone())));
}
context.flushDnsUpdates();
assertEquals(3, tester.controllerTester().nameService().records().size());
Optional<Record> record = tester.controllerTester().findCname("app1--tenant1.global.vespa.yahooapis.com");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.yahooapis.com", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
record = tester.controllerTester().findCname("app1.tenant1.global.vespa.yahooapis.com");
assertTrue(record.isPresent());
assertEquals("app1.tenant1.global.vespa.yahooapis.com", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
}
@Test
public void testDnsAliasRegistrationWithEndpoints() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("foobar", "qrs", "us-west-1", "us-central-1")
.endpoint("default", "qrs", "us-west-1", "us-central-1")
.endpoint("all", "qrs")
.endpoint("west", "qrs", "us-west-1")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
var notWest = Set.of(
"rotation-id-01", "foobar--app1--tenant1.global.vespa.oath.cloud",
"rotation-id-02", "app1--tenant1.global.vespa.oath.cloud",
"rotation-id-03", "all--app1--tenant1.global.vespa.oath.cloud"
);
var west = Sets.union(notWest, Set.of("rotation-id-04", "west--app1--tenant1.global.vespa.oath.cloud"));
for (Deployment deployment : deployments) {
assertEquals("Rotation names are passed to config server in " + deployment.zone(),
ZoneId.from("prod.us-west-1").equals(deployment.zone()) ? west : notWest,
tester.configServer().rotationNames().get(context.deploymentIdIn(deployment.zone())));
}
context.flushDnsUpdates();
assertEquals(4, tester.controllerTester().nameService().records().size());
var record1 = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record1.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record1.get().name().asString());
assertEquals("rotation-fqdn-02.", record1.get().data().asString());
var record2 = tester.controllerTester().findCname("foobar--app1--tenant1.global.vespa.oath.cloud");
assertTrue(record2.isPresent());
assertEquals("foobar--app1--tenant1.global.vespa.oath.cloud", record2.get().name().asString());
assertEquals("rotation-fqdn-01.", record2.get().data().asString());
var record3 = tester.controllerTester().findCname("all--app1--tenant1.global.vespa.oath.cloud");
assertTrue(record3.isPresent());
assertEquals("all--app1--tenant1.global.vespa.oath.cloud", record3.get().name().asString());
assertEquals("rotation-fqdn-03.", record3.get().data().asString());
var record4 = tester.controllerTester().findCname("west--app1--tenant1.global.vespa.oath.cloud");
assertTrue(record4.isPresent());
assertEquals("west--app1--tenant1.global.vespa.oath.cloud", record4.get().name().asString());
assertEquals("rotation-fqdn-04.", record4.get().data().asString());
}
@Test
public void testDnsAliasRegistrationWithChangingEndpoints() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
var west = ZoneId.from("prod", "us-west-1");
var central = ZoneId.from("prod", "us-central-1");
var east = ZoneId.from("prod", "us-east-3");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage).deploy();
for (var zone : List.of(west, central)) {
assertEquals(
"Zone " + zone + " is a member of global endpoint",
Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone))
);
}
ApplicationPackage applicationPackage2 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value())
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage2).deploy();
for (var zone : List.of(west, central)) {
assertEquals(
"Zone " + zone + " is a member of global endpoint",
Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone))
);
}
assertEquals(
"Zone " + east + " is a member of global endpoint",
Set.of("rotation-id-02", "east--app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(east))
);
ApplicationPackage applicationPackage3 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value(), east.region().value())
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage3).deploy();
for (var zone : List.of(west, central, east)) {
assertEquals(
"Zone " + zone + " is a member of global endpoint",
zone.equals(east)
? Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud",
"rotation-id-02", "east--app1--tenant1.global.vespa.oath.cloud")
: Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone))
);
}
ApplicationPackage applicationPackage4 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value())
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
try {
context.submit(applicationPackage4);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant1.app1' has endpoints " +
"[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
"but does not include all of these in deployment.xml. Deploying given deployment.xml " +
"will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1] " +
"and add [endpoint 'default' (cluster qrs) -> us-central-1, us-west-1]. " +
ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
}
ApplicationPackage applicationPackage5 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
try {
context.submit(applicationPackage5);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant1.app1' has endpoints " +
"[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
"but does not include all of these in deployment.xml. Deploying given deployment.xml " +
"will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1]. " +
ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
}
ApplicationPackage applicationPackage6 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage6);
}
@Test
public void testUnassignRotations() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", "us-west-1", "us-central-1")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
ApplicationPackage applicationPackage2 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-central-1")
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage2).deploy();
assertEquals(List.of(), context.instance().rotations());
assertEquals(
Set.of(),
tester.configServer().rotationNames().get(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")))
);
}
@Test
public void testUpdatesExistingDnsAlias() {
{
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
assertEquals(1, tester.controllerTester().nameService().records().size());
Optional<Record> record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.allow(ValidationId.deploymentRemoval)
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage);
tester.applications().deleteApplication(context.application().id(),
tester.controllerTester().credentialsFor(context.application().id().tenant()));
try (RotationLock lock = tester.controller().routing().rotations().lock()) {
assertTrue("Rotation is unassigned",
tester.controller().routing().rotations().availableRotations(lock)
.containsKey(new RotationId("rotation-id-01")));
}
context.flushDnsUpdates();
record = tester.controllerTester().findCname("app1--tenant1.global.vespa.yahooapis.com");
assertTrue(record.isEmpty());
record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isEmpty());
record = tester.controllerTester().findCname("app1.tenant1.global.vespa.yahooapis.com");
assertTrue(record.isEmpty());
}
{
var context = tester.newDeploymentContext("tenant2", "app2", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
assertEquals(1, tester.controllerTester().nameService().records().size());
var record = tester.controllerTester().findCname("app2--tenant2.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app2--tenant2.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
}
{
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
assertEquals("rotation-id-02", context.instance().rotations().get(0).rotationId().asString());
assertEquals(2, tester.controllerTester().nameService().records().size());
var record1 = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record1.isPresent());
assertEquals("rotation-fqdn-02.", record1.get().data().asString());
var record2 = tester.controllerTester().findCname("app2--tenant2.global.vespa.oath.cloud");
assertTrue(record2.isPresent());
assertEquals("rotation-fqdn-01.", record2.get().data().asString());
}
}
@Test
public void testIntegrationTestDeployment() {
Version six = Version.fromString("6.1");
tester.controllerTester().zoneRegistry().setSystemName(SystemName.cd);
tester.controllerTester().zoneRegistry().setZones(ZoneApiMock.fromId("prod.cd-us-central-1"));
tester.configServer().bootstrap(List.of(ZoneId.from("prod.cd-us-central-1")), SystemApplication.all());
tester.controllerTester().upgradeSystem(six);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.majorVersion(6)
.region("cd-us-central-1")
.build();
var context = tester.newDeploymentContext();
ZoneId zone = ZoneId.from("prod", "cd-us-central-1");
DeployOptions options = new DeployOptions(true, Optional.empty(), false,
false);
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), options);
assertTrue("Application deployed and activated",
tester.configServer().application(context.instanceId(), zone).get().activated());
assertTrue("No job status added",
context.instanceJobs().isEmpty());
Version seven = Version.fromString("7.2");
tester.controllerTester().upgradeSystem(seven);
tester.upgrader().maintain();
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), options);
assertEquals(six, context.instance().deployments().get(zone).version());
}
@Test
@Test
public void testSuspension() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
context.submit(applicationPackage).deploy();
DeploymentId deployment1 = context.deploymentIdIn(ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
DeploymentId deployment2 = context.deploymentIdIn(ZoneId.from(Environment.prod, RegionName.from("us-east-3")));
assertFalse(tester.configServer().isSuspended(deployment1));
assertFalse(tester.configServer().isSuspended(deployment2));
tester.configServer().setSuspended(deployment1, true);
assertTrue(tester.configServer().isSuspended(deployment1));
assertFalse(tester.configServer().isSuspended(deployment2));
}
@Test
public void testDeletingApplicationThatHasAlreadyBeenDeleted() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-east-3")
.region("us-west-1")
.build();
ZoneId zone = ZoneId.from("prod", "us-west-1");
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), DeployOptions.none());
tester.controller().applications().deactivate(context.instanceId(), ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
tester.controller().applications().deactivate(context.instanceId(), ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
}
@Test
public void testDeployApplicationPackageWithApplicationDir() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build(true);
tester.newDeploymentContext().submit(applicationPackage);
}
@Test
public void testDeployApplicationWithWarnings() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
ZoneId zone = ZoneId.from("prod", "us-west-1");
int warnings = 3;
tester.configServer().generateWarnings(context.deploymentIdIn(zone), warnings);
context.submit(applicationPackage).deploy();
assertEquals(warnings, context.deployment(zone)
.metrics().warnings().get(DeploymentMetrics.Warning.all).intValue());
}
@Test
public void testDeploySelectivelyProvisionsCertificate() {
Function<Instance, Optional<EndpointCertificateMetadata>> certificate = (application) -> tester.controller().curator().readEndpointCertificateMetadata(application.id());
var context1 = tester.newDeploymentContext("tenant1", "app1", "default");
var prodZone = ZoneId.from("prod", "us-west-1");
var stagingZone = ZoneId.from("staging", "us-east-3");
var testZone = ZoneId.from("test", "us-east-1");
tester.controllerTester().zoneRegistry().exclusiveRoutingIn(ZoneApiMock.from(prodZone));
var applicationPackage = new ApplicationPackageBuilder().athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.environment(prodZone.environment())
.region(prodZone.region())
.build();
context1.submit(applicationPackage).deploy();
var cert = certificate.apply(context1.instance());
assertTrue("Provisions certificate in " + Environment.prod, cert.isPresent());
assertEquals(Stream.concat(Stream.of("vznqtz7a5ygwjkbhhj7ymxvlrekgt4l6g.vespa.oath.cloud",
"app1.tenant1.global.vespa.oath.cloud",
"*.app1.tenant1.global.vespa.oath.cloud"),
Stream.of(prodZone, testZone, stagingZone)
.flatMap(zone -> Stream.of("", "*.")
.map(prefix -> prefix + "app1.tenant1." + zone.region().value() +
(zone.environment() == Environment.prod ? "" : "." + zone.environment().value()) +
".vespa.oath.cloud")))
.collect(Collectors.toUnmodifiableList()),
tester.controllerTester().serviceRegistry().endpointCertificateMock().dnsNamesOf(context1.instanceId()));
context1.submit(applicationPackage).deploy();
assertEquals(cert, certificate.apply(context1.instance()));
var context2 = tester.newDeploymentContext("tenant1", "app2", "default");
var devZone = ZoneId.from("dev", "us-east-1");
tester.controller().applications().deploy(context2.instanceId(), devZone, Optional.of(applicationPackage), DeployOptions.none());
assertTrue("Application deployed and activated",
tester.configServer().application(context2.instanceId(), devZone).get().activated());
assertFalse("Does not provision certificate in zones with routing layer", certificate.apply(context2.instance()).isPresent());
}
@Test
public void testDeployWithCrossCloudEndpoints() {
tester.controllerTester().zoneRegistry().setZones(
ZoneApiMock.fromId("prod.us-west-1"),
ZoneApiMock.newBuilder().with(CloudName.from("aws")).withId("prod.aws-us-east-1").build()
);
var context = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder()
.region("aws-us-east-1")
.region("us-west-1")
.endpoint("default", "default")
.build();
try {
context.submit(applicationPackage);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("Endpoint 'default' in instance 'default' cannot contain regions in different clouds: [aws-us-east-1, us-west-1]", e.getMessage());
}
var applicationPackage2 = new ApplicationPackageBuilder()
.region("aws-us-east-1")
.region("us-west-1")
.endpoint("aws", "default", "aws-us-east-1")
.endpoint("foo", "default", "aws-us-east-1", "us-west-1")
.build();
try {
context.submit(applicationPackage2);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("Endpoint 'foo' in instance 'default' cannot contain regions in different clouds: [aws-us-east-1, us-west-1]", e.getMessage());
}
}
@Test
public void testDeployWithoutSourceRevision() {
var context = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.environment(Environment.prod)
.region("us-west-1")
.build();
context.submit(applicationPackage, Optional.empty())
.deploy();
assertEquals("Deployed application", 1, context.instance().deployments().size());
}
@Test
public void testDeployWithGlobalEndpointsAndMultipleRoutingMethods() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.endpoint("default", "default", zone1.region().value(), zone2.region().value())
.endpoint("east", "default", zone2.region().value())
.region(zone1.region())
.region(zone2.region())
.build();
tester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone1), RoutingMethod.shared,
RoutingMethod.sharedLayer4);
tester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone2), RoutingMethod.shared,
RoutingMethod.exclusive);
context.submit(applicationPackage).deploy();
var expectedRecords = List.of(
new Record(Record.Type.ALIAS,
RecordName.from("east.application.tenant.global.vespa.oath.cloud"),
new LatencyAliasTarget(HostName.from("lb-0--tenant:application:default--prod.us-east-3"),
"dns-zone-1", ZoneId.from("prod.us-east-3")).pack()),
new Record(Record.Type.CNAME,
RecordName.from("application--tenant.global.vespa.oath.cloud"),
RecordData.from("rotation-fqdn-01.")),
new Record(Record.Type.CNAME,
RecordName.from("application.tenant.us-east-3.vespa.oath.cloud"),
RecordData.from("lb-0--tenant:application:default--prod.us-east-3.")),
new Record(Record.Type.CNAME,
RecordName.from("east--application--tenant.global.vespa.oath.cloud"),
RecordData.from("rotation-fqdn-02.")));
assertEquals(expectedRecords, List.copyOf(tester.controllerTester().nameService().records()));
}
@Test
public void testDirectRoutingSupport() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
var applicationPackageBuilder = new ApplicationPackageBuilder()
.region(zone1.region())
.region(zone2.region());
tester.controllerTester().zoneRegistry()
.setRoutingMethod(ZoneApiMock.from(zone1), RoutingMethod.shared, RoutingMethod.sharedLayer4)
.setRoutingMethod(ZoneApiMock.from(zone2), RoutingMethod.shared, RoutingMethod.sharedLayer4);
Supplier<Set<RoutingMethod>> routingMethods = () -> tester.controller().routing().endpointsOf(context.deploymentIdIn(zone1))
.asList()
.stream()
.map(Endpoint::routingMethod)
.collect(Collectors.toSet());
((InMemoryFlagSource) tester.controller().flagSource()).withBooleanFlag(Flags.ALLOW_DIRECT_ROUTING.id(), false);
context.submit(applicationPackageBuilder.build()).deploy();
assertEquals(Set.of(RoutingMethod.shared), routingMethods.get());
context.submit(applicationPackageBuilder.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION).build())
.deploy();
assertEquals(Set.of(RoutingMethod.shared), routingMethods.get());
applicationPackageBuilder = applicationPackageBuilder.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"));
context.submit(applicationPackageBuilder.build()).deploy();
assertEquals(Set.of(RoutingMethod.shared), routingMethods.get());
((InMemoryFlagSource) tester.controller().flagSource()).withBooleanFlag(Flags.ALLOW_DIRECT_ROUTING.id(), true);
context.submit(applicationPackageBuilder.build()).deploy();
assertEquals(Set.of(RoutingMethod.shared, RoutingMethod.sharedLayer4), routingMethods.get());
applicationPackageBuilder = applicationPackageBuilder.endpoint("default", "default");
context.submit(applicationPackageBuilder.build()).deploy();
for (var zone : List.of(zone1, zone2)) {
assertEquals(Set.of("rotation-id-01",
"application.tenant.global.vespa.oath.cloud",
"application--tenant.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone)));
}
}
@Test
public void testChangeEndpointCluster() {
var context = tester.newDeploymentContext();
var west = ZoneId.from("prod", "us-west-1");
var east = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region(west.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage).deploy();
assertEquals(ClusterSpec.Id.from("foo"), tester.applications().requireInstance(context.instanceId())
.rotations().get(0).clusterId());
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "bar")
.region(west.region().value())
.region(east.region().value())
.build();
try {
context.submit(applicationPackage).deploy();
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant.application' has endpoints [endpoint " +
"'default' (cluster foo) -> us-east-3, us-west-1], but does not include all of these in " +
"deployment.xml. Deploying given deployment.xml will remove " +
"[endpoint 'default' (cluster foo) -> us-east-3, us-west-1] and add " +
"[endpoint 'default' (cluster bar) -> us-east-3, us-west-1]. To allow this add " +
"<allow until='yyyy-mm-dd'>global-endpoint-change</allow> to validation-overrides.xml, see " +
"https:
}
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "bar")
.region(west.region().value())
.region(east.region().value())
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage).deploy();
assertEquals(ClusterSpec.Id.from("bar"), tester.applications().requireInstance(context.instanceId())
.rotations().get(0).clusterId());
}
@Test
public void testReadableApplications() {
var db = new MockCuratorDb();
var tester = new DeploymentTester(new ControllerTester(db));
var app1 = tester.newDeploymentContext("t1", "a1", "default")
.submit()
.deploy();
var app2 = tester.newDeploymentContext("t2", "a2", "default")
.submit()
.deploy();
assertEquals(2, tester.applications().readable().size());
db.curator().set(Path.fromString("/controller/v1/applications/" + app2.application().id().serialized()),
new byte[]{(byte) 0xDE, (byte) 0xAD});
assertEquals(1, tester.applications().readable().size());
try {
tester.applications().asList();
fail("Expected exception");
} catch (Exception ignored) {
}
app1.submit().deploy();
}
} | |
Isn't this equivalent to `assertEquals(Set.of(RoutingMethod.shared, RoutingMethod.sharedLayer4), routingMethods)`? | public void testDevDeployment() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.dev)
.majorVersion(6)
.region("us-east-1")
.build();
var context = tester.newDeploymentContext();
ZoneId zone = ZoneId.from("dev", "us-east-1");
tester.controllerTester().zoneRegistry()
.setRoutingMethod(ZoneApiMock.from(zone), RoutingMethod.shared, RoutingMethod.sharedLayer4);
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), DeployOptions.none());
assertTrue("Application deployed and activated",
tester.configServer().application(context.instanceId(), zone).get().activated());
assertTrue("No job status added",
context.instanceJobs().isEmpty());
assertEquals("DeploymentSpec is not persisted", DeploymentSpec.empty, context.application().deploymentSpec());
Set<RoutingMethod> routingMethods = tester.controller().routing().endpointsOf(context.deploymentIdIn(zone))
.asList()
.stream()
.map(Endpoint::routingMethod)
.collect(Collectors.toSet());
assertThat(routingMethods, IsIterableContainingInAnyOrder.containsInAnyOrder(RoutingMethod.shared, RoutingMethod.sharedLayer4));
} | assertThat(routingMethods, IsIterableContainingInAnyOrder.containsInAnyOrder(RoutingMethod.shared, RoutingMethod.sharedLayer4)); | public void testDevDeployment() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.dev)
.majorVersion(6)
.region("us-east-1")
.build();
var context = tester.newDeploymentContext();
ZoneId zone = ZoneId.from("dev", "us-east-1");
tester.controllerTester().zoneRegistry()
.setRoutingMethod(ZoneApiMock.from(zone), RoutingMethod.shared, RoutingMethod.sharedLayer4);
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), DeployOptions.none());
assertTrue("Application deployed and activated",
tester.configServer().application(context.instanceId(), zone).get().activated());
assertTrue("No job status added",
context.instanceJobs().isEmpty());
assertEquals("DeploymentSpec is not persisted", DeploymentSpec.empty, context.application().deploymentSpec());
Set<RoutingMethod> routingMethods = tester.controller().routing().endpointsOf(context.deploymentIdIn(zone))
.asList()
.stream()
.map(Endpoint::routingMethod)
.collect(Collectors.toSet());
assertEquals(routingMethods, Set.of(RoutingMethod.shared, RoutingMethod.sharedLayer4));
} | class ControllerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
public void testDeployment() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
Version version1 = tester.configServer().initialVersion();
var context = tester.newDeploymentContext();
context.submit(applicationPackage);
assertEquals("Application version is known from completion of initial job",
ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1, "a@b", new Version("6.1"), Instant.ofEpochSecond(1)),
context.instance().change().application().get());
context.runJob(systemTest);
context.runJob(stagingTest);
ApplicationVersion applicationVersion = context.instance().change().application().get();
assertFalse("Application version has been set during deployment", applicationVersion.isUnknown());
tester.triggerJobs();
tester.clock().advance(Duration.ofSeconds(1));
context.timeOutUpgrade(productionUsWest1);
assertEquals(4, context.instanceJobs().size());
tester.triggerJobs();
tester.controllerTester().createNewController();
assertNotNull(tester.controller().tenants().get(TenantName.from("tenant1")));
assertNotNull(tester.controller().applications().requireInstance(context.instanceId()));
context.submit(applicationPackage);
context.runJob(systemTest);
context.runJob(stagingTest);
context.jobAborted(productionUsWest1);
context.runJob(productionUsWest1);
tester.triggerJobs();
context.runJob(productionUsEast3);
assertEquals(4, context.instanceJobs().size());
applicationPackage = new ApplicationPackageBuilder()
.instances("hellO")
.build();
try {
context.submit(applicationPackage);
fail("Expected exception due to illegal deployment spec.");
}
catch (IllegalArgumentException e) {
assertEquals("Invalid id 'hellO'. Tenant, application and instance names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.", e.getMessage());
}
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("deep-space-9")
.build();
try {
context.submit(applicationPackage);
fail("Expected exception due to illegal deployment spec.");
}
catch (IllegalArgumentException e) {
assertEquals("Zone prod.deep-space-9 in deployment spec was not found in this system!", e.getMessage());
}
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-east-3")
.build();
try {
assertTrue(context.instance().deployments().containsKey(ZoneId.from("prod", "us-west-1")));
context.submit(applicationPackage);
fail("Expected exception due to illegal production deployment removal");
}
catch (IllegalArgumentException e) {
assertEquals("deployment-removal: application 'tenant.application' is deployed in us-west-1, but does not include this zone in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval),
e.getMessage());
}
assertNotNull("Zone was not removed",
context.instance().deployments().get(productionUsWest1.zone(main)));
applicationPackage = new ApplicationPackageBuilder()
.allow(ValidationId.deploymentRemoval)
.upgradePolicy("default")
.environment(Environment.prod)
.region("us-east-3")
.build();
context.submit(applicationPackage);
assertNull("Zone was removed",
context.instance().deployments().get(productionUsWest1.zone(main)));
assertNull("Deployment job was removed", context.instanceJobs().get(productionUsWest1));
}
@Test
public void testGlobalRotations() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.region(zone1.region())
.region(zone2.region())
.endpoint("default", "default", zone1.region().value(), zone2.region().value())
.build();
context.submit(applicationPackage).deploy();
var deployment1 = context.deploymentIdIn(zone1);
var status1 = tester.controller().routing().globalRotationStatus(deployment1);
assertEquals(1, status1.size());
assertTrue("All upstreams are in", status1.values().stream().allMatch(es -> es.getStatus() == EndpointStatus.Status.in));
var newStatus = new EndpointStatus(EndpointStatus.Status.out, "unit-test", ControllerTest.class.getSimpleName(), tester.clock().instant().getEpochSecond());
tester.controller().routing().setGlobalRotationStatus(deployment1, newStatus);
status1 = tester.controller().routing().globalRotationStatus(deployment1);
assertEquals(1, status1.size());
assertTrue("All upstreams are out", status1.values().stream().allMatch(es -> es.getStatus() == EndpointStatus.Status.out));
assertTrue("Reason is set", status1.values().stream().allMatch(es -> es.getReason().equals("unit-test")));
var status2 = tester.controller().routing().globalRotationStatus(context.deploymentIdIn(zone2));
assertEquals(1, status2.size());
assertTrue("All upstreams are in", status2.values().stream().allMatch(es -> es.getStatus() == EndpointStatus.Status.in));
}
@Test
public void testDnsAliasRegistration() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
for (Deployment deployment : deployments) {
assertEquals("Rotation names are passed to config server in " + deployment.zone(),
Set.of("rotation-id-01",
"app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(deployment.zone())));
}
context.flushDnsUpdates();
assertEquals(1, tester.controllerTester().nameService().records().size());
var record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
}
@Test
public void testDnsAliasRegistrationLegacy() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
for (Deployment deployment : deployments) {
assertEquals("Rotation names are passed to config server in " + deployment.zone(),
Set.of("rotation-id-01",
"app1--tenant1.global.vespa.oath.cloud",
"app1.tenant1.global.vespa.yahooapis.com",
"app1--tenant1.global.vespa.yahooapis.com"),
tester.configServer().rotationNames().get(context.deploymentIdIn(deployment.zone())));
}
context.flushDnsUpdates();
assertEquals(3, tester.controllerTester().nameService().records().size());
Optional<Record> record = tester.controllerTester().findCname("app1--tenant1.global.vespa.yahooapis.com");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.yahooapis.com", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
record = tester.controllerTester().findCname("app1.tenant1.global.vespa.yahooapis.com");
assertTrue(record.isPresent());
assertEquals("app1.tenant1.global.vespa.yahooapis.com", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
}
@Test
public void testDnsAliasRegistrationWithEndpoints() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("foobar", "qrs", "us-west-1", "us-central-1")
.endpoint("default", "qrs", "us-west-1", "us-central-1")
.endpoint("all", "qrs")
.endpoint("west", "qrs", "us-west-1")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
var notWest = Set.of(
"rotation-id-01", "foobar--app1--tenant1.global.vespa.oath.cloud",
"rotation-id-02", "app1--tenant1.global.vespa.oath.cloud",
"rotation-id-03", "all--app1--tenant1.global.vespa.oath.cloud"
);
var west = Sets.union(notWest, Set.of("rotation-id-04", "west--app1--tenant1.global.vespa.oath.cloud"));
for (Deployment deployment : deployments) {
assertEquals("Rotation names are passed to config server in " + deployment.zone(),
ZoneId.from("prod.us-west-1").equals(deployment.zone()) ? west : notWest,
tester.configServer().rotationNames().get(context.deploymentIdIn(deployment.zone())));
}
context.flushDnsUpdates();
assertEquals(4, tester.controllerTester().nameService().records().size());
var record1 = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record1.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record1.get().name().asString());
assertEquals("rotation-fqdn-02.", record1.get().data().asString());
var record2 = tester.controllerTester().findCname("foobar--app1--tenant1.global.vespa.oath.cloud");
assertTrue(record2.isPresent());
assertEquals("foobar--app1--tenant1.global.vespa.oath.cloud", record2.get().name().asString());
assertEquals("rotation-fqdn-01.", record2.get().data().asString());
var record3 = tester.controllerTester().findCname("all--app1--tenant1.global.vespa.oath.cloud");
assertTrue(record3.isPresent());
assertEquals("all--app1--tenant1.global.vespa.oath.cloud", record3.get().name().asString());
assertEquals("rotation-fqdn-03.", record3.get().data().asString());
var record4 = tester.controllerTester().findCname("west--app1--tenant1.global.vespa.oath.cloud");
assertTrue(record4.isPresent());
assertEquals("west--app1--tenant1.global.vespa.oath.cloud", record4.get().name().asString());
assertEquals("rotation-fqdn-04.", record4.get().data().asString());
}
@Test
public void testDnsAliasRegistrationWithChangingEndpoints() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
var west = ZoneId.from("prod", "us-west-1");
var central = ZoneId.from("prod", "us-central-1");
var east = ZoneId.from("prod", "us-east-3");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage).deploy();
for (var zone : List.of(west, central)) {
assertEquals(
"Zone " + zone + " is a member of global endpoint",
Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone))
);
}
ApplicationPackage applicationPackage2 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value())
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage2).deploy();
for (var zone : List.of(west, central)) {
assertEquals(
"Zone " + zone + " is a member of global endpoint",
Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone))
);
}
assertEquals(
"Zone " + east + " is a member of global endpoint",
Set.of("rotation-id-02", "east--app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(east))
);
ApplicationPackage applicationPackage3 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value(), east.region().value())
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage3).deploy();
for (var zone : List.of(west, central, east)) {
assertEquals(
"Zone " + zone + " is a member of global endpoint",
zone.equals(east)
? Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud",
"rotation-id-02", "east--app1--tenant1.global.vespa.oath.cloud")
: Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone))
);
}
ApplicationPackage applicationPackage4 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value())
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
try {
context.submit(applicationPackage4);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant1.app1' has endpoints " +
"[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
"but does not include all of these in deployment.xml. Deploying given deployment.xml " +
"will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1] " +
"and add [endpoint 'default' (cluster qrs) -> us-central-1, us-west-1]. " +
ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
}
ApplicationPackage applicationPackage5 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
try {
context.submit(applicationPackage5);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant1.app1' has endpoints " +
"[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
"but does not include all of these in deployment.xml. Deploying given deployment.xml " +
"will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1]. " +
ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
}
ApplicationPackage applicationPackage6 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage6);
}
@Test
public void testUnassignRotations() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", "us-west-1", "us-central-1")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
ApplicationPackage applicationPackage2 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-central-1")
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage2).deploy();
assertEquals(List.of(), context.instance().rotations());
assertEquals(
Set.of(),
tester.configServer().rotationNames().get(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")))
);
}
@Test
public void testUpdatesExistingDnsAlias() {
{
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
assertEquals(1, tester.controllerTester().nameService().records().size());
Optional<Record> record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.allow(ValidationId.deploymentRemoval)
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage);
tester.applications().deleteApplication(context.application().id(),
tester.controllerTester().credentialsFor(context.application().id().tenant()));
try (RotationLock lock = tester.controller().routing().rotations().lock()) {
assertTrue("Rotation is unassigned",
tester.controller().routing().rotations().availableRotations(lock)
.containsKey(new RotationId("rotation-id-01")));
}
context.flushDnsUpdates();
record = tester.controllerTester().findCname("app1--tenant1.global.vespa.yahooapis.com");
assertTrue(record.isEmpty());
record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isEmpty());
record = tester.controllerTester().findCname("app1.tenant1.global.vespa.yahooapis.com");
assertTrue(record.isEmpty());
}
{
var context = tester.newDeploymentContext("tenant2", "app2", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
assertEquals(1, tester.controllerTester().nameService().records().size());
var record = tester.controllerTester().findCname("app2--tenant2.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app2--tenant2.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
}
{
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
assertEquals("rotation-id-02", context.instance().rotations().get(0).rotationId().asString());
assertEquals(2, tester.controllerTester().nameService().records().size());
var record1 = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record1.isPresent());
assertEquals("rotation-fqdn-02.", record1.get().data().asString());
var record2 = tester.controllerTester().findCname("app2--tenant2.global.vespa.oath.cloud");
assertTrue(record2.isPresent());
assertEquals("rotation-fqdn-01.", record2.get().data().asString());
}
}
@Test
public void testIntegrationTestDeployment() {
Version six = Version.fromString("6.1");
tester.controllerTester().zoneRegistry().setSystemName(SystemName.cd);
tester.controllerTester().zoneRegistry().setZones(ZoneApiMock.fromId("prod.cd-us-central-1"));
tester.configServer().bootstrap(List.of(ZoneId.from("prod.cd-us-central-1")), SystemApplication.all());
tester.controllerTester().upgradeSystem(six);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.majorVersion(6)
.region("cd-us-central-1")
.build();
var context = tester.newDeploymentContext();
ZoneId zone = ZoneId.from("prod", "cd-us-central-1");
DeployOptions options = new DeployOptions(true, Optional.empty(), false,
false);
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), options);
assertTrue("Application deployed and activated",
tester.configServer().application(context.instanceId(), zone).get().activated());
assertTrue("No job status added",
context.instanceJobs().isEmpty());
Version seven = Version.fromString("7.2");
tester.controllerTester().upgradeSystem(seven);
tester.upgrader().maintain();
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), options);
assertEquals(six, context.instance().deployments().get(zone).version());
}
@Test
@Test
public void testSuspension() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
context.submit(applicationPackage).deploy();
DeploymentId deployment1 = context.deploymentIdIn(ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
DeploymentId deployment2 = context.deploymentIdIn(ZoneId.from(Environment.prod, RegionName.from("us-east-3")));
assertFalse(tester.configServer().isSuspended(deployment1));
assertFalse(tester.configServer().isSuspended(deployment2));
tester.configServer().setSuspended(deployment1, true);
assertTrue(tester.configServer().isSuspended(deployment1));
assertFalse(tester.configServer().isSuspended(deployment2));
}
@Test
public void testDeletingApplicationThatHasAlreadyBeenDeleted() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-east-3")
.region("us-west-1")
.build();
ZoneId zone = ZoneId.from("prod", "us-west-1");
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), DeployOptions.none());
tester.controller().applications().deactivate(context.instanceId(), ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
tester.controller().applications().deactivate(context.instanceId(), ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
}
@Test
public void testDeployApplicationPackageWithApplicationDir() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build(true);
tester.newDeploymentContext().submit(applicationPackage);
}
@Test
public void testDeployApplicationWithWarnings() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
ZoneId zone = ZoneId.from("prod", "us-west-1");
int warnings = 3;
tester.configServer().generateWarnings(context.deploymentIdIn(zone), warnings);
context.submit(applicationPackage).deploy();
assertEquals(warnings, context.deployment(zone)
.metrics().warnings().get(DeploymentMetrics.Warning.all).intValue());
}
@Test
public void testDeploySelectivelyProvisionsCertificate() {
Function<Instance, Optional<EndpointCertificateMetadata>> certificate = (application) -> tester.controller().curator().readEndpointCertificateMetadata(application.id());
var context1 = tester.newDeploymentContext("tenant1", "app1", "default");
var prodZone = ZoneId.from("prod", "us-west-1");
var stagingZone = ZoneId.from("staging", "us-east-3");
var testZone = ZoneId.from("test", "us-east-1");
tester.controllerTester().zoneRegistry().exclusiveRoutingIn(ZoneApiMock.from(prodZone));
var applicationPackage = new ApplicationPackageBuilder().athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.environment(prodZone.environment())
.region(prodZone.region())
.build();
context1.submit(applicationPackage).deploy();
var cert = certificate.apply(context1.instance());
assertTrue("Provisions certificate in " + Environment.prod, cert.isPresent());
assertEquals(Stream.concat(Stream.of("vznqtz7a5ygwjkbhhj7ymxvlrekgt4l6g.vespa.oath.cloud",
"app1.tenant1.global.vespa.oath.cloud",
"*.app1.tenant1.global.vespa.oath.cloud"),
Stream.of(prodZone, testZone, stagingZone)
.flatMap(zone -> Stream.of("", "*.")
.map(prefix -> prefix + "app1.tenant1." + zone.region().value() +
(zone.environment() == Environment.prod ? "" : "." + zone.environment().value()) +
".vespa.oath.cloud")))
.collect(Collectors.toUnmodifiableList()),
tester.controllerTester().serviceRegistry().endpointCertificateMock().dnsNamesOf(context1.instanceId()));
context1.submit(applicationPackage).deploy();
assertEquals(cert, certificate.apply(context1.instance()));
var context2 = tester.newDeploymentContext("tenant1", "app2", "default");
var devZone = ZoneId.from("dev", "us-east-1");
tester.controller().applications().deploy(context2.instanceId(), devZone, Optional.of(applicationPackage), DeployOptions.none());
assertTrue("Application deployed and activated",
tester.configServer().application(context2.instanceId(), devZone).get().activated());
assertFalse("Does not provision certificate in zones with routing layer", certificate.apply(context2.instance()).isPresent());
}
@Test
public void testDeployWithCrossCloudEndpoints() {
tester.controllerTester().zoneRegistry().setZones(
ZoneApiMock.fromId("prod.us-west-1"),
ZoneApiMock.newBuilder().with(CloudName.from("aws")).withId("prod.aws-us-east-1").build()
);
var context = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder()
.region("aws-us-east-1")
.region("us-west-1")
.endpoint("default", "default")
.build();
try {
context.submit(applicationPackage);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("Endpoint 'default' in instance 'default' cannot contain regions in different clouds: [aws-us-east-1, us-west-1]", e.getMessage());
}
var applicationPackage2 = new ApplicationPackageBuilder()
.region("aws-us-east-1")
.region("us-west-1")
.endpoint("aws", "default", "aws-us-east-1")
.endpoint("foo", "default", "aws-us-east-1", "us-west-1")
.build();
try {
context.submit(applicationPackage2);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("Endpoint 'foo' in instance 'default' cannot contain regions in different clouds: [aws-us-east-1, us-west-1]", e.getMessage());
}
}
@Test
public void testDeployWithoutSourceRevision() {
var context = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.environment(Environment.prod)
.region("us-west-1")
.build();
context.submit(applicationPackage, Optional.empty())
.deploy();
assertEquals("Deployed application", 1, context.instance().deployments().size());
}
@Test
public void testDeployWithGlobalEndpointsAndMultipleRoutingMethods() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.endpoint("default", "default", zone1.region().value(), zone2.region().value())
.endpoint("east", "default", zone2.region().value())
.region(zone1.region())
.region(zone2.region())
.build();
tester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone1), RoutingMethod.shared,
RoutingMethod.sharedLayer4);
tester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone2), RoutingMethod.shared,
RoutingMethod.exclusive);
context.submit(applicationPackage).deploy();
var expectedRecords = List.of(
new Record(Record.Type.ALIAS,
RecordName.from("east.application.tenant.global.vespa.oath.cloud"),
new LatencyAliasTarget(HostName.from("lb-0--tenant:application:default--prod.us-east-3"),
"dns-zone-1", ZoneId.from("prod.us-east-3")).pack()),
new Record(Record.Type.CNAME,
RecordName.from("application--tenant.global.vespa.oath.cloud"),
RecordData.from("rotation-fqdn-01.")),
new Record(Record.Type.CNAME,
RecordName.from("application.tenant.us-east-3.vespa.oath.cloud"),
RecordData.from("lb-0--tenant:application:default--prod.us-east-3.")),
new Record(Record.Type.CNAME,
RecordName.from("east--application--tenant.global.vespa.oath.cloud"),
RecordData.from("rotation-fqdn-02.")));
assertEquals(expectedRecords, List.copyOf(tester.controllerTester().nameService().records()));
}
@Test
public void testDirectRoutingSupport() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
var applicationPackageBuilder = new ApplicationPackageBuilder()
.region(zone1.region())
.region(zone2.region());
tester.controllerTester().zoneRegistry()
.setRoutingMethod(ZoneApiMock.from(zone1), RoutingMethod.shared, RoutingMethod.sharedLayer4)
.setRoutingMethod(ZoneApiMock.from(zone2), RoutingMethod.shared, RoutingMethod.sharedLayer4);
Supplier<Set<RoutingMethod>> routingMethods = () -> tester.controller().routing().endpointsOf(context.deploymentIdIn(zone1))
.asList()
.stream()
.map(Endpoint::routingMethod)
.collect(Collectors.toSet());
((InMemoryFlagSource) tester.controller().flagSource()).withBooleanFlag(Flags.ALLOW_DIRECT_ROUTING.id(), false);
context.submit(applicationPackageBuilder.build()).deploy();
assertEquals(Set.of(RoutingMethod.shared), routingMethods.get());
context.submit(applicationPackageBuilder.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION).build())
.deploy();
assertEquals(Set.of(RoutingMethod.shared), routingMethods.get());
applicationPackageBuilder = applicationPackageBuilder.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"));
context.submit(applicationPackageBuilder.build()).deploy();
assertEquals(Set.of(RoutingMethod.shared), routingMethods.get());
((InMemoryFlagSource) tester.controller().flagSource()).withBooleanFlag(Flags.ALLOW_DIRECT_ROUTING.id(), true);
context.submit(applicationPackageBuilder.build()).deploy();
assertEquals(Set.of(RoutingMethod.shared, RoutingMethod.sharedLayer4), routingMethods.get());
applicationPackageBuilder = applicationPackageBuilder.endpoint("default", "default");
context.submit(applicationPackageBuilder.build()).deploy();
for (var zone : List.of(zone1, zone2)) {
assertEquals(Set.of("rotation-id-01",
"application.tenant.global.vespa.oath.cloud",
"application--tenant.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone)));
}
}
@Test
public void testChangeEndpointCluster() {
var context = tester.newDeploymentContext();
var west = ZoneId.from("prod", "us-west-1");
var east = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region(west.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage).deploy();
assertEquals(ClusterSpec.Id.from("foo"), tester.applications().requireInstance(context.instanceId())
.rotations().get(0).clusterId());
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "bar")
.region(west.region().value())
.region(east.region().value())
.build();
try {
context.submit(applicationPackage).deploy();
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant.application' has endpoints [endpoint " +
"'default' (cluster foo) -> us-east-3, us-west-1], but does not include all of these in " +
"deployment.xml. Deploying given deployment.xml will remove " +
"[endpoint 'default' (cluster foo) -> us-east-3, us-west-1] and add " +
"[endpoint 'default' (cluster bar) -> us-east-3, us-west-1]. To allow this add " +
"<allow until='yyyy-mm-dd'>global-endpoint-change</allow> to validation-overrides.xml, see " +
"https:
}
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "bar")
.region(west.region().value())
.region(east.region().value())
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage).deploy();
assertEquals(ClusterSpec.Id.from("bar"), tester.applications().requireInstance(context.instanceId())
.rotations().get(0).clusterId());
}
@Test
public void testReadableApplications() {
var db = new MockCuratorDb();
var tester = new DeploymentTester(new ControllerTester(db));
var app1 = tester.newDeploymentContext("t1", "a1", "default")
.submit()
.deploy();
var app2 = tester.newDeploymentContext("t2", "a2", "default")
.submit()
.deploy();
assertEquals(2, tester.applications().readable().size());
db.curator().set(Path.fromString("/controller/v1/applications/" + app2.application().id().serialized()),
new byte[]{(byte) 0xDE, (byte) 0xAD});
assertEquals(1, tester.applications().readable().size());
try {
tester.applications().asList();
fail("Expected exception");
} catch (Exception ignored) {
}
app1.submit().deploy();
}
} | class ControllerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
public void testDeployment() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
Version version1 = tester.configServer().initialVersion();
var context = tester.newDeploymentContext();
context.submit(applicationPackage);
assertEquals("Application version is known from completion of initial job",
ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1, "a@b", new Version("6.1"), Instant.ofEpochSecond(1)),
context.instance().change().application().get());
context.runJob(systemTest);
context.runJob(stagingTest);
ApplicationVersion applicationVersion = context.instance().change().application().get();
assertFalse("Application version has been set during deployment", applicationVersion.isUnknown());
tester.triggerJobs();
tester.clock().advance(Duration.ofSeconds(1));
context.timeOutUpgrade(productionUsWest1);
assertEquals(4, context.instanceJobs().size());
tester.triggerJobs();
tester.controllerTester().createNewController();
assertNotNull(tester.controller().tenants().get(TenantName.from("tenant1")));
assertNotNull(tester.controller().applications().requireInstance(context.instanceId()));
context.submit(applicationPackage);
context.runJob(systemTest);
context.runJob(stagingTest);
context.jobAborted(productionUsWest1);
context.runJob(productionUsWest1);
tester.triggerJobs();
context.runJob(productionUsEast3);
assertEquals(4, context.instanceJobs().size());
applicationPackage = new ApplicationPackageBuilder()
.instances("hellO")
.build();
try {
context.submit(applicationPackage);
fail("Expected exception due to illegal deployment spec.");
}
catch (IllegalArgumentException e) {
assertEquals("Invalid id 'hellO'. Tenant, application and instance names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.", e.getMessage());
}
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("deep-space-9")
.build();
try {
context.submit(applicationPackage);
fail("Expected exception due to illegal deployment spec.");
}
catch (IllegalArgumentException e) {
assertEquals("Zone prod.deep-space-9 in deployment spec was not found in this system!", e.getMessage());
}
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-east-3")
.build();
try {
assertTrue(context.instance().deployments().containsKey(ZoneId.from("prod", "us-west-1")));
context.submit(applicationPackage);
fail("Expected exception due to illegal production deployment removal");
}
catch (IllegalArgumentException e) {
assertEquals("deployment-removal: application 'tenant.application' is deployed in us-west-1, but does not include this zone in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval),
e.getMessage());
}
assertNotNull("Zone was not removed",
context.instance().deployments().get(productionUsWest1.zone(main)));
applicationPackage = new ApplicationPackageBuilder()
.allow(ValidationId.deploymentRemoval)
.upgradePolicy("default")
.environment(Environment.prod)
.region("us-east-3")
.build();
context.submit(applicationPackage);
assertNull("Zone was removed",
context.instance().deployments().get(productionUsWest1.zone(main)));
assertNull("Deployment job was removed", context.instanceJobs().get(productionUsWest1));
}
@Test
public void testGlobalRotations() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.region(zone1.region())
.region(zone2.region())
.endpoint("default", "default", zone1.region().value(), zone2.region().value())
.build();
context.submit(applicationPackage).deploy();
var deployment1 = context.deploymentIdIn(zone1);
var status1 = tester.controller().routing().globalRotationStatus(deployment1);
assertEquals(1, status1.size());
assertTrue("All upstreams are in", status1.values().stream().allMatch(es -> es.getStatus() == EndpointStatus.Status.in));
var newStatus = new EndpointStatus(EndpointStatus.Status.out, "unit-test", ControllerTest.class.getSimpleName(), tester.clock().instant().getEpochSecond());
tester.controller().routing().setGlobalRotationStatus(deployment1, newStatus);
status1 = tester.controller().routing().globalRotationStatus(deployment1);
assertEquals(1, status1.size());
assertTrue("All upstreams are out", status1.values().stream().allMatch(es -> es.getStatus() == EndpointStatus.Status.out));
assertTrue("Reason is set", status1.values().stream().allMatch(es -> es.getReason().equals("unit-test")));
var status2 = tester.controller().routing().globalRotationStatus(context.deploymentIdIn(zone2));
assertEquals(1, status2.size());
assertTrue("All upstreams are in", status2.values().stream().allMatch(es -> es.getStatus() == EndpointStatus.Status.in));
}
@Test
public void testDnsAliasRegistration() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
for (Deployment deployment : deployments) {
assertEquals("Rotation names are passed to config server in " + deployment.zone(),
Set.of("rotation-id-01",
"app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(deployment.zone())));
}
context.flushDnsUpdates();
assertEquals(1, tester.controllerTester().nameService().records().size());
var record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
}
@Test
public void testDnsAliasRegistrationLegacy() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
for (Deployment deployment : deployments) {
assertEquals("Rotation names are passed to config server in " + deployment.zone(),
Set.of("rotation-id-01",
"app1--tenant1.global.vespa.oath.cloud",
"app1.tenant1.global.vespa.yahooapis.com",
"app1--tenant1.global.vespa.yahooapis.com"),
tester.configServer().rotationNames().get(context.deploymentIdIn(deployment.zone())));
}
context.flushDnsUpdates();
assertEquals(3, tester.controllerTester().nameService().records().size());
Optional<Record> record = tester.controllerTester().findCname("app1--tenant1.global.vespa.yahooapis.com");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.yahooapis.com", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
record = tester.controllerTester().findCname("app1.tenant1.global.vespa.yahooapis.com");
assertTrue(record.isPresent());
assertEquals("app1.tenant1.global.vespa.yahooapis.com", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
}
@Test
public void testDnsAliasRegistrationWithEndpoints() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("foobar", "qrs", "us-west-1", "us-central-1")
.endpoint("default", "qrs", "us-west-1", "us-central-1")
.endpoint("all", "qrs")
.endpoint("west", "qrs", "us-west-1")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
var notWest = Set.of(
"rotation-id-01", "foobar--app1--tenant1.global.vespa.oath.cloud",
"rotation-id-02", "app1--tenant1.global.vespa.oath.cloud",
"rotation-id-03", "all--app1--tenant1.global.vespa.oath.cloud"
);
var west = Sets.union(notWest, Set.of("rotation-id-04", "west--app1--tenant1.global.vespa.oath.cloud"));
for (Deployment deployment : deployments) {
assertEquals("Rotation names are passed to config server in " + deployment.zone(),
ZoneId.from("prod.us-west-1").equals(deployment.zone()) ? west : notWest,
tester.configServer().rotationNames().get(context.deploymentIdIn(deployment.zone())));
}
context.flushDnsUpdates();
assertEquals(4, tester.controllerTester().nameService().records().size());
var record1 = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record1.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record1.get().name().asString());
assertEquals("rotation-fqdn-02.", record1.get().data().asString());
var record2 = tester.controllerTester().findCname("foobar--app1--tenant1.global.vespa.oath.cloud");
assertTrue(record2.isPresent());
assertEquals("foobar--app1--tenant1.global.vespa.oath.cloud", record2.get().name().asString());
assertEquals("rotation-fqdn-01.", record2.get().data().asString());
var record3 = tester.controllerTester().findCname("all--app1--tenant1.global.vespa.oath.cloud");
assertTrue(record3.isPresent());
assertEquals("all--app1--tenant1.global.vespa.oath.cloud", record3.get().name().asString());
assertEquals("rotation-fqdn-03.", record3.get().data().asString());
var record4 = tester.controllerTester().findCname("west--app1--tenant1.global.vespa.oath.cloud");
assertTrue(record4.isPresent());
assertEquals("west--app1--tenant1.global.vespa.oath.cloud", record4.get().name().asString());
assertEquals("rotation-fqdn-04.", record4.get().data().asString());
}
@Test
public void testDnsAliasRegistrationWithChangingEndpoints() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
var west = ZoneId.from("prod", "us-west-1");
var central = ZoneId.from("prod", "us-central-1");
var east = ZoneId.from("prod", "us-east-3");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage).deploy();
for (var zone : List.of(west, central)) {
assertEquals(
"Zone " + zone + " is a member of global endpoint",
Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone))
);
}
ApplicationPackage applicationPackage2 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value())
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage2).deploy();
for (var zone : List.of(west, central)) {
assertEquals(
"Zone " + zone + " is a member of global endpoint",
Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone))
);
}
assertEquals(
"Zone " + east + " is a member of global endpoint",
Set.of("rotation-id-02", "east--app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(east))
);
ApplicationPackage applicationPackage3 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value(), east.region().value())
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage3).deploy();
for (var zone : List.of(west, central, east)) {
assertEquals(
"Zone " + zone + " is a member of global endpoint",
zone.equals(east)
? Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud",
"rotation-id-02", "east--app1--tenant1.global.vespa.oath.cloud")
: Set.of("rotation-id-01", "app1--tenant1.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone))
);
}
ApplicationPackage applicationPackage4 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", west.region().value(), central.region().value())
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
try {
context.submit(applicationPackage4);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant1.app1' has endpoints " +
"[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
"but does not include all of these in deployment.xml. Deploying given deployment.xml " +
"will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1] " +
"and add [endpoint 'default' (cluster qrs) -> us-central-1, us-west-1]. " +
ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
}
ApplicationPackage applicationPackage5 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.build();
try {
context.submit(applicationPackage5);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant1.app1' has endpoints " +
"[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
"but does not include all of these in deployment.xml. Deploying given deployment.xml " +
"will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1]. " +
ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
}
ApplicationPackage applicationPackage6 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("east", "qrs", east.region().value())
.region(west.region().value())
.region(central.region().value())
.region(east.region().value())
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage6);
}
@Test
public void testUnassignRotations() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "qrs", "us-west-1", "us-central-1")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
ApplicationPackage applicationPackage2 = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-central-1")
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage2).deploy();
assertEquals(List.of(), context.instance().rotations());
assertEquals(
Set.of(),
tester.configServer().rotationNames().get(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")))
);
}
@Test
public void testUpdatesExistingDnsAlias() {
{
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
assertEquals(1, tester.controllerTester().nameService().records().size());
Optional<Record> record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app1--tenant1.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.allow(ValidationId.deploymentRemoval)
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage);
tester.applications().deleteApplication(context.application().id(),
tester.controllerTester().credentialsFor(context.application().id().tenant()));
try (RotationLock lock = tester.controller().routing().rotations().lock()) {
assertTrue("Rotation is unassigned",
tester.controller().routing().rotations().availableRotations(lock)
.containsKey(new RotationId("rotation-id-01")));
}
context.flushDnsUpdates();
record = tester.controllerTester().findCname("app1--tenant1.global.vespa.yahooapis.com");
assertTrue(record.isEmpty());
record = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record.isEmpty());
record = tester.controllerTester().findCname("app1.tenant1.global.vespa.yahooapis.com");
assertTrue(record.isEmpty());
}
{
var context = tester.newDeploymentContext("tenant2", "app2", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
assertEquals(1, tester.controllerTester().nameService().records().size());
var record = tester.controllerTester().findCname("app2--tenant2.global.vespa.oath.cloud");
assertTrue(record.isPresent());
assertEquals("app2--tenant2.global.vespa.oath.cloud", record.get().name().asString());
assertEquals("rotation-fqdn-01.", record.get().data().asString());
}
{
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region("us-west-1")
.region("us-central-1")
.build();
context.submit(applicationPackage).deploy();
assertEquals("rotation-id-02", context.instance().rotations().get(0).rotationId().asString());
assertEquals(2, tester.controllerTester().nameService().records().size());
var record1 = tester.controllerTester().findCname("app1--tenant1.global.vespa.oath.cloud");
assertTrue(record1.isPresent());
assertEquals("rotation-fqdn-02.", record1.get().data().asString());
var record2 = tester.controllerTester().findCname("app2--tenant2.global.vespa.oath.cloud");
assertTrue(record2.isPresent());
assertEquals("rotation-fqdn-01.", record2.get().data().asString());
}
}
@Test
public void testIntegrationTestDeployment() {
Version six = Version.fromString("6.1");
tester.controllerTester().zoneRegistry().setSystemName(SystemName.cd);
tester.controllerTester().zoneRegistry().setZones(ZoneApiMock.fromId("prod.cd-us-central-1"));
tester.configServer().bootstrap(List.of(ZoneId.from("prod.cd-us-central-1")), SystemApplication.all());
tester.controllerTester().upgradeSystem(six);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.majorVersion(6)
.region("cd-us-central-1")
.build();
var context = tester.newDeploymentContext();
ZoneId zone = ZoneId.from("prod", "cd-us-central-1");
DeployOptions options = new DeployOptions(true, Optional.empty(), false,
false);
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), options);
assertTrue("Application deployed and activated",
tester.configServer().application(context.instanceId(), zone).get().activated());
assertTrue("No job status added",
context.instanceJobs().isEmpty());
Version seven = Version.fromString("7.2");
tester.controllerTester().upgradeSystem(seven);
tester.upgrader().maintain();
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), options);
assertEquals(six, context.instance().deployments().get(zone).version());
}
@Test
@Test
public void testSuspension() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
context.submit(applicationPackage).deploy();
DeploymentId deployment1 = context.deploymentIdIn(ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
DeploymentId deployment2 = context.deploymentIdIn(ZoneId.from(Environment.prod, RegionName.from("us-east-3")));
assertFalse(tester.configServer().isSuspended(deployment1));
assertFalse(tester.configServer().isSuspended(deployment2));
tester.configServer().setSuspended(deployment1, true);
assertTrue(tester.configServer().isSuspended(deployment1));
assertFalse(tester.configServer().isSuspended(deployment2));
}
@Test
public void testDeletingApplicationThatHasAlreadyBeenDeleted() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-east-3")
.region("us-west-1")
.build();
ZoneId zone = ZoneId.from("prod", "us-west-1");
tester.controller().applications().deploy(context.instanceId(), zone, Optional.of(applicationPackage), DeployOptions.none());
tester.controller().applications().deactivate(context.instanceId(), ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
tester.controller().applications().deactivate(context.instanceId(), ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
}
@Test
public void testDeployApplicationPackageWithApplicationDir() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build(true);
tester.newDeploymentContext().submit(applicationPackage);
}
@Test
public void testDeployApplicationWithWarnings() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
ZoneId zone = ZoneId.from("prod", "us-west-1");
int warnings = 3;
tester.configServer().generateWarnings(context.deploymentIdIn(zone), warnings);
context.submit(applicationPackage).deploy();
assertEquals(warnings, context.deployment(zone)
.metrics().warnings().get(DeploymentMetrics.Warning.all).intValue());
}
@Test
public void testDeploySelectivelyProvisionsCertificate() {
Function<Instance, Optional<EndpointCertificateMetadata>> certificate = (application) -> tester.controller().curator().readEndpointCertificateMetadata(application.id());
var context1 = tester.newDeploymentContext("tenant1", "app1", "default");
var prodZone = ZoneId.from("prod", "us-west-1");
var stagingZone = ZoneId.from("staging", "us-east-3");
var testZone = ZoneId.from("test", "us-east-1");
tester.controllerTester().zoneRegistry().exclusiveRoutingIn(ZoneApiMock.from(prodZone));
var applicationPackage = new ApplicationPackageBuilder().athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.environment(prodZone.environment())
.region(prodZone.region())
.build();
context1.submit(applicationPackage).deploy();
var cert = certificate.apply(context1.instance());
assertTrue("Provisions certificate in " + Environment.prod, cert.isPresent());
assertEquals(Stream.concat(Stream.of("vznqtz7a5ygwjkbhhj7ymxvlrekgt4l6g.vespa.oath.cloud",
"app1.tenant1.global.vespa.oath.cloud",
"*.app1.tenant1.global.vespa.oath.cloud"),
Stream.of(prodZone, testZone, stagingZone)
.flatMap(zone -> Stream.of("", "*.")
.map(prefix -> prefix + "app1.tenant1." + zone.region().value() +
(zone.environment() == Environment.prod ? "" : "." + zone.environment().value()) +
".vespa.oath.cloud")))
.collect(Collectors.toUnmodifiableList()),
tester.controllerTester().serviceRegistry().endpointCertificateMock().dnsNamesOf(context1.instanceId()));
context1.submit(applicationPackage).deploy();
assertEquals(cert, certificate.apply(context1.instance()));
var context2 = tester.newDeploymentContext("tenant1", "app2", "default");
var devZone = ZoneId.from("dev", "us-east-1");
tester.controller().applications().deploy(context2.instanceId(), devZone, Optional.of(applicationPackage), DeployOptions.none());
assertTrue("Application deployed and activated",
tester.configServer().application(context2.instanceId(), devZone).get().activated());
assertFalse("Does not provision certificate in zones with routing layer", certificate.apply(context2.instance()).isPresent());
}
@Test
public void testDeployWithCrossCloudEndpoints() {
tester.controllerTester().zoneRegistry().setZones(
ZoneApiMock.fromId("prod.us-west-1"),
ZoneApiMock.newBuilder().with(CloudName.from("aws")).withId("prod.aws-us-east-1").build()
);
var context = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder()
.region("aws-us-east-1")
.region("us-west-1")
.endpoint("default", "default")
.build();
try {
context.submit(applicationPackage);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("Endpoint 'default' in instance 'default' cannot contain regions in different clouds: [aws-us-east-1, us-west-1]", e.getMessage());
}
var applicationPackage2 = new ApplicationPackageBuilder()
.region("aws-us-east-1")
.region("us-west-1")
.endpoint("aws", "default", "aws-us-east-1")
.endpoint("foo", "default", "aws-us-east-1", "us-west-1")
.build();
try {
context.submit(applicationPackage2);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("Endpoint 'foo' in instance 'default' cannot contain regions in different clouds: [aws-us-east-1, us-west-1]", e.getMessage());
}
}
@Test
public void testDeployWithoutSourceRevision() {
var context = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.environment(Environment.prod)
.region("us-west-1")
.build();
context.submit(applicationPackage, Optional.empty())
.deploy();
assertEquals("Deployed application", 1, context.instance().deployments().size());
}
@Test
public void testDeployWithGlobalEndpointsAndMultipleRoutingMethods() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.endpoint("default", "default", zone1.region().value(), zone2.region().value())
.endpoint("east", "default", zone2.region().value())
.region(zone1.region())
.region(zone2.region())
.build();
tester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone1), RoutingMethod.shared,
RoutingMethod.sharedLayer4);
tester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone2), RoutingMethod.shared,
RoutingMethod.exclusive);
context.submit(applicationPackage).deploy();
var expectedRecords = List.of(
new Record(Record.Type.ALIAS,
RecordName.from("east.application.tenant.global.vespa.oath.cloud"),
new LatencyAliasTarget(HostName.from("lb-0--tenant:application:default--prod.us-east-3"),
"dns-zone-1", ZoneId.from("prod.us-east-3")).pack()),
new Record(Record.Type.CNAME,
RecordName.from("application--tenant.global.vespa.oath.cloud"),
RecordData.from("rotation-fqdn-01.")),
new Record(Record.Type.CNAME,
RecordName.from("application.tenant.us-east-3.vespa.oath.cloud"),
RecordData.from("lb-0--tenant:application:default--prod.us-east-3.")),
new Record(Record.Type.CNAME,
RecordName.from("east--application--tenant.global.vespa.oath.cloud"),
RecordData.from("rotation-fqdn-02.")));
assertEquals(expectedRecords, List.copyOf(tester.controllerTester().nameService().records()));
}
@Test
public void testDirectRoutingSupport() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
var applicationPackageBuilder = new ApplicationPackageBuilder()
.region(zone1.region())
.region(zone2.region());
tester.controllerTester().zoneRegistry()
.setRoutingMethod(ZoneApiMock.from(zone1), RoutingMethod.shared, RoutingMethod.sharedLayer4)
.setRoutingMethod(ZoneApiMock.from(zone2), RoutingMethod.shared, RoutingMethod.sharedLayer4);
Supplier<Set<RoutingMethod>> routingMethods = () -> tester.controller().routing().endpointsOf(context.deploymentIdIn(zone1))
.asList()
.stream()
.map(Endpoint::routingMethod)
.collect(Collectors.toSet());
((InMemoryFlagSource) tester.controller().flagSource()).withBooleanFlag(Flags.ALLOW_DIRECT_ROUTING.id(), false);
context.submit(applicationPackageBuilder.build()).deploy();
assertEquals(Set.of(RoutingMethod.shared), routingMethods.get());
context.submit(applicationPackageBuilder.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION).build())
.deploy();
assertEquals(Set.of(RoutingMethod.shared), routingMethods.get());
applicationPackageBuilder = applicationPackageBuilder.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"));
context.submit(applicationPackageBuilder.build()).deploy();
assertEquals(Set.of(RoutingMethod.shared), routingMethods.get());
((InMemoryFlagSource) tester.controller().flagSource()).withBooleanFlag(Flags.ALLOW_DIRECT_ROUTING.id(), true);
context.submit(applicationPackageBuilder.build()).deploy();
assertEquals(Set.of(RoutingMethod.shared, RoutingMethod.sharedLayer4), routingMethods.get());
applicationPackageBuilder = applicationPackageBuilder.endpoint("default", "default");
context.submit(applicationPackageBuilder.build()).deploy();
for (var zone : List.of(zone1, zone2)) {
assertEquals(Set.of("rotation-id-01",
"application.tenant.global.vespa.oath.cloud",
"application--tenant.global.vespa.oath.cloud"),
tester.configServer().rotationNames().get(context.deploymentIdIn(zone)));
}
}
@Test
public void testChangeEndpointCluster() {
var context = tester.newDeploymentContext();
var west = ZoneId.from("prod", "us-west-1");
var east = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "foo")
.region(west.region().value())
.region(east.region().value())
.build();
context.submit(applicationPackage).deploy();
assertEquals(ClusterSpec.Id.from("foo"), tester.applications().requireInstance(context.instanceId())
.rotations().get(0).clusterId());
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "bar")
.region(west.region().value())
.region(east.region().value())
.build();
try {
context.submit(applicationPackage).deploy();
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant.application' has endpoints [endpoint " +
"'default' (cluster foo) -> us-east-3, us-west-1], but does not include all of these in " +
"deployment.xml. Deploying given deployment.xml will remove " +
"[endpoint 'default' (cluster foo) -> us-east-3, us-west-1] and add " +
"[endpoint 'default' (cluster bar) -> us-east-3, us-west-1]. To allow this add " +
"<allow until='yyyy-mm-dd'>global-endpoint-change</allow> to validation-overrides.xml, see " +
"https:
}
applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.endpoint("default", "bar")
.region(west.region().value())
.region(east.region().value())
.allow(ValidationId.globalEndpointChange)
.build();
context.submit(applicationPackage).deploy();
assertEquals(ClusterSpec.Id.from("bar"), tester.applications().requireInstance(context.instanceId())
.rotations().get(0).clusterId());
}
@Test
public void testReadableApplications() {
var db = new MockCuratorDb();
var tester = new DeploymentTester(new ControllerTester(db));
var app1 = tester.newDeploymentContext("t1", "a1", "default")
.submit()
.deploy();
var app2 = tester.newDeploymentContext("t2", "a2", "default")
.submit()
.deploy();
assertEquals(2, tester.applications().readable().size());
db.curator().set(Path.fromString("/controller/v1/applications/" + app2.application().id().serialized()),
new byte[]{(byte) 0xDE, (byte) 0xAD});
assertEquals(1, tester.applications().readable().size());
try {
tester.applications().asList();
fail("Expected exception");
} catch (Exception ignored) {
}
app1.submit().deploy();
}
} |
Use port 19092 | private static URI createMetricsProxyURI(String hostname) {
return URI.create("http:
} | return URI.create("http: | private static URI createMetricsProxyURI(String hostname) {
return URI.create("http:
} | class ProtonMetricsRetriever {
private final ClusterProtonMetricsRetriever metricsRetriever;
public ProtonMetricsRetriever() {
this( new ClusterProtonMetricsRetriever());
}
public ProtonMetricsRetriever(ClusterProtonMetricsRetriever metricsRetriever) {
this.metricsRetriever = metricsRetriever;
}
public ProtonMetricsResponse getMetrics(Application application) {
var hosts = getHostsOfApplication(application);
var clusterMetrics = metricsRetriever.requestMetricsGroupedByCluster(hosts);
return new ProtonMetricsResponse(200, application.getId(), clusterMetrics);
}
private static Collection<URI> getHostsOfApplication(Application application) {
return application.getModel().getHosts().stream()
.filter(host -> host.getServices().stream().anyMatch(isSearchNode()))
.map(HostInfo::getHostname)
.map(ProtonMetricsRetriever::createMetricsProxyURI)
.collect(Collectors.toList());
}
private static Predicate<ServiceInfo> isSearchNode() {
return serviceInfo -> serviceInfo.getServiceType().equalsIgnoreCase("searchnode");
}
} | class ProtonMetricsRetriever {
private final ClusterProtonMetricsRetriever metricsRetriever;
public ProtonMetricsRetriever() {
this( new ClusterProtonMetricsRetriever());
}
public ProtonMetricsRetriever(ClusterProtonMetricsRetriever metricsRetriever) {
this.metricsRetriever = metricsRetriever;
}
public ProtonMetricsResponse getMetrics(Application application) {
var hosts = getHostsOfApplication(application);
var clusterMetrics = metricsRetriever.requestMetricsGroupedByCluster(hosts);
return new ProtonMetricsResponse(200, application.getId(), clusterMetrics);
}
private static Collection<URI> getHostsOfApplication(Application application) {
return application.getModel().getHosts().stream()
.filter(host -> host.getServices().stream().anyMatch(isSearchNode()))
.map(HostInfo::getHostname)
.map(ProtonMetricsRetriever::createMetricsProxyURI)
.collect(Collectors.toList());
}
private static Predicate<ServiceInfo> isSearchNode() {
return serviceInfo -> serviceInfo.getServiceType().equalsIgnoreCase("searchnode");
}
} |
It would be good to have a list of two hosts, each having different metric values. Then we would have some actual aggregation | public void testMetricAggregation() throws IOException {
Collection<URI> host = List.of(URI.create("http:
stubFor(get(urlEqualTo("/metrics/v2/values"))
.willReturn(aResponse()
.withStatus(200)
.withBody(nodeMetrics())));
String expectedClusterName = "content/content/0/0";
Map<String, ProtonMetricsAggregator> aggregatorMap = new ClusterProtonMetricsRetriever().requestMetricsGroupedByCluster(host);
compareAggregators(
new ProtonMetricsAggregator()
.addDocumentReadyCount(1275)
.addDocumentActiveCount(1275)
.addDocumentTotalCount(1275)
.addDocumentDiskUsage(14781856)
.addResourceDiskUsageAverage(0.0009083386306)
.addResourceMemoryUsageAverage(0.0183488434436),
aggregatorMap.get(expectedClusterName)
);
wireMock.stop();
} | Collection<URI> host = List.of(URI.create("http: | public void testMetricAggregation() throws IOException {
List<URI> hosts = Stream.of(1, 2)
.map(item -> URI.create("http:
.collect(Collectors.toList());
stubFor(get(urlEqualTo("/metrics1/v2/values"))
.willReturn(aResponse()
.withStatus(200)
.withBody(nodeMetrics("_1"))));
stubFor(get(urlEqualTo("/metrics2/v2/values"))
.willReturn(aResponse()
.withStatus(200)
.withBody(nodeMetrics("_2"))));
String expectedClusterNameContent = "content/content/0/0";
String expectedClusterNameMusic = "content/music/0/0";
Map<String, ProtonMetricsAggregator> aggregatorMap = new ClusterProtonMetricsRetriever().requestMetricsGroupedByCluster(hosts);
compareAggregators(
new ProtonMetricsAggregator()
.addDocumentReadyCount(1275)
.addDocumentActiveCount(1275)
.addDocumentTotalCount(1275)
.addDocumentDiskUsage(14781856)
.addResourceDiskUsageAverage(0.0009083386306)
.addResourceMemoryUsageAverage(0.0183488434436),
aggregatorMap.get(expectedClusterNameContent)
);
compareAggregators(
new ProtonMetricsAggregator()
.addDocumentReadyCount(3008)
.addDocumentActiveCount(3008)
.addDocumentTotalCount(3008)
.addDocumentDiskUsage(331157)
.addResourceDiskUsageAverage(0.0000152263558)
.addResourceMemoryUsageAverage(0.0156505524171),
aggregatorMap.get(expectedClusterNameMusic)
);
wireMock.stop();
} | class ClusterProtonMetricsRetrieverTest {
@Rule
public final WireMockRule wireMock = new WireMockRule(options().dynamicPort(), true);
@Test
private String nodeMetrics() throws IOException {
return Files.readString(Path.of("src/test/resources/metrics/node_metrics"));
}
private static final double metricsTolerance = 0.001;
private void compareAggregators(ProtonMetricsAggregator expected, ProtonMetricsAggregator actual) {
assertEquals(expected.aggregateDocumentDiskUsage(), actual.aggregateDocumentDiskUsage(), metricsTolerance);
}
} | class ClusterProtonMetricsRetrieverTest {
@Rule
public final WireMockRule wireMock = new WireMockRule(options().dynamicPort(), true);
@Test
private String nodeMetrics(String extension) throws IOException {
return Files.readString(Path.of("src/test/resources/metrics/node_metrics" + extension));
}
private static final double metricsTolerance = 0.001;
private void compareAggregators(ProtonMetricsAggregator expected, ProtonMetricsAggregator actual) {
assertEquals(expected.aggregateDocumentDiskUsage(), actual.aggregateDocumentDiskUsage(), metricsTolerance);
}
} |
Also log exception | private JsonResponse buildResponseFromProtonMetrics(List<ProtonMetrics> protonMetrics) {
try {
var jsonObject = new JSONObject();
var jsonArray = new JSONArray();
for (ProtonMetrics metrics : protonMetrics) {
jsonArray.put(metrics.toJson());
}
jsonObject.put("metrics", jsonArray);
return new JsonResponse(200, jsonObject.toString());
} catch (JSONException e) {
log.severe("Unable to build JsonResponse with Proton data");
return new JsonResponse(500, "");
}
} | log.severe("Unable to build JsonResponse with Proton data"); | private JsonResponse buildResponseFromProtonMetrics(List<ProtonMetrics> protonMetrics) {
try {
var jsonObject = new JSONObject();
var jsonArray = new JSONArray();
for (ProtonMetrics metrics : protonMetrics) {
jsonArray.put(metrics.toJson());
}
jsonObject.put("metrics", jsonArray);
return new JsonResponse(200, jsonObject.toString());
} catch (JSONException e) {
log.severe("Unable to build JsonResponse with Proton data");
return new JsonResponse(500, "");
}
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestConfigSerializer testConfigSerializer;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
}
@Override
public Duration getTimeout() {
return Duration.ofMinutes(20);
}
@Override
public HttpResponse handle(HttpRequest request) {
try {
Path path = new Path(request.getUri(), OPTIONAL_PREFIX);
switch (request.getMethod()) {
case GET: return handleGET(path, request);
case PUT: return handlePUT(path, request);
case POST: return handlePOST(path, request);
case PATCH: return handlePATCH(path, request);
case DELETE: return handleDELETE(path, request);
case OPTIONS: return handleOPTIONS();
default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
}
}
catch (ForbiddenException e) {
return ErrorResponse.forbidden(Exceptions.toMessageString(e));
}
catch (NotAuthorizedException e) {
return ErrorResponse.unauthorized(Exceptions.toMessageString(e));
}
catch (NotExistsException e) {
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
}
catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
catch (ConfigServerException e) {
switch (e.getErrorCode()) {
case NOT_FOUND:
return new ErrorResponse(NOT_FOUND, e.getErrorCode().name(), Exceptions.toMessageString(e));
case ACTIVATION_CONFLICT:
return new ErrorResponse(CONFLICT, e.getErrorCode().name(), Exceptions.toMessageString(e));
case INTERNAL_SERVER_ERROR:
return new ErrorResponse(INTERNAL_SERVER_ERROR, e.getErrorCode().name(), Exceptions.toMessageString(e));
default:
return new ErrorResponse(BAD_REQUEST, e.getErrorCode().name(), Exceptions.toMessageString(e));
}
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/tenant")) return tenants(request);
if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/metrics")) return metrics(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePUT(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePATCH(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleDELETE(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeAllProdDeployments(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleOPTIONS() {
EmptyResponse response = new EmptyResponse();
response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS");
return response;
}
private HttpResponse recursiveRoot(HttpRequest request) {
Slime slime = new Slime();
Cursor tenantArray = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
toSlime(tenantArray.addObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse root(HttpRequest request) {
return recurseOverTenants(request)
? recursiveRoot(request)
: new ResourceResponse(request, "tenant");
}
private HttpResponse tenants(HttpRequest request) {
Slime slime = new Slime();
Cursor response = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject());
return new SlimeJsonResponse(slime);
}
private HttpResponse tenant(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenant(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenant(Tenant tenant, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
if (controller.tenants().get(tenantName).isEmpty())
return ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist");
Slime slime = new Slime();
Cursor applicationArray = slime.setArray();
for (com.yahoo.vespa.hosted.controller.Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true)) {
Cursor applicationObject = applicationArray.addObject();
applicationObject.setString("tenant", application.id().tenant().value());
applicationObject.setString("application", application.id().application().value());
applicationObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value(),
request.getUri()).toString());
Cursor instanceArray = applicationObject.setArray("instances");
for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet()
: application.instances().keySet()) {
Cursor instanceObject = instanceArray.addObject();
instanceObject.setString("instance", instance.value());
instanceObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/instance/" + instance.value(),
request.getUri()).toString());
}
}
}
return new SlimeJsonResponse(slime);
}
private HttpResponse devApplicationPackage(ApplicationId id, JobType type) {
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Only manually deployed zones have dev packages");
ZoneId zone = type.zone(controller.system());
byte[] applicationPackage = controller.applications().applicationStore().getDev(id, zone);
return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage);
}
private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse compileVersion(String tenantName, String applicationName) {
Slime slime = new Slime();
slime.setObject().setString("compileVersion",
compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString());
return new SlimeJsonResponse(slime);
}
private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
Principal user = request.getJDiscRequest().getUserPrincipal();
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withDeveloperKey(developerKey, user);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Principal user = ((CloudTenant) controller.tenants().require(TenantName.from(tenantName))).developerKeys().get(developerKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withoutDeveloperKey(developerKey);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) {
keys.forEach((key, principal) -> {
Cursor keyObject = keysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", principal.getName());
});
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withoutDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes.");
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
Inspector majorVersionField = requestObject.field("majorVersion");
if (majorVersionField.valid()) {
Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong();
application = application.withMajorVersion(majorVersion);
messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion));
}
Inspector pemDeployKeyField = requestObject.field("pemDeployKey");
if (pemDeployKeyField.valid()) {
String pemDeployKey = pemDeployKeyField.asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
application = application.withDeployKey(deployKey);
messageBuilder.add("Added deploy key " + pemDeployKey);
}
controller.applications().store(application);
});
return new MessageResponse(messageBuilder.toString());
}
private com.yahoo.vespa.hosted.controller.Application getApplication(String tenantName, String applicationName) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
return controller.applications().getApplication(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private Instance getInstance(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
return controller.applications().getInstance(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, id);
Slime slime = new Slime();
Cursor nodesArray = slime.setObject().setArray("nodes");
for (Node node : nodes) {
Cursor nodeObject = nodesArray.addObject();
nodeObject.setString("hostname", node.hostname().value());
nodeObject.setString("state", valueOf(node.state()));
node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.flavor());
toSlime(node.resources(), nodeObject);
nodeObject.setBool("fastDisk", node.resources().diskSpeed() == NodeResources.DiskSpeed.fast);
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
return new SlimeJsonResponse(slime);
}
private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id);
Slime slime = new Slime();
Cursor clustersObject = slime.setObject().setObject("clusters");
for (Cluster cluster : application.clusters().values()) {
Cursor clusterObject = clustersObject.setObject(cluster.id().value());
toSlime(cluster.min(), clusterObject.setObject("min"));
toSlime(cluster.max(), clusterObject.setObject("max"));
toSlime(cluster.current(), clusterObject.setObject("current"));
cluster.target().ifPresent(target -> toSlime(target, clusterObject.setObject("target")));
cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested")));
}
return new SlimeJsonResponse(slime);
}
private static String valueOf(Node.State state) {
switch (state) {
case failed: return "failed";
case parked: return "parked";
case dirty: return "dirty";
case ready: return "ready";
case active: return "active";
case inactive: return "inactive";
case reserved: return "reserved";
case provisioned: return "provisioned";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ServiceState state) {
switch (state) {
case expectedUp: return "expectedUp";
case allowedDown: return "allowedDown";
case unorchestrated: return "unorchestrated";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ClusterType type) {
switch (type) {
case admin: return "admin";
case content: return "content";
case container: return "container";
case combined: return "combined";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
private static String valueOf(NodeResources.DiskSpeed diskSpeed) {
switch (diskSpeed) {
case fast : return "fast";
case slow : return "slow";
case any : return "any";
default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'");
}
}
private static String valueOf(NodeResources.StorageType storageType) {
switch (storageType) {
case remote : return "remote";
case local : return "local";
case any : return "any";
default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'");
}
}
private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters);
return new HttpResponse(200) {
@Override
public void render(OutputStream outputStream) throws IOException {
logStream.transferTo(outputStream);
}
};
}
private HttpResponse metrics(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
List<ProtonMetrics> protonMetrics = controller.serviceRegistry().configServer().getProtonMetrics(deployment);
return buildResponseFromProtonMetrics(protonMetrics);
}
private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
boolean requireTests = ! requestObject.field("skipTests").asBool();
boolean reTrigger = requestObject.field("reTrigger").asBool();
String triggered = reTrigger
? controller.applications().deploymentTrigger()
.reTrigger(id, type).type().jobName()
: controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests)
.stream().map(job -> job.type().jobName()).collect(joining(", "));
return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered"
: "Triggered " + triggered + " for " + id);
}
private HttpResponse pause(ApplicationId id, JobType type) {
Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause);
controller.applications().deploymentTrigger().pauseJob(id, type, until);
return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause);
}
private HttpResponse resume(ApplicationId id, JobType type) {
controller.applications().deploymentTrigger().resumeJob(id, type);
return new MessageResponse(type.jobName() + " for " + id + " resumed");
}
private void toSlime(Cursor object, com.yahoo.vespa.hosted.controller.Application application, HttpRequest request) {
object.setString("tenant", application.id().tenant().value());
object.setString("application", application.id().application().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/job/",
request.getUri()).toString());
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
application.instances().values().stream().findFirst().ifPresent(instance -> {
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
});
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request);
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
if (deploymentSpec.instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec.requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
globalEndpointsToSlime(object, instance);
List<Deployment> deployments = deploymentSpec.instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor deploymentsArray = object.setArray("deployments");
for (Deployment deployment : deployments) {
Cursor deploymentObject = deploymentsArray.addObject();
if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty())
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/instance/" + instance.name().value() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
}
private void globalEndpointsToSlime(Cursor object, Instance instance) {
var globalEndpointUrls = new LinkedHashSet<String>();
controller.routing().endpointsOf(instance.id())
.requiresRotation()
.not().legacy()
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalEndpointUrls::add);
var globalRotationsArray = object.setArray("globalRotations");
globalEndpointUrls.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
}
private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) {
com.yahoo.vespa.hosted.controller.Application application = status.application();
object.setString("tenant", instance.id().tenant().value());
object.setString("application", instance.id().application().value());
object.setString("instance", instance.id().instance().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + instance.id().tenant().value() +
"/application/" + instance.id().application().value() +
"/instance/" + instance.id().instance().value() + "/job/",
request.getUri()).toString());
application.latestVersion().ifPresent(version -> {
sourceRevisionToSlime(version.source(), object.setObject("source"));
version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
version.commit().ifPresent(commit -> object.setString("commit", commit));
});
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if (application.deploymentSpec().instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec().requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
globalEndpointsToSlime(object, instance);
List<Deployment> deployments =
application.deploymentSpec().instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor instancesArray = object.setArray("instances");
for (Deployment deployment : deployments) {
Cursor deploymentObject = instancesArray.addObject();
if (deployment.zone().environment() == Environment.prod) {
if (instance.rotations().size() == 1) {
toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment),
deploymentObject);
}
if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) {
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
}
}
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("instance", instance.id().instance().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
status.jobSteps().keySet().stream()
.filter(job -> job.application().instance().equals(instance.name()))
.filter(job -> job.type().isProduction() && job.type().isDeployment())
.map(job -> job.type().zone(controller.system()))
.filter(zone -> ! instance.deployments().containsKey(zone))
.forEach(zone -> {
Cursor deploymentObject = instancesArray.addObject();
deploymentObject.setString("environment", zone.environment().value());
deploymentObject.setString("region", zone.region().value());
});
application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key)));
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().getInstance(id)
.orElseThrow(() -> new NotExistsException(id + " not found"));
DeploymentId deploymentId = new DeploymentId(instance.id(),
ZoneId.from(environment, region));
Deployment deployment = instance.deployments().get(deploymentId.zoneId());
if (deployment == null)
throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId());
Slime slime = new Slime();
toSlime(slime.setObject(), deploymentId, deployment, request);
return new SlimeJsonResponse(slime);
}
private void toSlime(Cursor object, Change change) {
change.platform().ifPresent(version -> object.setString("version", version.toString()));
change.application()
.filter(version -> !version.isUnknown())
.ifPresent(version -> toSlime(version, object.setObject("revision")));
}
private void toSlime(Endpoint endpoint, Cursor object) {
object.setString("cluster", endpoint.cluster().value());
object.setBool("tls", endpoint.tls());
object.setString("url", endpoint.url().toString());
object.setString("scope", endpointScopeString(endpoint.scope()));
object.setString("routingMethod", routingMethodString(endpoint.routingMethod()));
}
private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) {
response.setString("tenant", deploymentId.applicationId().tenant().value());
response.setString("application", deploymentId.applicationId().application().value());
response.setString("instance", deploymentId.applicationId().instance().value());
response.setString("environment", deploymentId.zoneId().environment().value());
response.setString("region", deploymentId.zoneId().region().value());
var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId()));
var endpointArray = response.setArray("endpoints");
for (var endpoint : controller.routing().endpointsOf(deploymentId)
.scope(Endpoint.Scope.zone)
.not().legacy()) {
toSlime(endpoint, endpointArray.addObject());
}
var globalEndpoints = controller.routing().endpointsOf(application, deploymentId.applicationId().instance())
.not().legacy()
.targets(deploymentId.zoneId());
for (var endpoint : globalEndpoints) {
toSlime(endpoint, endpointArray.addObject());
}
response.setString("nodes", withPathAndQuery("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/", "recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString());
response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString());
response.setString("version", deployment.version().toFullString());
response.setString("revision", deployment.applicationVersion().id());
response.setLong("deployTimeEpochMs", deployment.at().toEpochMilli());
controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId())
.ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", deployment.at().plus(deploymentTimeToLive).toEpochMilli()));
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
var instance = application.instances().get(deploymentId.applicationId().instance());
if (instance != null) {
if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod)
toSlime(instance.rotations(), instance.rotationStatus(), deployment, response);
JobType.from(controller.system(), deployment.zone())
.map(type -> new JobId(instance.id(), type))
.map(status.jobSteps()::get)
.ifPresent(stepStatus -> {
JobControllerApiHandlerHelper.applicationVersionToSlime(
response.setObject("applicationVersion"), deployment.applicationVersion());
if (!status.jobsToRun().containsKey(stepStatus.job().get()))
response.setString("status", "complete");
else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true))
response.setString("status", "pending");
else response.setString("status", "running");
});
}
Cursor activity = response.setObject("activity");
deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried",
instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten",
instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
DeploymentMetrics metrics = deployment.metrics();
Cursor metricsObject = response.setObject("metrics");
metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond());
metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond());
metricsObject.setDouble("documentCount", metrics.documentCount());
metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis());
metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli()));
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if ( ! applicationVersion.isUnknown()) {
object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong());
object.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if (revision.isEmpty()) return;
object.setString("gitRepository", revision.get().repository());
object.setString("gitBranch", revision.get().branch());
object.setString("gitCommit", revision.get().commit());
}
private void toSlime(RotationState state, Cursor object) {
Cursor bcpStatus = object.setObject("bcpStatus");
bcpStatus.setString("rotationStatus", rotationStateString(state));
}
private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) {
var array = object.setArray("endpointStatus");
for (var rotation : rotations) {
var statusObject = array.addObject();
var targets = status.of(rotation.rotationId());
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("rotationId", rotation.rotationId().asString());
statusObject.setString("clusterId", rotation.clusterId().value());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli());
}
}
private URI monitoringSystemUri(DeploymentId deploymentId) {
return controller.zoneRegistry().getMonitoringSystemUri(deploymentId);
}
/**
* Returns a non-broken, released version at least as old as the oldest platform the given application is on.
*
* If no known version is applicable, the newest version at least as old as the oldest platform is selected,
* among all versions released for this system. If no such versions exists, throws an IllegalStateException.
*/
private Version compileVersion(TenantAndApplicationId id) {
Version oldestPlatform = controller.applications().oldestInstalledPlatform(id);
VersionStatus versionStatus = controller.versionStatus();
return versionStatus.versions().stream()
.filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low))
.filter(VespaVersion::isReleased)
.map(VespaVersion::versionNumber)
.filter(version -> ! version.isAfter(oldestPlatform))
.max(Comparator.naturalOrder())
.orElseGet(() -> controller.mavenRepository().metadata().versions().stream()
.filter(version -> ! version.isAfter(oldestPlatform))
.filter(version -> ! versionStatus.versions().stream()
.map(VespaVersion::versionNumber)
.collect(Collectors.toSet()).contains(version))
.max(Comparator.naturalOrder())
.orElseThrow(() -> new IllegalStateException("No available releases of " +
controller.mavenRepository().artifactId())));
}
private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
ZoneId zone = ZoneId.from(environment, region);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
var deploymentId = new DeploymentId(instance.id(), zone);
setGlobalRotationStatus(deploymentId, inService, request);
setGlobalEndpointStatus(deploymentId, inService, request);
return new MessageResponse(String.format("Successfully set %s in %s %s service",
instance.id().toShortString(), zone, inService ? "in" : "out of"));
}
/** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */
private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
var status = inService ? GlobalRouting.Status.in : GlobalRouting.Status.out;
controller.routing().policies().setGlobalRoutingStatus(deployment, status, agent);
}
/** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */
private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var requestData = toSlime(request.getData()).get();
var reason = mandatory("reason", requestData).asString();
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
long timestamp = controller.clock().instant().getEpochSecond();
var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp);
controller.routing().setGlobalRotationStatus(deployment, endpointStatus);
}
private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Slime slime = new Slime();
Cursor array = slime.setObject().setArray("globalrotationoverride");
controller.routing().globalRotationStatus(deploymentId)
.forEach((endpoint, status) -> {
array.addString(endpoint.upstreamIdOf(deploymentId));
Cursor statusObject = array.addObject();
statusObject.setString("status", status.getStatus().name());
statusObject.setString("reason", status.getReason() == null ? "" : status.getReason());
statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent());
statusObject.setLong("timestamp", status.getEpoch());
});
return new SlimeJsonResponse(slime);
}
private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().requireInstance(applicationId);
ZoneId zone = ZoneId.from(environment, region);
RotationId rotation = findRotationId(instance, endpointId);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
Slime slime = new Slime();
Cursor response = slime.setObject();
toSlime(instance.rotationStatus().of(rotation, deployment), response);
return new SlimeJsonResponse(slime);
}
private HttpResponse metering(String tenant, String application, HttpRequest request) {
Slime slime = new Slime();
Cursor root = slime.setObject();
MeteringData meteringData = controller.serviceRegistry()
.meteringService()
.getMeteringData(TenantName.from(tenant), ApplicationName.from(application));
ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringData.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringData.getLastMonth();
Cursor lastmonth = root.setObject("lastmonth");
lastmonth.setDouble("cpu", lastMonth.getCpuCores());
lastmonth.setDouble("mem", lastMonth.getMemoryGb());
lastmonth.setDouble("disk", lastMonth.getDiskGb());
Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory();
Cursor details = root.setObject("details");
Cursor detailsCpu = details.setObject("cpu");
Cursor detailsMem = details.setObject("mem");
Cursor detailsDisk = details.setObject("disk");
history.entrySet().stream()
.forEach(entry -> {
String instanceName = entry.getKey().instance().value();
Cursor detailsCpuApp = detailsCpu.setObject(instanceName);
Cursor detailsMemApp = detailsMem.setObject(instanceName);
Cursor detailsDiskApp = detailsDisk.setObject(instanceName);
Cursor detailsCpuData = detailsCpuApp.setArray("data");
Cursor detailsMemData = detailsMemApp.setArray("data");
Cursor detailsDiskData = detailsDiskApp.setArray("data");
entry.getValue().stream()
.forEach(resourceSnapshot -> {
Cursor cpu = detailsCpuData.addObject();
cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
cpu.setDouble("value", resourceSnapshot.getCpuCores());
Cursor mem = detailsMemData.addObject();
mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
mem.setDouble("value", resourceSnapshot.getMemoryGb());
Cursor disk = detailsDiskData.addObject();
disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
disk.setDouble("value", resourceSnapshot.getDiskGb());
});
});
return new SlimeJsonResponse(slime);
}
private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! instance.change().isEmpty()) {
instance.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", instance.change().isPinned());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
boolean suspended = controller.applications().isSuspended(deploymentId);
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setBool("suspended", suspended);
return new SlimeJsonResponse(slime);
}
private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region);
ServiceApiResponse response = new ServiceApiResponse(ZoneId.from(environment, region),
new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(),
controller.zoneRegistry().getConfigServerApiUris(ZoneId.from(environment, region)),
request.getUri());
response.setResponse(applicationView);
return response;
}
private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), ZoneId.from(environment, region));
if ("container-clustercontroller".equals((serviceName)) && restPath.contains("/status/")) {
String result = controller.serviceRegistry().configServer().getClusterControllerStatus(deploymentId, restPath);
return new HtmlResponse(result);
}
Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath);
ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(),
deploymentId.applicationId(),
controller.zoneRegistry().getConfigServerApiUris(deploymentId.zoneId()),
request.getUri());
response.setResponse(result, serviceName, restPath);
return response;
}
private HttpResponse updateTenant(String tenantName, HttpRequest request) {
getTenantOrThrow(tenantName);
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().update(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createTenant(String tenantName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().create(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest());
com.yahoo.vespa.hosted.controller.Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
if (controller.applications().getApplication(applicationId).isEmpty())
createApplication(tenantName, applicationName, request);
controller.applications().createInstance(applicationId.instance(instanceName));
Slime slime = new Slime();
toSlime(applicationId.instance(instanceName), slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
/** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */
private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) {
request = controller.auditLogger().log(request);
String versionString = readToString(request.getData());
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Version version = Version.fromString(versionString);
if (version.equals(Version.emptyVersion))
version = controller.systemVersion();
if ( ! systemHasVersion(version))
throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " +
"Version is not active in this system. " +
"Active versions: " + controller.versionStatus().versions()
.stream()
.map(VespaVersion::versionNumber)
.map(Version::toString)
.collect(joining(", ")));
Change change = Change.of(version);
if (pin)
change = change.withPin();
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Trigger deployment to the last known application package for the given application. */
private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) {
controller.auditLogger().log(request);
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */
private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = application.get().require(id.instance()).change();
if (change.isEmpty()) {
response.append("No deployment in progress for ").append(id).append(" at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Schedule restart of deployment, or specific host in a deployment */
private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
RestartFilter restartFilter = new RestartFilter()
.withHostName(Optional.ofNullable(request.getProperty("hostname")).map(HostName::from))
.withClusterType(Optional.ofNullable(request.getProperty("clusterType")).map(ClusterSpec.Type::from))
.withClusterId(Optional.ofNullable(request.getProperty("clusterId")).map(ClusterSpec.Id::from));
controller.applications().restart(deploymentId, restartFilter);
return new MessageResponse("Requested restart of " + deploymentId);
}
private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) {
if ( ! type.environment().isManuallyDeployed() && ! isOperator(request))
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("applicationZip"))
throw new IllegalArgumentException("Missing required form part 'applicationZip'");
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(id.tenant(),
Optional.of(id.instance()),
Optional.of(type.zone(controller.system())),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions"))
.map(json -> SlimeUtils.jsonToSlime(json).get())
.flatMap(options -> optional("vespaVersion", options))
.map(Version::fromString);
controller.jobController().deploy(id, type, version, applicationPackage);
RunId runId = controller.jobController().last(id, type).get().id();
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("message", "Deployment started in " + runId +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<com.yahoo.vespa.hosted.controller.Application> application = controller.applications().getApplication(TenantAndApplicationId.from(applicationId));
Inspector sourceRevision = deployOptions.field("sourceRevision");
Inspector buildNumber = deployOptions.field("buildNumber");
if (sourceRevision.valid() != buildNumber.valid())
throw new IllegalArgumentException("Source revision and build number must both be provided, or not");
Optional<ApplicationVersion> applicationVersion = Optional.empty();
if (sourceRevision.valid()) {
if (applicationPackage.isPresent())
throw new IllegalArgumentException("Application version and application package can't both be provided.");
applicationVersion = Optional.of(ApplicationVersion.from(toSourceRevision(sourceRevision),
buildNumber.asLong()));
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
boolean deployDirectly = deployOptions.field("deployDirectly").asBool();
Optional<Version> vespaVersion = optional("vespaVersion", deployOptions).map(Version::new);
if (deployDirectly && applicationPackage.isEmpty() && applicationVersion.isEmpty() && vespaVersion.isEmpty()) {
Optional<Deployment> deployment = controller.applications().getInstance(applicationId)
.map(Instance::deployments)
.flatMap(deployments -> Optional.ofNullable(deployments.get(zone)));
if(deployment.isEmpty())
throw new IllegalArgumentException("Can't redeploy application, no deployment currently exist");
ApplicationVersion version = deployment.get().applicationVersion();
if(version.isUnknown())
throw new IllegalArgumentException("Can't redeploy application, application version is unknown");
applicationVersion = Optional.of(version);
vespaVersion = Optional.of(deployment.get().version());
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
Optional.of(applicationId.instance()),
Optional.of(zone),
aPackage,
Optional.of(requireUserPrincipal(request))));
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass);
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if (tenant.isEmpty())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
controller.tenants().delete(tenant.get().name(),
accessControlRequests.credentials(tenant.get().name(),
toSlime(request.getData()).get(),
request.getJDiscRequest()));
return tenant(tenant.get(), request);
}
private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
return new MessageResponse("Deleted application " + id);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty()) {
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
}
return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
controller.applications().deactivate(id.applicationId(), id.zoneId());
return new MessageResponse("Deactivated " + id);
}
/** Returns test config for indicated job, with production deployments of the default instance. */
private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
HashSet<DeploymentId> deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toCollection(HashSet::new));
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.routing().zoneEndpointsOf(deployments),
controller.applications().contentClustersByZone(deployments)));
}
private static SourceRevision toSourceRevision(Inspector object) {
if (!object.field("repository").valid() ||
!object.field("branch").valid() ||
!object.field("commit").valid()) {
throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\".");
}
return new SourceRevision(object.field("repository").asString(),
object.field("branch").asString(),
object.field("commit").asString());
}
private Tenant getTenantOrThrow(String tenantName) {
return controller.tenants().get(tenantName)
.orElseThrow(() -> new NotExistsException(new TenantId(tenantName)));
}
private void toSlime(Cursor object, Tenant tenant, HttpRequest request) {
object.setString("tenant", tenant.name().value());
object.setString("type", tenantType(tenant));
List<com.yahoo.vespa.hosted.controller.Application> applications = controller.applications().asList(tenant.name());
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
object.setString("athensDomain", athenzTenant.domain().getName());
object.setString("property", athenzTenant.property().id());
athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString()));
athenzTenant.contact().ifPresent(c -> {
object.setString("propertyUrl", c.propertyUrl().toString());
object.setString("contactsUrl", c.url().toString());
object.setString("issueCreationUrl", c.issueTrackerUrl().toString());
Cursor contactsArray = object.setArray("contacts");
c.persons().forEach(persons -> {
Cursor personArray = contactsArray.addArray();
persons.forEach(personArray::addString);
});
});
break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
cloudTenant.creator().ifPresent(creator -> object.setString("creator", creator.getName()));
Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys");
cloudTenant.developerKeys().forEach((key, user) -> {
Cursor keyObject = pemDeveloperKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", user.getName());
});
break;
}
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
Cursor applicationArray = object.setArray("applications");
for (com.yahoo.vespa.hosted.controller.Application application : applications) {
DeploymentStatus status = controller.jobController().deploymentStatus(application);
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, status, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
}
private void toSlime(ClusterResources resources, Cursor object) {
object.setLong("nodes", resources.nodes());
object.setLong("groups", resources.groups());
toSlime(resources.nodeResources(), object.setObject("nodeResources"));
if ( ! controller.zoneRegistry().system().isPublic())
object.setDouble("cost", Math.round(resources.nodes() * resources.nodeResources().cost() * 100.0 / 3.0) / 100.0);
}
private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", valueOf(resources.diskSpeed()));
object.setString("storageType", valueOf(resources.storageType()));
}
private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) {
object.setString("tenant", tenant.name().value());
Cursor metaData = object.setObject("metaData");
metaData.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
metaData.setString("athensDomain", athenzTenant.domain().getName());
metaData.setString("property", athenzTenant.property().id());
break;
case cloud: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString());
}
/** Returns a copy of the given URI with the host and port from the given URI, the path set to the given path and the query set to given query*/
private URI withPathAndQuery(String newPath, String newQuery, URI uri) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, newQuery, null);
}
catch (URISyntaxException e) {
throw new RuntimeException("Will not happen", e);
}
}
/** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */
private URI withPath(String newPath, URI uri) {
return withPathAndQuery(newPath, null, uri);
}
private long asLong(String valueOrNull, long defaultWhenNull) {
if (valueOrNull == null) return defaultWhenNull;
try {
return Long.parseLong(valueOrNull);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'");
}
}
private void toSlime(Run run, Cursor object) {
object.setLong("id", run.id().number());
object.setString("version", run.versions().targetPlatform().toFullString());
if ( ! run.versions().targetApplication().isUnknown())
toSlime(run.versions().targetApplication(), object.setObject("revision"));
object.setString("reason", "unknown reason");
object.setLong("at", run.end().orElse(run.start()).toEpochMilli());
}
private Slime toSlime(InputStream jsonStream) {
try {
byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000);
return SlimeUtils.jsonToSlime(jsonBytes);
} catch (IOException e) {
throw new RuntimeException();
}
}
private static Principal requireUserPrincipal(HttpRequest request) {
Principal principal = request.getJDiscRequest().getUserPrincipal();
if (principal == null) throw new InternalServerErrorException("Expected a user principal");
return principal;
}
private Inspector mandatory(String key, Inspector object) {
if ( ! object.field(key).valid())
throw new IllegalArgumentException("'" + key + "' is missing");
return object.field(key);
}
private Optional<String> optional(String key, Inspector object) {
return SlimeUtils.optionalString(object.field(key));
}
private static String path(Object... elements) {
return Joiner.on("/").join(elements);
}
private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value(),
request.getUri()).toString());
}
private void toSlime(ApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value() +
"/instance/" + id.instance().value(),
request.getUri()).toString());
}
private Slime toSlime(ActivateResult result) {
Slime slime = new Slime();
Cursor object = slime.setObject();
object.setString("revisionId", result.revisionId().id());
object.setLong("applicationZipSize", result.applicationZipSizeBytes());
Cursor logArray = object.setArray("prepareMessages");
if (result.prepareResponse().log != null) {
for (Log logMessage : result.prepareResponse().log) {
Cursor logObject = logArray.addObject();
logObject.setLong("time", logMessage.time);
logObject.setString("level", logMessage.level);
logObject.setString("message", logMessage.message);
}
}
Cursor changeObject = object.setObject("configChangeActions");
Cursor restartActionsArray = changeObject.setArray("restart");
for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) {
Cursor restartActionObject = restartActionsArray.addObject();
restartActionObject.setString("clusterName", restartAction.clusterName);
restartActionObject.setString("clusterType", restartAction.clusterType);
restartActionObject.setString("serviceType", restartAction.serviceType);
serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services"));
stringsToSlime(restartAction.messages, restartActionObject.setArray("messages"));
}
Cursor refeedActionsArray = changeObject.setArray("refeed");
for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) {
Cursor refeedActionObject = refeedActionsArray.addObject();
refeedActionObject.setString("name", refeedAction.name);
refeedActionObject.setBool("allowed", refeedAction.allowed);
refeedActionObject.setString("documentType", refeedAction.documentType);
refeedActionObject.setString("clusterName", refeedAction.clusterName);
serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services"));
stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages"));
}
return slime;
}
private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) {
for (ServiceInfo serviceInfo : serviceInfoList) {
Cursor serviceInfoObject = array.addObject();
serviceInfoObject.setString("serviceName", serviceInfo.serviceName);
serviceInfoObject.setString("serviceType", serviceInfo.serviceType);
serviceInfoObject.setString("configId", serviceInfo.configId);
serviceInfoObject.setString("hostName", serviceInfo.hostName);
}
}
private void stringsToSlime(List<String> strings, Cursor array) {
for (String string : strings)
array.addString(string);
}
private String readToString(InputStream stream) {
Scanner scanner = new Scanner(stream).useDelimiter("\\A");
if ( ! scanner.hasNext()) return null;
return scanner.next();
}
private boolean systemHasVersion(Version version) {
return controller.versionStatus().versions().stream().anyMatch(v -> v.versionNumber().equals(version));
}
private static boolean recurseOverTenants(HttpRequest request) {
return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive"));
}
private static boolean recurseOverApplications(HttpRequest request) {
return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive"));
}
private static boolean recurseOverDeployments(HttpRequest request) {
return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive"));
}
private static boolean showOnlyProductionInstances(HttpRequest request) {
return "true".equals(request.getProperty("production"));
}
private static String tenantType(Tenant tenant) {
switch (tenant.type()) {
case athenz: return "ATHENS";
case cloud: return "CLOUD";
default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName());
}
}
private static ApplicationId appIdFromPath(Path path) {
return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance"));
}
private static JobType jobTypeFromPath(Path path) {
return JobType.fromJobName(path.get("jobtype"));
}
private static RunId runIdFromPath(Path path) {
long number = Long.parseLong(path.get("number"));
return new RunId(appIdFromPath(path), jobTypeFromPath(path), number);
}
private HttpResponse submit(String tenant, String application, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
Optional<String> repository = optional("repository", submitOptions);
Optional<String> branch = optional("branch", submitOptions);
Optional<String> commit = optional("commit", submitOptions);
Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent()
? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get()))
: Optional.empty();
Optional<String> sourceUrl = optional("sourceUrl", submitOptions);
Optional<String> authorEmail = optional("authorEmail", submitOptions);
sourceUrl.map(URI::create).ifPresent(url -> {
if (url.getHost() == null || url.getScheme() == null)
throw new IllegalArgumentException("Source URL must include scheme and host");
});
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true);
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
Optional.empty(),
Optional.empty(),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
sourceUrl,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
private HttpResponse removeAllProdDeployments(String tenant, String application) {
JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application,
Optional.empty(), Optional.empty(), Optional.empty(), 1,
ApplicationPackage.deploymentRemoval(), new byte[0]);
return new MessageResponse("All deployments removed");
}
private static Map<String, byte[]> parseDataParts(HttpRequest request) {
String contentHash = request.getHeader("x-Content-Hash");
if (contentHash == null)
return new MultipartParser().parse(request);
DigestInputStream digester = Signatures.sha256Digester(request.getData());
var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri());
if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash)))
throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash");
return dataParts;
}
private static RotationId findRotationId(Instance instance, Optional<String> endpointId) {
if (instance.rotations().isEmpty()) {
throw new NotExistsException("global rotation does not exist for " + instance);
}
if (endpointId.isPresent()) {
return instance.rotations().stream()
.filter(r -> r.endpointId().id().equals(endpointId.get()))
.map(AssignedRotation::rotationId)
.findFirst()
.orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() +
" does not exist for " + instance));
} else if (instance.rotations().size() > 1) {
throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given");
}
return instance.rotations().get(0).rotationId();
}
private static String rotationStateString(RotationState state) {
switch (state) {
case in: return "IN";
case out: return "OUT";
}
return "UNKNOWN";
}
private static String endpointScopeString(Endpoint.Scope scope) {
switch (scope) {
case region: return "region";
case global: return "global";
case zone: return "zone";
}
throw new IllegalArgumentException("Unknown endpoint scope " + scope);
}
private static String routingMethodString(RoutingMethod method) {
switch (method) {
case exclusive: return "exclusive";
case shared: return "shared";
case sharedLayer4: return "sharedLayer4";
}
throw new IllegalArgumentException("Unknown routing method " + method);
}
private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) {
return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName))
.filter(cls::isInstance)
.map(cls::cast)
.orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request"));
}
/** Returns whether given request is by an operator */
private static boolean isOperator(HttpRequest request) {
var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class);
return securityContext.roles().stream()
.map(Role::definition)
.anyMatch(definition -> definition == RoleDefinition.hostedOperator);
}
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestConfigSerializer testConfigSerializer;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
}
@Override
public Duration getTimeout() {
return Duration.ofMinutes(20);
}
@Override
public HttpResponse handle(HttpRequest request) {
try {
Path path = new Path(request.getUri(), OPTIONAL_PREFIX);
switch (request.getMethod()) {
case GET: return handleGET(path, request);
case PUT: return handlePUT(path, request);
case POST: return handlePOST(path, request);
case PATCH: return handlePATCH(path, request);
case DELETE: return handleDELETE(path, request);
case OPTIONS: return handleOPTIONS();
default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
}
}
catch (ForbiddenException e) {
return ErrorResponse.forbidden(Exceptions.toMessageString(e));
}
catch (NotAuthorizedException e) {
return ErrorResponse.unauthorized(Exceptions.toMessageString(e));
}
catch (NotExistsException e) {
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
}
catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
catch (ConfigServerException e) {
switch (e.getErrorCode()) {
case NOT_FOUND:
return new ErrorResponse(NOT_FOUND, e.getErrorCode().name(), Exceptions.toMessageString(e));
case ACTIVATION_CONFLICT:
return new ErrorResponse(CONFLICT, e.getErrorCode().name(), Exceptions.toMessageString(e));
case INTERNAL_SERVER_ERROR:
return new ErrorResponse(INTERNAL_SERVER_ERROR, e.getErrorCode().name(), Exceptions.toMessageString(e));
default:
return new ErrorResponse(BAD_REQUEST, e.getErrorCode().name(), Exceptions.toMessageString(e));
}
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/tenant")) return tenants(request);
if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/metrics")) return metrics(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePUT(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePATCH(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleDELETE(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeAllProdDeployments(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleOPTIONS() {
EmptyResponse response = new EmptyResponse();
response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS");
return response;
}
private HttpResponse recursiveRoot(HttpRequest request) {
Slime slime = new Slime();
Cursor tenantArray = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
toSlime(tenantArray.addObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse root(HttpRequest request) {
return recurseOverTenants(request)
? recursiveRoot(request)
: new ResourceResponse(request, "tenant");
}
private HttpResponse tenants(HttpRequest request) {
Slime slime = new Slime();
Cursor response = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject());
return new SlimeJsonResponse(slime);
}
private HttpResponse tenant(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenant(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenant(Tenant tenant, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
if (controller.tenants().get(tenantName).isEmpty())
return ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist");
Slime slime = new Slime();
Cursor applicationArray = slime.setArray();
for (com.yahoo.vespa.hosted.controller.Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true)) {
Cursor applicationObject = applicationArray.addObject();
applicationObject.setString("tenant", application.id().tenant().value());
applicationObject.setString("application", application.id().application().value());
applicationObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value(),
request.getUri()).toString());
Cursor instanceArray = applicationObject.setArray("instances");
for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet()
: application.instances().keySet()) {
Cursor instanceObject = instanceArray.addObject();
instanceObject.setString("instance", instance.value());
instanceObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/instance/" + instance.value(),
request.getUri()).toString());
}
}
}
return new SlimeJsonResponse(slime);
}
private HttpResponse devApplicationPackage(ApplicationId id, JobType type) {
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Only manually deployed zones have dev packages");
ZoneId zone = type.zone(controller.system());
byte[] applicationPackage = controller.applications().applicationStore().getDev(id, zone);
return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage);
}
private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse compileVersion(String tenantName, String applicationName) {
Slime slime = new Slime();
slime.setObject().setString("compileVersion",
compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString());
return new SlimeJsonResponse(slime);
}
private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
Principal user = request.getJDiscRequest().getUserPrincipal();
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withDeveloperKey(developerKey, user);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Principal user = ((CloudTenant) controller.tenants().require(TenantName.from(tenantName))).developerKeys().get(developerKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withoutDeveloperKey(developerKey);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) {
keys.forEach((key, principal) -> {
Cursor keyObject = keysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", principal.getName());
});
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withoutDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes.");
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
Inspector majorVersionField = requestObject.field("majorVersion");
if (majorVersionField.valid()) {
Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong();
application = application.withMajorVersion(majorVersion);
messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion));
}
Inspector pemDeployKeyField = requestObject.field("pemDeployKey");
if (pemDeployKeyField.valid()) {
String pemDeployKey = pemDeployKeyField.asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
application = application.withDeployKey(deployKey);
messageBuilder.add("Added deploy key " + pemDeployKey);
}
controller.applications().store(application);
});
return new MessageResponse(messageBuilder.toString());
}
private com.yahoo.vespa.hosted.controller.Application getApplication(String tenantName, String applicationName) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
return controller.applications().getApplication(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private Instance getInstance(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
return controller.applications().getInstance(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, id);
Slime slime = new Slime();
Cursor nodesArray = slime.setObject().setArray("nodes");
for (Node node : nodes) {
Cursor nodeObject = nodesArray.addObject();
nodeObject.setString("hostname", node.hostname().value());
nodeObject.setString("state", valueOf(node.state()));
node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.flavor());
toSlime(node.resources(), nodeObject);
nodeObject.setBool("fastDisk", node.resources().diskSpeed() == NodeResources.DiskSpeed.fast);
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
return new SlimeJsonResponse(slime);
}
private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id);
Slime slime = new Slime();
Cursor clustersObject = slime.setObject().setObject("clusters");
for (Cluster cluster : application.clusters().values()) {
Cursor clusterObject = clustersObject.setObject(cluster.id().value());
toSlime(cluster.min(), clusterObject.setObject("min"));
toSlime(cluster.max(), clusterObject.setObject("max"));
toSlime(cluster.current(), clusterObject.setObject("current"));
cluster.target().ifPresent(target -> toSlime(target, clusterObject.setObject("target")));
cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested")));
}
return new SlimeJsonResponse(slime);
}
private static String valueOf(Node.State state) {
switch (state) {
case failed: return "failed";
case parked: return "parked";
case dirty: return "dirty";
case ready: return "ready";
case active: return "active";
case inactive: return "inactive";
case reserved: return "reserved";
case provisioned: return "provisioned";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ServiceState state) {
switch (state) {
case expectedUp: return "expectedUp";
case allowedDown: return "allowedDown";
case unorchestrated: return "unorchestrated";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ClusterType type) {
switch (type) {
case admin: return "admin";
case content: return "content";
case container: return "container";
case combined: return "combined";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
private static String valueOf(NodeResources.DiskSpeed diskSpeed) {
switch (diskSpeed) {
case fast : return "fast";
case slow : return "slow";
case any : return "any";
default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'");
}
}
private static String valueOf(NodeResources.StorageType storageType) {
switch (storageType) {
case remote : return "remote";
case local : return "local";
case any : return "any";
default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'");
}
}
private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters);
return new HttpResponse(200) {
@Override
public void render(OutputStream outputStream) throws IOException {
logStream.transferTo(outputStream);
}
};
}
private HttpResponse metrics(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
List<ProtonMetrics> protonMetrics = controller.serviceRegistry().configServer().getProtonMetrics(deployment);
return buildResponseFromProtonMetrics(protonMetrics);
}
private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
boolean requireTests = ! requestObject.field("skipTests").asBool();
boolean reTrigger = requestObject.field("reTrigger").asBool();
String triggered = reTrigger
? controller.applications().deploymentTrigger()
.reTrigger(id, type).type().jobName()
: controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests)
.stream().map(job -> job.type().jobName()).collect(joining(", "));
return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered"
: "Triggered " + triggered + " for " + id);
}
private HttpResponse pause(ApplicationId id, JobType type) {
Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause);
controller.applications().deploymentTrigger().pauseJob(id, type, until);
return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause);
}
private HttpResponse resume(ApplicationId id, JobType type) {
controller.applications().deploymentTrigger().resumeJob(id, type);
return new MessageResponse(type.jobName() + " for " + id + " resumed");
}
private void toSlime(Cursor object, com.yahoo.vespa.hosted.controller.Application application, HttpRequest request) {
object.setString("tenant", application.id().tenant().value());
object.setString("application", application.id().application().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/job/",
request.getUri()).toString());
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
application.instances().values().stream().findFirst().ifPresent(instance -> {
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
});
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request);
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
if (deploymentSpec.instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec.requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
globalEndpointsToSlime(object, instance);
List<Deployment> deployments = deploymentSpec.instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor deploymentsArray = object.setArray("deployments");
for (Deployment deployment : deployments) {
Cursor deploymentObject = deploymentsArray.addObject();
if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty())
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/instance/" + instance.name().value() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
}
private void globalEndpointsToSlime(Cursor object, Instance instance) {
var globalEndpointUrls = new LinkedHashSet<String>();
controller.routing().endpointsOf(instance.id())
.requiresRotation()
.not().legacy()
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalEndpointUrls::add);
var globalRotationsArray = object.setArray("globalRotations");
globalEndpointUrls.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
}
private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) {
com.yahoo.vespa.hosted.controller.Application application = status.application();
object.setString("tenant", instance.id().tenant().value());
object.setString("application", instance.id().application().value());
object.setString("instance", instance.id().instance().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + instance.id().tenant().value() +
"/application/" + instance.id().application().value() +
"/instance/" + instance.id().instance().value() + "/job/",
request.getUri()).toString());
application.latestVersion().ifPresent(version -> {
sourceRevisionToSlime(version.source(), object.setObject("source"));
version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
version.commit().ifPresent(commit -> object.setString("commit", commit));
});
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if (application.deploymentSpec().instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec().requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
globalEndpointsToSlime(object, instance);
List<Deployment> deployments =
application.deploymentSpec().instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor instancesArray = object.setArray("instances");
for (Deployment deployment : deployments) {
Cursor deploymentObject = instancesArray.addObject();
if (deployment.zone().environment() == Environment.prod) {
if (instance.rotations().size() == 1) {
toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment),
deploymentObject);
}
if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) {
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
}
}
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("instance", instance.id().instance().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
status.jobSteps().keySet().stream()
.filter(job -> job.application().instance().equals(instance.name()))
.filter(job -> job.type().isProduction() && job.type().isDeployment())
.map(job -> job.type().zone(controller.system()))
.filter(zone -> ! instance.deployments().containsKey(zone))
.forEach(zone -> {
Cursor deploymentObject = instancesArray.addObject();
deploymentObject.setString("environment", zone.environment().value());
deploymentObject.setString("region", zone.region().value());
});
application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key)));
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().getInstance(id)
.orElseThrow(() -> new NotExistsException(id + " not found"));
DeploymentId deploymentId = new DeploymentId(instance.id(),
ZoneId.from(environment, region));
Deployment deployment = instance.deployments().get(deploymentId.zoneId());
if (deployment == null)
throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId());
Slime slime = new Slime();
toSlime(slime.setObject(), deploymentId, deployment, request);
return new SlimeJsonResponse(slime);
}
private void toSlime(Cursor object, Change change) {
change.platform().ifPresent(version -> object.setString("version", version.toString()));
change.application()
.filter(version -> !version.isUnknown())
.ifPresent(version -> toSlime(version, object.setObject("revision")));
}
private void toSlime(Endpoint endpoint, Cursor object) {
object.setString("cluster", endpoint.cluster().value());
object.setBool("tls", endpoint.tls());
object.setString("url", endpoint.url().toString());
object.setString("scope", endpointScopeString(endpoint.scope()));
object.setString("routingMethod", routingMethodString(endpoint.routingMethod()));
}
private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) {
response.setString("tenant", deploymentId.applicationId().tenant().value());
response.setString("application", deploymentId.applicationId().application().value());
response.setString("instance", deploymentId.applicationId().instance().value());
response.setString("environment", deploymentId.zoneId().environment().value());
response.setString("region", deploymentId.zoneId().region().value());
var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId()));
var endpointArray = response.setArray("endpoints");
for (var endpoint : controller.routing().endpointsOf(deploymentId)
.scope(Endpoint.Scope.zone)
.not().legacy()) {
toSlime(endpoint, endpointArray.addObject());
}
var globalEndpoints = controller.routing().endpointsOf(application, deploymentId.applicationId().instance())
.not().legacy()
.targets(deploymentId.zoneId());
for (var endpoint : globalEndpoints) {
toSlime(endpoint, endpointArray.addObject());
}
response.setString("nodes", withPathAndQuery("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/", "recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString());
response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString());
response.setString("version", deployment.version().toFullString());
response.setString("revision", deployment.applicationVersion().id());
response.setLong("deployTimeEpochMs", deployment.at().toEpochMilli());
controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId())
.ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", deployment.at().plus(deploymentTimeToLive).toEpochMilli()));
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
var instance = application.instances().get(deploymentId.applicationId().instance());
if (instance != null) {
if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod)
toSlime(instance.rotations(), instance.rotationStatus(), deployment, response);
JobType.from(controller.system(), deployment.zone())
.map(type -> new JobId(instance.id(), type))
.map(status.jobSteps()::get)
.ifPresent(stepStatus -> {
JobControllerApiHandlerHelper.applicationVersionToSlime(
response.setObject("applicationVersion"), deployment.applicationVersion());
if (!status.jobsToRun().containsKey(stepStatus.job().get()))
response.setString("status", "complete");
else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true))
response.setString("status", "pending");
else response.setString("status", "running");
});
}
Cursor activity = response.setObject("activity");
deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried",
instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten",
instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
DeploymentMetrics metrics = deployment.metrics();
Cursor metricsObject = response.setObject("metrics");
metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond());
metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond());
metricsObject.setDouble("documentCount", metrics.documentCount());
metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis());
metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli()));
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if ( ! applicationVersion.isUnknown()) {
object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong());
object.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if (revision.isEmpty()) return;
object.setString("gitRepository", revision.get().repository());
object.setString("gitBranch", revision.get().branch());
object.setString("gitCommit", revision.get().commit());
}
private void toSlime(RotationState state, Cursor object) {
Cursor bcpStatus = object.setObject("bcpStatus");
bcpStatus.setString("rotationStatus", rotationStateString(state));
}
private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) {
var array = object.setArray("endpointStatus");
for (var rotation : rotations) {
var statusObject = array.addObject();
var targets = status.of(rotation.rotationId());
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("rotationId", rotation.rotationId().asString());
statusObject.setString("clusterId", rotation.clusterId().value());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli());
}
}
private URI monitoringSystemUri(DeploymentId deploymentId) {
return controller.zoneRegistry().getMonitoringSystemUri(deploymentId);
}
/**
* Returns a non-broken, released version at least as old as the oldest platform the given application is on.
*
* If no known version is applicable, the newest version at least as old as the oldest platform is selected,
* among all versions released for this system. If no such versions exists, throws an IllegalStateException.
*/
private Version compileVersion(TenantAndApplicationId id) {
Version oldestPlatform = controller.applications().oldestInstalledPlatform(id);
VersionStatus versionStatus = controller.versionStatus();
return versionStatus.versions().stream()
.filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low))
.filter(VespaVersion::isReleased)
.map(VespaVersion::versionNumber)
.filter(version -> ! version.isAfter(oldestPlatform))
.max(Comparator.naturalOrder())
.orElseGet(() -> controller.mavenRepository().metadata().versions().stream()
.filter(version -> ! version.isAfter(oldestPlatform))
.filter(version -> ! versionStatus.versions().stream()
.map(VespaVersion::versionNumber)
.collect(Collectors.toSet()).contains(version))
.max(Comparator.naturalOrder())
.orElseThrow(() -> new IllegalStateException("No available releases of " +
controller.mavenRepository().artifactId())));
}
private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
ZoneId zone = ZoneId.from(environment, region);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
var deploymentId = new DeploymentId(instance.id(), zone);
setGlobalRotationStatus(deploymentId, inService, request);
setGlobalEndpointStatus(deploymentId, inService, request);
return new MessageResponse(String.format("Successfully set %s in %s %s service",
instance.id().toShortString(), zone, inService ? "in" : "out of"));
}
/** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */
private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
var status = inService ? GlobalRouting.Status.in : GlobalRouting.Status.out;
controller.routing().policies().setGlobalRoutingStatus(deployment, status, agent);
}
/** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */
private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var requestData = toSlime(request.getData()).get();
var reason = mandatory("reason", requestData).asString();
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
long timestamp = controller.clock().instant().getEpochSecond();
var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp);
controller.routing().setGlobalRotationStatus(deployment, endpointStatus);
}
private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Slime slime = new Slime();
Cursor array = slime.setObject().setArray("globalrotationoverride");
controller.routing().globalRotationStatus(deploymentId)
.forEach((endpoint, status) -> {
array.addString(endpoint.upstreamIdOf(deploymentId));
Cursor statusObject = array.addObject();
statusObject.setString("status", status.getStatus().name());
statusObject.setString("reason", status.getReason() == null ? "" : status.getReason());
statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent());
statusObject.setLong("timestamp", status.getEpoch());
});
return new SlimeJsonResponse(slime);
}
private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().requireInstance(applicationId);
ZoneId zone = ZoneId.from(environment, region);
RotationId rotation = findRotationId(instance, endpointId);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
Slime slime = new Slime();
Cursor response = slime.setObject();
toSlime(instance.rotationStatus().of(rotation, deployment), response);
return new SlimeJsonResponse(slime);
}
private HttpResponse metering(String tenant, String application, HttpRequest request) {
Slime slime = new Slime();
Cursor root = slime.setObject();
MeteringData meteringData = controller.serviceRegistry()
.meteringService()
.getMeteringData(TenantName.from(tenant), ApplicationName.from(application));
ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringData.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringData.getLastMonth();
Cursor lastmonth = root.setObject("lastmonth");
lastmonth.setDouble("cpu", lastMonth.getCpuCores());
lastmonth.setDouble("mem", lastMonth.getMemoryGb());
lastmonth.setDouble("disk", lastMonth.getDiskGb());
Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory();
Cursor details = root.setObject("details");
Cursor detailsCpu = details.setObject("cpu");
Cursor detailsMem = details.setObject("mem");
Cursor detailsDisk = details.setObject("disk");
history.entrySet().stream()
.forEach(entry -> {
String instanceName = entry.getKey().instance().value();
Cursor detailsCpuApp = detailsCpu.setObject(instanceName);
Cursor detailsMemApp = detailsMem.setObject(instanceName);
Cursor detailsDiskApp = detailsDisk.setObject(instanceName);
Cursor detailsCpuData = detailsCpuApp.setArray("data");
Cursor detailsMemData = detailsMemApp.setArray("data");
Cursor detailsDiskData = detailsDiskApp.setArray("data");
entry.getValue().stream()
.forEach(resourceSnapshot -> {
Cursor cpu = detailsCpuData.addObject();
cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
cpu.setDouble("value", resourceSnapshot.getCpuCores());
Cursor mem = detailsMemData.addObject();
mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
mem.setDouble("value", resourceSnapshot.getMemoryGb());
Cursor disk = detailsDiskData.addObject();
disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
disk.setDouble("value", resourceSnapshot.getDiskGb());
});
});
return new SlimeJsonResponse(slime);
}
private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! instance.change().isEmpty()) {
instance.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", instance.change().isPinned());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
boolean suspended = controller.applications().isSuspended(deploymentId);
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setBool("suspended", suspended);
return new SlimeJsonResponse(slime);
}
private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region);
ServiceApiResponse response = new ServiceApiResponse(ZoneId.from(environment, region),
new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(),
controller.zoneRegistry().getConfigServerApiUris(ZoneId.from(environment, region)),
request.getUri());
response.setResponse(applicationView);
return response;
}
private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), ZoneId.from(environment, region));
if ("container-clustercontroller".equals((serviceName)) && restPath.contains("/status/")) {
String result = controller.serviceRegistry().configServer().getClusterControllerStatus(deploymentId, restPath);
return new HtmlResponse(result);
}
Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath);
ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(),
deploymentId.applicationId(),
controller.zoneRegistry().getConfigServerApiUris(deploymentId.zoneId()),
request.getUri());
response.setResponse(result, serviceName, restPath);
return response;
}
private HttpResponse updateTenant(String tenantName, HttpRequest request) {
getTenantOrThrow(tenantName);
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().update(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createTenant(String tenantName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().create(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest());
com.yahoo.vespa.hosted.controller.Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
if (controller.applications().getApplication(applicationId).isEmpty())
createApplication(tenantName, applicationName, request);
controller.applications().createInstance(applicationId.instance(instanceName));
Slime slime = new Slime();
toSlime(applicationId.instance(instanceName), slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
/** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */
private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) {
request = controller.auditLogger().log(request);
String versionString = readToString(request.getData());
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Version version = Version.fromString(versionString);
if (version.equals(Version.emptyVersion))
version = controller.systemVersion();
if ( ! systemHasVersion(version))
throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " +
"Version is not active in this system. " +
"Active versions: " + controller.versionStatus().versions()
.stream()
.map(VespaVersion::versionNumber)
.map(Version::toString)
.collect(joining(", ")));
Change change = Change.of(version);
if (pin)
change = change.withPin();
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Trigger deployment to the last known application package for the given application. */
private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) {
controller.auditLogger().log(request);
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */
private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = application.get().require(id.instance()).change();
if (change.isEmpty()) {
response.append("No deployment in progress for ").append(id).append(" at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Schedule restart of deployment, or specific host in a deployment */
private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
RestartFilter restartFilter = new RestartFilter()
.withHostName(Optional.ofNullable(request.getProperty("hostname")).map(HostName::from))
.withClusterType(Optional.ofNullable(request.getProperty("clusterType")).map(ClusterSpec.Type::from))
.withClusterId(Optional.ofNullable(request.getProperty("clusterId")).map(ClusterSpec.Id::from));
controller.applications().restart(deploymentId, restartFilter);
return new MessageResponse("Requested restart of " + deploymentId);
}
private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) {
if ( ! type.environment().isManuallyDeployed() && ! isOperator(request))
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("applicationZip"))
throw new IllegalArgumentException("Missing required form part 'applicationZip'");
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(id.tenant(),
Optional.of(id.instance()),
Optional.of(type.zone(controller.system())),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions"))
.map(json -> SlimeUtils.jsonToSlime(json).get())
.flatMap(options -> optional("vespaVersion", options))
.map(Version::fromString);
controller.jobController().deploy(id, type, version, applicationPackage);
RunId runId = controller.jobController().last(id, type).get().id();
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("message", "Deployment started in " + runId +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<com.yahoo.vespa.hosted.controller.Application> application = controller.applications().getApplication(TenantAndApplicationId.from(applicationId));
Inspector sourceRevision = deployOptions.field("sourceRevision");
Inspector buildNumber = deployOptions.field("buildNumber");
if (sourceRevision.valid() != buildNumber.valid())
throw new IllegalArgumentException("Source revision and build number must both be provided, or not");
Optional<ApplicationVersion> applicationVersion = Optional.empty();
if (sourceRevision.valid()) {
if (applicationPackage.isPresent())
throw new IllegalArgumentException("Application version and application package can't both be provided.");
applicationVersion = Optional.of(ApplicationVersion.from(toSourceRevision(sourceRevision),
buildNumber.asLong()));
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
boolean deployDirectly = deployOptions.field("deployDirectly").asBool();
Optional<Version> vespaVersion = optional("vespaVersion", deployOptions).map(Version::new);
if (deployDirectly && applicationPackage.isEmpty() && applicationVersion.isEmpty() && vespaVersion.isEmpty()) {
Optional<Deployment> deployment = controller.applications().getInstance(applicationId)
.map(Instance::deployments)
.flatMap(deployments -> Optional.ofNullable(deployments.get(zone)));
if(deployment.isEmpty())
throw new IllegalArgumentException("Can't redeploy application, no deployment currently exist");
ApplicationVersion version = deployment.get().applicationVersion();
if(version.isUnknown())
throw new IllegalArgumentException("Can't redeploy application, application version is unknown");
applicationVersion = Optional.of(version);
vespaVersion = Optional.of(deployment.get().version());
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
Optional.of(applicationId.instance()),
Optional.of(zone),
aPackage,
Optional.of(requireUserPrincipal(request))));
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass);
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if (tenant.isEmpty())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
controller.tenants().delete(tenant.get().name(),
accessControlRequests.credentials(tenant.get().name(),
toSlime(request.getData()).get(),
request.getJDiscRequest()));
return tenant(tenant.get(), request);
}
private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
return new MessageResponse("Deleted application " + id);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty()) {
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
}
return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
controller.applications().deactivate(id.applicationId(), id.zoneId());
return new MessageResponse("Deactivated " + id);
}
/** Returns test config for indicated job, with production deployments of the default instance. */
private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
HashSet<DeploymentId> deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toCollection(HashSet::new));
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.routing().zoneEndpointsOf(deployments),
controller.applications().contentClustersByZone(deployments)));
}
private static SourceRevision toSourceRevision(Inspector object) {
if (!object.field("repository").valid() ||
!object.field("branch").valid() ||
!object.field("commit").valid()) {
throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\".");
}
return new SourceRevision(object.field("repository").asString(),
object.field("branch").asString(),
object.field("commit").asString());
}
private Tenant getTenantOrThrow(String tenantName) {
return controller.tenants().get(tenantName)
.orElseThrow(() -> new NotExistsException(new TenantId(tenantName)));
}
private void toSlime(Cursor object, Tenant tenant, HttpRequest request) {
object.setString("tenant", tenant.name().value());
object.setString("type", tenantType(tenant));
List<com.yahoo.vespa.hosted.controller.Application> applications = controller.applications().asList(tenant.name());
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
object.setString("athensDomain", athenzTenant.domain().getName());
object.setString("property", athenzTenant.property().id());
athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString()));
athenzTenant.contact().ifPresent(c -> {
object.setString("propertyUrl", c.propertyUrl().toString());
object.setString("contactsUrl", c.url().toString());
object.setString("issueCreationUrl", c.issueTrackerUrl().toString());
Cursor contactsArray = object.setArray("contacts");
c.persons().forEach(persons -> {
Cursor personArray = contactsArray.addArray();
persons.forEach(personArray::addString);
});
});
break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
cloudTenant.creator().ifPresent(creator -> object.setString("creator", creator.getName()));
Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys");
cloudTenant.developerKeys().forEach((key, user) -> {
Cursor keyObject = pemDeveloperKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", user.getName());
});
break;
}
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
Cursor applicationArray = object.setArray("applications");
for (com.yahoo.vespa.hosted.controller.Application application : applications) {
DeploymentStatus status = controller.jobController().deploymentStatus(application);
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, status, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
}
private void toSlime(ClusterResources resources, Cursor object) {
object.setLong("nodes", resources.nodes());
object.setLong("groups", resources.groups());
toSlime(resources.nodeResources(), object.setObject("nodeResources"));
if ( ! controller.zoneRegistry().system().isPublic())
object.setDouble("cost", Math.round(resources.nodes() * resources.nodeResources().cost() * 100.0 / 3.0) / 100.0);
}
private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", valueOf(resources.diskSpeed()));
object.setString("storageType", valueOf(resources.storageType()));
}
private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) {
object.setString("tenant", tenant.name().value());
Cursor metaData = object.setObject("metaData");
metaData.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
metaData.setString("athensDomain", athenzTenant.domain().getName());
metaData.setString("property", athenzTenant.property().id());
break;
case cloud: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString());
}
/** Returns a copy of the given URI with the host and port from the given URI, the path set to the given path and the query set to given query*/
private URI withPathAndQuery(String newPath, String newQuery, URI uri) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, newQuery, null);
}
catch (URISyntaxException e) {
throw new RuntimeException("Will not happen", e);
}
}
/** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */
private URI withPath(String newPath, URI uri) {
return withPathAndQuery(newPath, null, uri);
}
private long asLong(String valueOrNull, long defaultWhenNull) {
if (valueOrNull == null) return defaultWhenNull;
try {
return Long.parseLong(valueOrNull);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'");
}
}
private void toSlime(Run run, Cursor object) {
object.setLong("id", run.id().number());
object.setString("version", run.versions().targetPlatform().toFullString());
if ( ! run.versions().targetApplication().isUnknown())
toSlime(run.versions().targetApplication(), object.setObject("revision"));
object.setString("reason", "unknown reason");
object.setLong("at", run.end().orElse(run.start()).toEpochMilli());
}
private Slime toSlime(InputStream jsonStream) {
try {
byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000);
return SlimeUtils.jsonToSlime(jsonBytes);
} catch (IOException e) {
throw new RuntimeException();
}
}
private static Principal requireUserPrincipal(HttpRequest request) {
Principal principal = request.getJDiscRequest().getUserPrincipal();
if (principal == null) throw new InternalServerErrorException("Expected a user principal");
return principal;
}
private Inspector mandatory(String key, Inspector object) {
if ( ! object.field(key).valid())
throw new IllegalArgumentException("'" + key + "' is missing");
return object.field(key);
}
private Optional<String> optional(String key, Inspector object) {
return SlimeUtils.optionalString(object.field(key));
}
private static String path(Object... elements) {
return Joiner.on("/").join(elements);
}
private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value(),
request.getUri()).toString());
}
private void toSlime(ApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value() +
"/instance/" + id.instance().value(),
request.getUri()).toString());
}
private Slime toSlime(ActivateResult result) {
Slime slime = new Slime();
Cursor object = slime.setObject();
object.setString("revisionId", result.revisionId().id());
object.setLong("applicationZipSize", result.applicationZipSizeBytes());
Cursor logArray = object.setArray("prepareMessages");
if (result.prepareResponse().log != null) {
for (Log logMessage : result.prepareResponse().log) {
Cursor logObject = logArray.addObject();
logObject.setLong("time", logMessage.time);
logObject.setString("level", logMessage.level);
logObject.setString("message", logMessage.message);
}
}
Cursor changeObject = object.setObject("configChangeActions");
Cursor restartActionsArray = changeObject.setArray("restart");
for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) {
Cursor restartActionObject = restartActionsArray.addObject();
restartActionObject.setString("clusterName", restartAction.clusterName);
restartActionObject.setString("clusterType", restartAction.clusterType);
restartActionObject.setString("serviceType", restartAction.serviceType);
serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services"));
stringsToSlime(restartAction.messages, restartActionObject.setArray("messages"));
}
Cursor refeedActionsArray = changeObject.setArray("refeed");
for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) {
Cursor refeedActionObject = refeedActionsArray.addObject();
refeedActionObject.setString("name", refeedAction.name);
refeedActionObject.setBool("allowed", refeedAction.allowed);
refeedActionObject.setString("documentType", refeedAction.documentType);
refeedActionObject.setString("clusterName", refeedAction.clusterName);
serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services"));
stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages"));
}
return slime;
}
private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) {
for (ServiceInfo serviceInfo : serviceInfoList) {
Cursor serviceInfoObject = array.addObject();
serviceInfoObject.setString("serviceName", serviceInfo.serviceName);
serviceInfoObject.setString("serviceType", serviceInfo.serviceType);
serviceInfoObject.setString("configId", serviceInfo.configId);
serviceInfoObject.setString("hostName", serviceInfo.hostName);
}
}
private void stringsToSlime(List<String> strings, Cursor array) {
for (String string : strings)
array.addString(string);
}
private String readToString(InputStream stream) {
Scanner scanner = new Scanner(stream).useDelimiter("\\A");
if ( ! scanner.hasNext()) return null;
return scanner.next();
}
private boolean systemHasVersion(Version version) {
return controller.versionStatus().versions().stream().anyMatch(v -> v.versionNumber().equals(version));
}
private static boolean recurseOverTenants(HttpRequest request) {
return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive"));
}
private static boolean recurseOverApplications(HttpRequest request) {
return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive"));
}
private static boolean recurseOverDeployments(HttpRequest request) {
return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive"));
}
private static boolean showOnlyProductionInstances(HttpRequest request) {
return "true".equals(request.getProperty("production"));
}
private static String tenantType(Tenant tenant) {
switch (tenant.type()) {
case athenz: return "ATHENS";
case cloud: return "CLOUD";
default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName());
}
}
private static ApplicationId appIdFromPath(Path path) {
return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance"));
}
private static JobType jobTypeFromPath(Path path) {
return JobType.fromJobName(path.get("jobtype"));
}
private static RunId runIdFromPath(Path path) {
long number = Long.parseLong(path.get("number"));
return new RunId(appIdFromPath(path), jobTypeFromPath(path), number);
}
private HttpResponse submit(String tenant, String application, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
Optional<String> repository = optional("repository", submitOptions);
Optional<String> branch = optional("branch", submitOptions);
Optional<String> commit = optional("commit", submitOptions);
Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent()
? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get()))
: Optional.empty();
Optional<String> sourceUrl = optional("sourceUrl", submitOptions);
Optional<String> authorEmail = optional("authorEmail", submitOptions);
sourceUrl.map(URI::create).ifPresent(url -> {
if (url.getHost() == null || url.getScheme() == null)
throw new IllegalArgumentException("Source URL must include scheme and host");
});
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true);
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
Optional.empty(),
Optional.empty(),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
sourceUrl,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
private HttpResponse removeAllProdDeployments(String tenant, String application) {
JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application,
Optional.empty(), Optional.empty(), Optional.empty(), 1,
ApplicationPackage.deploymentRemoval(), new byte[0]);
return new MessageResponse("All deployments removed");
}
private static Map<String, byte[]> parseDataParts(HttpRequest request) {
String contentHash = request.getHeader("x-Content-Hash");
if (contentHash == null)
return new MultipartParser().parse(request);
DigestInputStream digester = Signatures.sha256Digester(request.getData());
var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri());
if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash)))
throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash");
return dataParts;
}
private static RotationId findRotationId(Instance instance, Optional<String> endpointId) {
if (instance.rotations().isEmpty()) {
throw new NotExistsException("global rotation does not exist for " + instance);
}
if (endpointId.isPresent()) {
return instance.rotations().stream()
.filter(r -> r.endpointId().id().equals(endpointId.get()))
.map(AssignedRotation::rotationId)
.findFirst()
.orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() +
" does not exist for " + instance));
} else if (instance.rotations().size() > 1) {
throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given");
}
return instance.rotations().get(0).rotationId();
}
private static String rotationStateString(RotationState state) {
switch (state) {
case in: return "IN";
case out: return "OUT";
}
return "UNKNOWN";
}
private static String endpointScopeString(Endpoint.Scope scope) {
switch (scope) {
case region: return "region";
case global: return "global";
case zone: return "zone";
}
throw new IllegalArgumentException("Unknown endpoint scope " + scope);
}
private static String routingMethodString(RoutingMethod method) {
switch (method) {
case exclusive: return "exclusive";
case shared: return "shared";
case sharedLayer4: return "sharedLayer4";
}
throw new IllegalArgumentException("Unknown routing method " + method);
}
private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) {
return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName))
.filter(cls::isInstance)
.map(cls::cast)
.orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request"));
}
/** Returns whether given request is by an operator */
private static boolean isOperator(HttpRequest request) {
var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class);
return securityContext.roles().stream()
.map(Role::definition)
.anyMatch(definition -> definition == RoleDefinition.hostedOperator);
}
} |
Add some error message here as well | private JsonResponse buildResponseFromProtonMetrics(List<ProtonMetrics> protonMetrics) {
try {
var jsonObject = new JSONObject();
var jsonArray = new JSONArray();
for (ProtonMetrics metrics : protonMetrics) {
jsonArray.put(metrics.toJson());
}
jsonObject.put("metrics", jsonArray);
return new JsonResponse(200, jsonObject.toString());
} catch (JSONException e) {
log.severe("Unable to build JsonResponse with Proton data");
return new JsonResponse(500, "");
}
} | return new JsonResponse(500, ""); | private JsonResponse buildResponseFromProtonMetrics(List<ProtonMetrics> protonMetrics) {
try {
var jsonObject = new JSONObject();
var jsonArray = new JSONArray();
for (ProtonMetrics metrics : protonMetrics) {
jsonArray.put(metrics.toJson());
}
jsonObject.put("metrics", jsonArray);
return new JsonResponse(200, jsonObject.toString());
} catch (JSONException e) {
log.severe("Unable to build JsonResponse with Proton data");
return new JsonResponse(500, "");
}
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestConfigSerializer testConfigSerializer;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
}
@Override
public Duration getTimeout() {
return Duration.ofMinutes(20);
}
@Override
public HttpResponse handle(HttpRequest request) {
try {
Path path = new Path(request.getUri(), OPTIONAL_PREFIX);
switch (request.getMethod()) {
case GET: return handleGET(path, request);
case PUT: return handlePUT(path, request);
case POST: return handlePOST(path, request);
case PATCH: return handlePATCH(path, request);
case DELETE: return handleDELETE(path, request);
case OPTIONS: return handleOPTIONS();
default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
}
}
catch (ForbiddenException e) {
return ErrorResponse.forbidden(Exceptions.toMessageString(e));
}
catch (NotAuthorizedException e) {
return ErrorResponse.unauthorized(Exceptions.toMessageString(e));
}
catch (NotExistsException e) {
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
}
catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
catch (ConfigServerException e) {
switch (e.getErrorCode()) {
case NOT_FOUND:
return new ErrorResponse(NOT_FOUND, e.getErrorCode().name(), Exceptions.toMessageString(e));
case ACTIVATION_CONFLICT:
return new ErrorResponse(CONFLICT, e.getErrorCode().name(), Exceptions.toMessageString(e));
case INTERNAL_SERVER_ERROR:
return new ErrorResponse(INTERNAL_SERVER_ERROR, e.getErrorCode().name(), Exceptions.toMessageString(e));
default:
return new ErrorResponse(BAD_REQUEST, e.getErrorCode().name(), Exceptions.toMessageString(e));
}
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/tenant")) return tenants(request);
if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/metrics")) return metrics(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePUT(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePATCH(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleDELETE(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeAllProdDeployments(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleOPTIONS() {
EmptyResponse response = new EmptyResponse();
response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS");
return response;
}
private HttpResponse recursiveRoot(HttpRequest request) {
Slime slime = new Slime();
Cursor tenantArray = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
toSlime(tenantArray.addObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse root(HttpRequest request) {
return recurseOverTenants(request)
? recursiveRoot(request)
: new ResourceResponse(request, "tenant");
}
private HttpResponse tenants(HttpRequest request) {
Slime slime = new Slime();
Cursor response = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject());
return new SlimeJsonResponse(slime);
}
private HttpResponse tenant(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenant(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenant(Tenant tenant, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
if (controller.tenants().get(tenantName).isEmpty())
return ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist");
Slime slime = new Slime();
Cursor applicationArray = slime.setArray();
for (com.yahoo.vespa.hosted.controller.Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true)) {
Cursor applicationObject = applicationArray.addObject();
applicationObject.setString("tenant", application.id().tenant().value());
applicationObject.setString("application", application.id().application().value());
applicationObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value(),
request.getUri()).toString());
Cursor instanceArray = applicationObject.setArray("instances");
for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet()
: application.instances().keySet()) {
Cursor instanceObject = instanceArray.addObject();
instanceObject.setString("instance", instance.value());
instanceObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/instance/" + instance.value(),
request.getUri()).toString());
}
}
}
return new SlimeJsonResponse(slime);
}
private HttpResponse devApplicationPackage(ApplicationId id, JobType type) {
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Only manually deployed zones have dev packages");
ZoneId zone = type.zone(controller.system());
byte[] applicationPackage = controller.applications().applicationStore().getDev(id, zone);
return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage);
}
private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse compileVersion(String tenantName, String applicationName) {
Slime slime = new Slime();
slime.setObject().setString("compileVersion",
compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString());
return new SlimeJsonResponse(slime);
}
private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
Principal user = request.getJDiscRequest().getUserPrincipal();
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withDeveloperKey(developerKey, user);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Principal user = ((CloudTenant) controller.tenants().require(TenantName.from(tenantName))).developerKeys().get(developerKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withoutDeveloperKey(developerKey);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) {
keys.forEach((key, principal) -> {
Cursor keyObject = keysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", principal.getName());
});
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withoutDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes.");
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
Inspector majorVersionField = requestObject.field("majorVersion");
if (majorVersionField.valid()) {
Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong();
application = application.withMajorVersion(majorVersion);
messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion));
}
Inspector pemDeployKeyField = requestObject.field("pemDeployKey");
if (pemDeployKeyField.valid()) {
String pemDeployKey = pemDeployKeyField.asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
application = application.withDeployKey(deployKey);
messageBuilder.add("Added deploy key " + pemDeployKey);
}
controller.applications().store(application);
});
return new MessageResponse(messageBuilder.toString());
}
private com.yahoo.vespa.hosted.controller.Application getApplication(String tenantName, String applicationName) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
return controller.applications().getApplication(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private Instance getInstance(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
return controller.applications().getInstance(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, id);
Slime slime = new Slime();
Cursor nodesArray = slime.setObject().setArray("nodes");
for (Node node : nodes) {
Cursor nodeObject = nodesArray.addObject();
nodeObject.setString("hostname", node.hostname().value());
nodeObject.setString("state", valueOf(node.state()));
node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.flavor());
toSlime(node.resources(), nodeObject);
nodeObject.setBool("fastDisk", node.resources().diskSpeed() == NodeResources.DiskSpeed.fast);
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
return new SlimeJsonResponse(slime);
}
private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id);
Slime slime = new Slime();
Cursor clustersObject = slime.setObject().setObject("clusters");
for (Cluster cluster : application.clusters().values()) {
Cursor clusterObject = clustersObject.setObject(cluster.id().value());
toSlime(cluster.min(), clusterObject.setObject("min"));
toSlime(cluster.max(), clusterObject.setObject("max"));
toSlime(cluster.current(), clusterObject.setObject("current"));
cluster.target().ifPresent(target -> toSlime(target, clusterObject.setObject("target")));
cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested")));
}
return new SlimeJsonResponse(slime);
}
private static String valueOf(Node.State state) {
switch (state) {
case failed: return "failed";
case parked: return "parked";
case dirty: return "dirty";
case ready: return "ready";
case active: return "active";
case inactive: return "inactive";
case reserved: return "reserved";
case provisioned: return "provisioned";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ServiceState state) {
switch (state) {
case expectedUp: return "expectedUp";
case allowedDown: return "allowedDown";
case unorchestrated: return "unorchestrated";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ClusterType type) {
switch (type) {
case admin: return "admin";
case content: return "content";
case container: return "container";
case combined: return "combined";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
private static String valueOf(NodeResources.DiskSpeed diskSpeed) {
switch (diskSpeed) {
case fast : return "fast";
case slow : return "slow";
case any : return "any";
default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'");
}
}
private static String valueOf(NodeResources.StorageType storageType) {
switch (storageType) {
case remote : return "remote";
case local : return "local";
case any : return "any";
default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'");
}
}
private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters);
return new HttpResponse(200) {
@Override
public void render(OutputStream outputStream) throws IOException {
logStream.transferTo(outputStream);
}
};
}
private HttpResponse metrics(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
List<ProtonMetrics> protonMetrics = controller.serviceRegistry().configServer().getProtonMetrics(deployment);
return buildResponseFromProtonMetrics(protonMetrics);
}
private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
boolean requireTests = ! requestObject.field("skipTests").asBool();
boolean reTrigger = requestObject.field("reTrigger").asBool();
String triggered = reTrigger
? controller.applications().deploymentTrigger()
.reTrigger(id, type).type().jobName()
: controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests)
.stream().map(job -> job.type().jobName()).collect(joining(", "));
return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered"
: "Triggered " + triggered + " for " + id);
}
private HttpResponse pause(ApplicationId id, JobType type) {
Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause);
controller.applications().deploymentTrigger().pauseJob(id, type, until);
return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause);
}
private HttpResponse resume(ApplicationId id, JobType type) {
controller.applications().deploymentTrigger().resumeJob(id, type);
return new MessageResponse(type.jobName() + " for " + id + " resumed");
}
private void toSlime(Cursor object, com.yahoo.vespa.hosted.controller.Application application, HttpRequest request) {
object.setString("tenant", application.id().tenant().value());
object.setString("application", application.id().application().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/job/",
request.getUri()).toString());
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
application.instances().values().stream().findFirst().ifPresent(instance -> {
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
});
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request);
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
if (deploymentSpec.instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec.requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
globalEndpointsToSlime(object, instance);
List<Deployment> deployments = deploymentSpec.instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor deploymentsArray = object.setArray("deployments");
for (Deployment deployment : deployments) {
Cursor deploymentObject = deploymentsArray.addObject();
if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty())
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/instance/" + instance.name().value() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
}
private void globalEndpointsToSlime(Cursor object, Instance instance) {
var globalEndpointUrls = new LinkedHashSet<String>();
controller.routing().endpointsOf(instance.id())
.requiresRotation()
.not().legacy()
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalEndpointUrls::add);
var globalRotationsArray = object.setArray("globalRotations");
globalEndpointUrls.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
}
private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) {
com.yahoo.vespa.hosted.controller.Application application = status.application();
object.setString("tenant", instance.id().tenant().value());
object.setString("application", instance.id().application().value());
object.setString("instance", instance.id().instance().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + instance.id().tenant().value() +
"/application/" + instance.id().application().value() +
"/instance/" + instance.id().instance().value() + "/job/",
request.getUri()).toString());
application.latestVersion().ifPresent(version -> {
sourceRevisionToSlime(version.source(), object.setObject("source"));
version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
version.commit().ifPresent(commit -> object.setString("commit", commit));
});
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if (application.deploymentSpec().instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec().requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
globalEndpointsToSlime(object, instance);
List<Deployment> deployments =
application.deploymentSpec().instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor instancesArray = object.setArray("instances");
for (Deployment deployment : deployments) {
Cursor deploymentObject = instancesArray.addObject();
if (deployment.zone().environment() == Environment.prod) {
if (instance.rotations().size() == 1) {
toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment),
deploymentObject);
}
if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) {
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
}
}
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("instance", instance.id().instance().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
status.jobSteps().keySet().stream()
.filter(job -> job.application().instance().equals(instance.name()))
.filter(job -> job.type().isProduction() && job.type().isDeployment())
.map(job -> job.type().zone(controller.system()))
.filter(zone -> ! instance.deployments().containsKey(zone))
.forEach(zone -> {
Cursor deploymentObject = instancesArray.addObject();
deploymentObject.setString("environment", zone.environment().value());
deploymentObject.setString("region", zone.region().value());
});
application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key)));
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().getInstance(id)
.orElseThrow(() -> new NotExistsException(id + " not found"));
DeploymentId deploymentId = new DeploymentId(instance.id(),
ZoneId.from(environment, region));
Deployment deployment = instance.deployments().get(deploymentId.zoneId());
if (deployment == null)
throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId());
Slime slime = new Slime();
toSlime(slime.setObject(), deploymentId, deployment, request);
return new SlimeJsonResponse(slime);
}
private void toSlime(Cursor object, Change change) {
change.platform().ifPresent(version -> object.setString("version", version.toString()));
change.application()
.filter(version -> !version.isUnknown())
.ifPresent(version -> toSlime(version, object.setObject("revision")));
}
private void toSlime(Endpoint endpoint, Cursor object) {
object.setString("cluster", endpoint.cluster().value());
object.setBool("tls", endpoint.tls());
object.setString("url", endpoint.url().toString());
object.setString("scope", endpointScopeString(endpoint.scope()));
object.setString("routingMethod", routingMethodString(endpoint.routingMethod()));
}
private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) {
response.setString("tenant", deploymentId.applicationId().tenant().value());
response.setString("application", deploymentId.applicationId().application().value());
response.setString("instance", deploymentId.applicationId().instance().value());
response.setString("environment", deploymentId.zoneId().environment().value());
response.setString("region", deploymentId.zoneId().region().value());
var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId()));
var endpointArray = response.setArray("endpoints");
for (var endpoint : controller.routing().endpointsOf(deploymentId)
.scope(Endpoint.Scope.zone)
.not().legacy()) {
toSlime(endpoint, endpointArray.addObject());
}
var globalEndpoints = controller.routing().endpointsOf(application, deploymentId.applicationId().instance())
.not().legacy()
.targets(deploymentId.zoneId());
for (var endpoint : globalEndpoints) {
toSlime(endpoint, endpointArray.addObject());
}
response.setString("nodes", withPathAndQuery("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/", "recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString());
response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString());
response.setString("version", deployment.version().toFullString());
response.setString("revision", deployment.applicationVersion().id());
response.setLong("deployTimeEpochMs", deployment.at().toEpochMilli());
controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId())
.ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", deployment.at().plus(deploymentTimeToLive).toEpochMilli()));
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
var instance = application.instances().get(deploymentId.applicationId().instance());
if (instance != null) {
if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod)
toSlime(instance.rotations(), instance.rotationStatus(), deployment, response);
JobType.from(controller.system(), deployment.zone())
.map(type -> new JobId(instance.id(), type))
.map(status.jobSteps()::get)
.ifPresent(stepStatus -> {
JobControllerApiHandlerHelper.applicationVersionToSlime(
response.setObject("applicationVersion"), deployment.applicationVersion());
if (!status.jobsToRun().containsKey(stepStatus.job().get()))
response.setString("status", "complete");
else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true))
response.setString("status", "pending");
else response.setString("status", "running");
});
}
Cursor activity = response.setObject("activity");
deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried",
instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten",
instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
DeploymentMetrics metrics = deployment.metrics();
Cursor metricsObject = response.setObject("metrics");
metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond());
metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond());
metricsObject.setDouble("documentCount", metrics.documentCount());
metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis());
metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli()));
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if ( ! applicationVersion.isUnknown()) {
object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong());
object.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if (revision.isEmpty()) return;
object.setString("gitRepository", revision.get().repository());
object.setString("gitBranch", revision.get().branch());
object.setString("gitCommit", revision.get().commit());
}
private void toSlime(RotationState state, Cursor object) {
Cursor bcpStatus = object.setObject("bcpStatus");
bcpStatus.setString("rotationStatus", rotationStateString(state));
}
private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) {
var array = object.setArray("endpointStatus");
for (var rotation : rotations) {
var statusObject = array.addObject();
var targets = status.of(rotation.rotationId());
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("rotationId", rotation.rotationId().asString());
statusObject.setString("clusterId", rotation.clusterId().value());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli());
}
}
private URI monitoringSystemUri(DeploymentId deploymentId) {
return controller.zoneRegistry().getMonitoringSystemUri(deploymentId);
}
/**
* Returns a non-broken, released version at least as old as the oldest platform the given application is on.
*
* If no known version is applicable, the newest version at least as old as the oldest platform is selected,
* among all versions released for this system. If no such versions exists, throws an IllegalStateException.
*/
private Version compileVersion(TenantAndApplicationId id) {
Version oldestPlatform = controller.applications().oldestInstalledPlatform(id);
VersionStatus versionStatus = controller.versionStatus();
return versionStatus.versions().stream()
.filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low))
.filter(VespaVersion::isReleased)
.map(VespaVersion::versionNumber)
.filter(version -> ! version.isAfter(oldestPlatform))
.max(Comparator.naturalOrder())
.orElseGet(() -> controller.mavenRepository().metadata().versions().stream()
.filter(version -> ! version.isAfter(oldestPlatform))
.filter(version -> ! versionStatus.versions().stream()
.map(VespaVersion::versionNumber)
.collect(Collectors.toSet()).contains(version))
.max(Comparator.naturalOrder())
.orElseThrow(() -> new IllegalStateException("No available releases of " +
controller.mavenRepository().artifactId())));
}
private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
ZoneId zone = ZoneId.from(environment, region);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
var deploymentId = new DeploymentId(instance.id(), zone);
setGlobalRotationStatus(deploymentId, inService, request);
setGlobalEndpointStatus(deploymentId, inService, request);
return new MessageResponse(String.format("Successfully set %s in %s %s service",
instance.id().toShortString(), zone, inService ? "in" : "out of"));
}
/** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */
private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
var status = inService ? GlobalRouting.Status.in : GlobalRouting.Status.out;
controller.routing().policies().setGlobalRoutingStatus(deployment, status, agent);
}
/** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */
private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var requestData = toSlime(request.getData()).get();
var reason = mandatory("reason", requestData).asString();
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
long timestamp = controller.clock().instant().getEpochSecond();
var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp);
controller.routing().setGlobalRotationStatus(deployment, endpointStatus);
}
private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Slime slime = new Slime();
Cursor array = slime.setObject().setArray("globalrotationoverride");
controller.routing().globalRotationStatus(deploymentId)
.forEach((endpoint, status) -> {
array.addString(endpoint.upstreamIdOf(deploymentId));
Cursor statusObject = array.addObject();
statusObject.setString("status", status.getStatus().name());
statusObject.setString("reason", status.getReason() == null ? "" : status.getReason());
statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent());
statusObject.setLong("timestamp", status.getEpoch());
});
return new SlimeJsonResponse(slime);
}
private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().requireInstance(applicationId);
ZoneId zone = ZoneId.from(environment, region);
RotationId rotation = findRotationId(instance, endpointId);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
Slime slime = new Slime();
Cursor response = slime.setObject();
toSlime(instance.rotationStatus().of(rotation, deployment), response);
return new SlimeJsonResponse(slime);
}
private HttpResponse metering(String tenant, String application, HttpRequest request) {
Slime slime = new Slime();
Cursor root = slime.setObject();
MeteringData meteringData = controller.serviceRegistry()
.meteringService()
.getMeteringData(TenantName.from(tenant), ApplicationName.from(application));
ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringData.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringData.getLastMonth();
Cursor lastmonth = root.setObject("lastmonth");
lastmonth.setDouble("cpu", lastMonth.getCpuCores());
lastmonth.setDouble("mem", lastMonth.getMemoryGb());
lastmonth.setDouble("disk", lastMonth.getDiskGb());
Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory();
Cursor details = root.setObject("details");
Cursor detailsCpu = details.setObject("cpu");
Cursor detailsMem = details.setObject("mem");
Cursor detailsDisk = details.setObject("disk");
history.entrySet().stream()
.forEach(entry -> {
String instanceName = entry.getKey().instance().value();
Cursor detailsCpuApp = detailsCpu.setObject(instanceName);
Cursor detailsMemApp = detailsMem.setObject(instanceName);
Cursor detailsDiskApp = detailsDisk.setObject(instanceName);
Cursor detailsCpuData = detailsCpuApp.setArray("data");
Cursor detailsMemData = detailsMemApp.setArray("data");
Cursor detailsDiskData = detailsDiskApp.setArray("data");
entry.getValue().stream()
.forEach(resourceSnapshot -> {
Cursor cpu = detailsCpuData.addObject();
cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
cpu.setDouble("value", resourceSnapshot.getCpuCores());
Cursor mem = detailsMemData.addObject();
mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
mem.setDouble("value", resourceSnapshot.getMemoryGb());
Cursor disk = detailsDiskData.addObject();
disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
disk.setDouble("value", resourceSnapshot.getDiskGb());
});
});
return new SlimeJsonResponse(slime);
}
private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! instance.change().isEmpty()) {
instance.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", instance.change().isPinned());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
boolean suspended = controller.applications().isSuspended(deploymentId);
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setBool("suspended", suspended);
return new SlimeJsonResponse(slime);
}
private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region);
ServiceApiResponse response = new ServiceApiResponse(ZoneId.from(environment, region),
new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(),
controller.zoneRegistry().getConfigServerApiUris(ZoneId.from(environment, region)),
request.getUri());
response.setResponse(applicationView);
return response;
}
private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), ZoneId.from(environment, region));
if ("container-clustercontroller".equals((serviceName)) && restPath.contains("/status/")) {
String result = controller.serviceRegistry().configServer().getClusterControllerStatus(deploymentId, restPath);
return new HtmlResponse(result);
}
Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath);
ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(),
deploymentId.applicationId(),
controller.zoneRegistry().getConfigServerApiUris(deploymentId.zoneId()),
request.getUri());
response.setResponse(result, serviceName, restPath);
return response;
}
private HttpResponse updateTenant(String tenantName, HttpRequest request) {
getTenantOrThrow(tenantName);
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().update(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createTenant(String tenantName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().create(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest());
com.yahoo.vespa.hosted.controller.Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
if (controller.applications().getApplication(applicationId).isEmpty())
createApplication(tenantName, applicationName, request);
controller.applications().createInstance(applicationId.instance(instanceName));
Slime slime = new Slime();
toSlime(applicationId.instance(instanceName), slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
/** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */
private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) {
request = controller.auditLogger().log(request);
String versionString = readToString(request.getData());
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Version version = Version.fromString(versionString);
if (version.equals(Version.emptyVersion))
version = controller.systemVersion();
if ( ! systemHasVersion(version))
throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " +
"Version is not active in this system. " +
"Active versions: " + controller.versionStatus().versions()
.stream()
.map(VespaVersion::versionNumber)
.map(Version::toString)
.collect(joining(", ")));
Change change = Change.of(version);
if (pin)
change = change.withPin();
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Trigger deployment to the last known application package for the given application. */
private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) {
controller.auditLogger().log(request);
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */
private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = application.get().require(id.instance()).change();
if (change.isEmpty()) {
response.append("No deployment in progress for ").append(id).append(" at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Schedule restart of deployment, or specific host in a deployment */
private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
RestartFilter restartFilter = new RestartFilter()
.withHostName(Optional.ofNullable(request.getProperty("hostname")).map(HostName::from))
.withClusterType(Optional.ofNullable(request.getProperty("clusterType")).map(ClusterSpec.Type::from))
.withClusterId(Optional.ofNullable(request.getProperty("clusterId")).map(ClusterSpec.Id::from));
controller.applications().restart(deploymentId, restartFilter);
return new MessageResponse("Requested restart of " + deploymentId);
}
private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) {
if ( ! type.environment().isManuallyDeployed() && ! isOperator(request))
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("applicationZip"))
throw new IllegalArgumentException("Missing required form part 'applicationZip'");
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(id.tenant(),
Optional.of(id.instance()),
Optional.of(type.zone(controller.system())),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions"))
.map(json -> SlimeUtils.jsonToSlime(json).get())
.flatMap(options -> optional("vespaVersion", options))
.map(Version::fromString);
controller.jobController().deploy(id, type, version, applicationPackage);
RunId runId = controller.jobController().last(id, type).get().id();
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("message", "Deployment started in " + runId +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<com.yahoo.vespa.hosted.controller.Application> application = controller.applications().getApplication(TenantAndApplicationId.from(applicationId));
Inspector sourceRevision = deployOptions.field("sourceRevision");
Inspector buildNumber = deployOptions.field("buildNumber");
if (sourceRevision.valid() != buildNumber.valid())
throw new IllegalArgumentException("Source revision and build number must both be provided, or not");
Optional<ApplicationVersion> applicationVersion = Optional.empty();
if (sourceRevision.valid()) {
if (applicationPackage.isPresent())
throw new IllegalArgumentException("Application version and application package can't both be provided.");
applicationVersion = Optional.of(ApplicationVersion.from(toSourceRevision(sourceRevision),
buildNumber.asLong()));
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
boolean deployDirectly = deployOptions.field("deployDirectly").asBool();
Optional<Version> vespaVersion = optional("vespaVersion", deployOptions).map(Version::new);
if (deployDirectly && applicationPackage.isEmpty() && applicationVersion.isEmpty() && vespaVersion.isEmpty()) {
Optional<Deployment> deployment = controller.applications().getInstance(applicationId)
.map(Instance::deployments)
.flatMap(deployments -> Optional.ofNullable(deployments.get(zone)));
if(deployment.isEmpty())
throw new IllegalArgumentException("Can't redeploy application, no deployment currently exist");
ApplicationVersion version = deployment.get().applicationVersion();
if(version.isUnknown())
throw new IllegalArgumentException("Can't redeploy application, application version is unknown");
applicationVersion = Optional.of(version);
vespaVersion = Optional.of(deployment.get().version());
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
Optional.of(applicationId.instance()),
Optional.of(zone),
aPackage,
Optional.of(requireUserPrincipal(request))));
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass);
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if (tenant.isEmpty())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
controller.tenants().delete(tenant.get().name(),
accessControlRequests.credentials(tenant.get().name(),
toSlime(request.getData()).get(),
request.getJDiscRequest()));
return tenant(tenant.get(), request);
}
private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
return new MessageResponse("Deleted application " + id);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty()) {
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
}
return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
controller.applications().deactivate(id.applicationId(), id.zoneId());
return new MessageResponse("Deactivated " + id);
}
/** Returns test config for indicated job, with production deployments of the default instance. */
private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
HashSet<DeploymentId> deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toCollection(HashSet::new));
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.routing().zoneEndpointsOf(deployments),
controller.applications().contentClustersByZone(deployments)));
}
private static SourceRevision toSourceRevision(Inspector object) {
if (!object.field("repository").valid() ||
!object.field("branch").valid() ||
!object.field("commit").valid()) {
throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\".");
}
return new SourceRevision(object.field("repository").asString(),
object.field("branch").asString(),
object.field("commit").asString());
}
private Tenant getTenantOrThrow(String tenantName) {
return controller.tenants().get(tenantName)
.orElseThrow(() -> new NotExistsException(new TenantId(tenantName)));
}
private void toSlime(Cursor object, Tenant tenant, HttpRequest request) {
object.setString("tenant", tenant.name().value());
object.setString("type", tenantType(tenant));
List<com.yahoo.vespa.hosted.controller.Application> applications = controller.applications().asList(tenant.name());
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
object.setString("athensDomain", athenzTenant.domain().getName());
object.setString("property", athenzTenant.property().id());
athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString()));
athenzTenant.contact().ifPresent(c -> {
object.setString("propertyUrl", c.propertyUrl().toString());
object.setString("contactsUrl", c.url().toString());
object.setString("issueCreationUrl", c.issueTrackerUrl().toString());
Cursor contactsArray = object.setArray("contacts");
c.persons().forEach(persons -> {
Cursor personArray = contactsArray.addArray();
persons.forEach(personArray::addString);
});
});
break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
cloudTenant.creator().ifPresent(creator -> object.setString("creator", creator.getName()));
Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys");
cloudTenant.developerKeys().forEach((key, user) -> {
Cursor keyObject = pemDeveloperKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", user.getName());
});
break;
}
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
Cursor applicationArray = object.setArray("applications");
for (com.yahoo.vespa.hosted.controller.Application application : applications) {
DeploymentStatus status = controller.jobController().deploymentStatus(application);
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, status, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
}
private void toSlime(ClusterResources resources, Cursor object) {
object.setLong("nodes", resources.nodes());
object.setLong("groups", resources.groups());
toSlime(resources.nodeResources(), object.setObject("nodeResources"));
if ( ! controller.zoneRegistry().system().isPublic())
object.setDouble("cost", Math.round(resources.nodes() * resources.nodeResources().cost() * 100.0 / 3.0) / 100.0);
}
private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", valueOf(resources.diskSpeed()));
object.setString("storageType", valueOf(resources.storageType()));
}
private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) {
object.setString("tenant", tenant.name().value());
Cursor metaData = object.setObject("metaData");
metaData.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
metaData.setString("athensDomain", athenzTenant.domain().getName());
metaData.setString("property", athenzTenant.property().id());
break;
case cloud: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString());
}
/** Returns a copy of the given URI with the host and port from the given URI, the path set to the given path and the query set to given query*/
private URI withPathAndQuery(String newPath, String newQuery, URI uri) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, newQuery, null);
}
catch (URISyntaxException e) {
throw new RuntimeException("Will not happen", e);
}
}
/** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */
private URI withPath(String newPath, URI uri) {
return withPathAndQuery(newPath, null, uri);
}
private long asLong(String valueOrNull, long defaultWhenNull) {
if (valueOrNull == null) return defaultWhenNull;
try {
return Long.parseLong(valueOrNull);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'");
}
}
private void toSlime(Run run, Cursor object) {
object.setLong("id", run.id().number());
object.setString("version", run.versions().targetPlatform().toFullString());
if ( ! run.versions().targetApplication().isUnknown())
toSlime(run.versions().targetApplication(), object.setObject("revision"));
object.setString("reason", "unknown reason");
object.setLong("at", run.end().orElse(run.start()).toEpochMilli());
}
private Slime toSlime(InputStream jsonStream) {
try {
byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000);
return SlimeUtils.jsonToSlime(jsonBytes);
} catch (IOException e) {
throw new RuntimeException();
}
}
private static Principal requireUserPrincipal(HttpRequest request) {
Principal principal = request.getJDiscRequest().getUserPrincipal();
if (principal == null) throw new InternalServerErrorException("Expected a user principal");
return principal;
}
private Inspector mandatory(String key, Inspector object) {
if ( ! object.field(key).valid())
throw new IllegalArgumentException("'" + key + "' is missing");
return object.field(key);
}
private Optional<String> optional(String key, Inspector object) {
return SlimeUtils.optionalString(object.field(key));
}
private static String path(Object... elements) {
return Joiner.on("/").join(elements);
}
private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value(),
request.getUri()).toString());
}
private void toSlime(ApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value() +
"/instance/" + id.instance().value(),
request.getUri()).toString());
}
private Slime toSlime(ActivateResult result) {
Slime slime = new Slime();
Cursor object = slime.setObject();
object.setString("revisionId", result.revisionId().id());
object.setLong("applicationZipSize", result.applicationZipSizeBytes());
Cursor logArray = object.setArray("prepareMessages");
if (result.prepareResponse().log != null) {
for (Log logMessage : result.prepareResponse().log) {
Cursor logObject = logArray.addObject();
logObject.setLong("time", logMessage.time);
logObject.setString("level", logMessage.level);
logObject.setString("message", logMessage.message);
}
}
Cursor changeObject = object.setObject("configChangeActions");
Cursor restartActionsArray = changeObject.setArray("restart");
for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) {
Cursor restartActionObject = restartActionsArray.addObject();
restartActionObject.setString("clusterName", restartAction.clusterName);
restartActionObject.setString("clusterType", restartAction.clusterType);
restartActionObject.setString("serviceType", restartAction.serviceType);
serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services"));
stringsToSlime(restartAction.messages, restartActionObject.setArray("messages"));
}
Cursor refeedActionsArray = changeObject.setArray("refeed");
for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) {
Cursor refeedActionObject = refeedActionsArray.addObject();
refeedActionObject.setString("name", refeedAction.name);
refeedActionObject.setBool("allowed", refeedAction.allowed);
refeedActionObject.setString("documentType", refeedAction.documentType);
refeedActionObject.setString("clusterName", refeedAction.clusterName);
serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services"));
stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages"));
}
return slime;
}
private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) {
for (ServiceInfo serviceInfo : serviceInfoList) {
Cursor serviceInfoObject = array.addObject();
serviceInfoObject.setString("serviceName", serviceInfo.serviceName);
serviceInfoObject.setString("serviceType", serviceInfo.serviceType);
serviceInfoObject.setString("configId", serviceInfo.configId);
serviceInfoObject.setString("hostName", serviceInfo.hostName);
}
}
private void stringsToSlime(List<String> strings, Cursor array) {
for (String string : strings)
array.addString(string);
}
private String readToString(InputStream stream) {
Scanner scanner = new Scanner(stream).useDelimiter("\\A");
if ( ! scanner.hasNext()) return null;
return scanner.next();
}
private boolean systemHasVersion(Version version) {
return controller.versionStatus().versions().stream().anyMatch(v -> v.versionNumber().equals(version));
}
private static boolean recurseOverTenants(HttpRequest request) {
return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive"));
}
private static boolean recurseOverApplications(HttpRequest request) {
return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive"));
}
private static boolean recurseOverDeployments(HttpRequest request) {
return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive"));
}
private static boolean showOnlyProductionInstances(HttpRequest request) {
return "true".equals(request.getProperty("production"));
}
private static String tenantType(Tenant tenant) {
switch (tenant.type()) {
case athenz: return "ATHENS";
case cloud: return "CLOUD";
default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName());
}
}
private static ApplicationId appIdFromPath(Path path) {
return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance"));
}
private static JobType jobTypeFromPath(Path path) {
return JobType.fromJobName(path.get("jobtype"));
}
private static RunId runIdFromPath(Path path) {
long number = Long.parseLong(path.get("number"));
return new RunId(appIdFromPath(path), jobTypeFromPath(path), number);
}
private HttpResponse submit(String tenant, String application, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
Optional<String> repository = optional("repository", submitOptions);
Optional<String> branch = optional("branch", submitOptions);
Optional<String> commit = optional("commit", submitOptions);
Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent()
? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get()))
: Optional.empty();
Optional<String> sourceUrl = optional("sourceUrl", submitOptions);
Optional<String> authorEmail = optional("authorEmail", submitOptions);
sourceUrl.map(URI::create).ifPresent(url -> {
if (url.getHost() == null || url.getScheme() == null)
throw new IllegalArgumentException("Source URL must include scheme and host");
});
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true);
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
Optional.empty(),
Optional.empty(),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
sourceUrl,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
private HttpResponse removeAllProdDeployments(String tenant, String application) {
JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application,
Optional.empty(), Optional.empty(), Optional.empty(), 1,
ApplicationPackage.deploymentRemoval(), new byte[0]);
return new MessageResponse("All deployments removed");
}
private static Map<String, byte[]> parseDataParts(HttpRequest request) {
String contentHash = request.getHeader("x-Content-Hash");
if (contentHash == null)
return new MultipartParser().parse(request);
DigestInputStream digester = Signatures.sha256Digester(request.getData());
var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri());
if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash)))
throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash");
return dataParts;
}
private static RotationId findRotationId(Instance instance, Optional<String> endpointId) {
if (instance.rotations().isEmpty()) {
throw new NotExistsException("global rotation does not exist for " + instance);
}
if (endpointId.isPresent()) {
return instance.rotations().stream()
.filter(r -> r.endpointId().id().equals(endpointId.get()))
.map(AssignedRotation::rotationId)
.findFirst()
.orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() +
" does not exist for " + instance));
} else if (instance.rotations().size() > 1) {
throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given");
}
return instance.rotations().get(0).rotationId();
}
private static String rotationStateString(RotationState state) {
switch (state) {
case in: return "IN";
case out: return "OUT";
}
return "UNKNOWN";
}
private static String endpointScopeString(Endpoint.Scope scope) {
switch (scope) {
case region: return "region";
case global: return "global";
case zone: return "zone";
}
throw new IllegalArgumentException("Unknown endpoint scope " + scope);
}
private static String routingMethodString(RoutingMethod method) {
switch (method) {
case exclusive: return "exclusive";
case shared: return "shared";
case sharedLayer4: return "sharedLayer4";
}
throw new IllegalArgumentException("Unknown routing method " + method);
}
private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) {
return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName))
.filter(cls::isInstance)
.map(cls::cast)
.orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request"));
}
/** Returns whether given request is by an operator */
private static boolean isOperator(HttpRequest request) {
var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class);
return securityContext.roles().stream()
.map(Role::definition)
.anyMatch(definition -> definition == RoleDefinition.hostedOperator);
}
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestConfigSerializer testConfigSerializer;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
}
@Override
public Duration getTimeout() {
return Duration.ofMinutes(20);
}
@Override
public HttpResponse handle(HttpRequest request) {
try {
Path path = new Path(request.getUri(), OPTIONAL_PREFIX);
switch (request.getMethod()) {
case GET: return handleGET(path, request);
case PUT: return handlePUT(path, request);
case POST: return handlePOST(path, request);
case PATCH: return handlePATCH(path, request);
case DELETE: return handleDELETE(path, request);
case OPTIONS: return handleOPTIONS();
default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
}
}
catch (ForbiddenException e) {
return ErrorResponse.forbidden(Exceptions.toMessageString(e));
}
catch (NotAuthorizedException e) {
return ErrorResponse.unauthorized(Exceptions.toMessageString(e));
}
catch (NotExistsException e) {
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
}
catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
catch (ConfigServerException e) {
switch (e.getErrorCode()) {
case NOT_FOUND:
return new ErrorResponse(NOT_FOUND, e.getErrorCode().name(), Exceptions.toMessageString(e));
case ACTIVATION_CONFLICT:
return new ErrorResponse(CONFLICT, e.getErrorCode().name(), Exceptions.toMessageString(e));
case INTERNAL_SERVER_ERROR:
return new ErrorResponse(INTERNAL_SERVER_ERROR, e.getErrorCode().name(), Exceptions.toMessageString(e));
default:
return new ErrorResponse(BAD_REQUEST, e.getErrorCode().name(), Exceptions.toMessageString(e));
}
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/tenant")) return tenants(request);
if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/metrics")) return metrics(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePUT(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePATCH(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleDELETE(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeAllProdDeployments(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleOPTIONS() {
EmptyResponse response = new EmptyResponse();
response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS");
return response;
}
private HttpResponse recursiveRoot(HttpRequest request) {
Slime slime = new Slime();
Cursor tenantArray = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
toSlime(tenantArray.addObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse root(HttpRequest request) {
return recurseOverTenants(request)
? recursiveRoot(request)
: new ResourceResponse(request, "tenant");
}
private HttpResponse tenants(HttpRequest request) {
Slime slime = new Slime();
Cursor response = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject());
return new SlimeJsonResponse(slime);
}
private HttpResponse tenant(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenant(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenant(Tenant tenant, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
if (controller.tenants().get(tenantName).isEmpty())
return ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist");
Slime slime = new Slime();
Cursor applicationArray = slime.setArray();
for (com.yahoo.vespa.hosted.controller.Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true)) {
Cursor applicationObject = applicationArray.addObject();
applicationObject.setString("tenant", application.id().tenant().value());
applicationObject.setString("application", application.id().application().value());
applicationObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value(),
request.getUri()).toString());
Cursor instanceArray = applicationObject.setArray("instances");
for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet()
: application.instances().keySet()) {
Cursor instanceObject = instanceArray.addObject();
instanceObject.setString("instance", instance.value());
instanceObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/instance/" + instance.value(),
request.getUri()).toString());
}
}
}
return new SlimeJsonResponse(slime);
}
private HttpResponse devApplicationPackage(ApplicationId id, JobType type) {
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Only manually deployed zones have dev packages");
ZoneId zone = type.zone(controller.system());
byte[] applicationPackage = controller.applications().applicationStore().getDev(id, zone);
return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage);
}
private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse compileVersion(String tenantName, String applicationName) {
Slime slime = new Slime();
slime.setObject().setString("compileVersion",
compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString());
return new SlimeJsonResponse(slime);
}
private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
Principal user = request.getJDiscRequest().getUserPrincipal();
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withDeveloperKey(developerKey, user);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Principal user = ((CloudTenant) controller.tenants().require(TenantName.from(tenantName))).developerKeys().get(developerKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withoutDeveloperKey(developerKey);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) {
keys.forEach((key, principal) -> {
Cursor keyObject = keysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", principal.getName());
});
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withoutDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes.");
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
Inspector majorVersionField = requestObject.field("majorVersion");
if (majorVersionField.valid()) {
Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong();
application = application.withMajorVersion(majorVersion);
messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion));
}
Inspector pemDeployKeyField = requestObject.field("pemDeployKey");
if (pemDeployKeyField.valid()) {
String pemDeployKey = pemDeployKeyField.asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
application = application.withDeployKey(deployKey);
messageBuilder.add("Added deploy key " + pemDeployKey);
}
controller.applications().store(application);
});
return new MessageResponse(messageBuilder.toString());
}
private com.yahoo.vespa.hosted.controller.Application getApplication(String tenantName, String applicationName) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
return controller.applications().getApplication(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private Instance getInstance(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
return controller.applications().getInstance(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, id);
Slime slime = new Slime();
Cursor nodesArray = slime.setObject().setArray("nodes");
for (Node node : nodes) {
Cursor nodeObject = nodesArray.addObject();
nodeObject.setString("hostname", node.hostname().value());
nodeObject.setString("state", valueOf(node.state()));
node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.flavor());
toSlime(node.resources(), nodeObject);
nodeObject.setBool("fastDisk", node.resources().diskSpeed() == NodeResources.DiskSpeed.fast);
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
return new SlimeJsonResponse(slime);
}
private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id);
Slime slime = new Slime();
Cursor clustersObject = slime.setObject().setObject("clusters");
for (Cluster cluster : application.clusters().values()) {
Cursor clusterObject = clustersObject.setObject(cluster.id().value());
toSlime(cluster.min(), clusterObject.setObject("min"));
toSlime(cluster.max(), clusterObject.setObject("max"));
toSlime(cluster.current(), clusterObject.setObject("current"));
cluster.target().ifPresent(target -> toSlime(target, clusterObject.setObject("target")));
cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested")));
}
return new SlimeJsonResponse(slime);
}
private static String valueOf(Node.State state) {
switch (state) {
case failed: return "failed";
case parked: return "parked";
case dirty: return "dirty";
case ready: return "ready";
case active: return "active";
case inactive: return "inactive";
case reserved: return "reserved";
case provisioned: return "provisioned";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ServiceState state) {
switch (state) {
case expectedUp: return "expectedUp";
case allowedDown: return "allowedDown";
case unorchestrated: return "unorchestrated";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ClusterType type) {
switch (type) {
case admin: return "admin";
case content: return "content";
case container: return "container";
case combined: return "combined";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
private static String valueOf(NodeResources.DiskSpeed diskSpeed) {
switch (diskSpeed) {
case fast : return "fast";
case slow : return "slow";
case any : return "any";
default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'");
}
}
private static String valueOf(NodeResources.StorageType storageType) {
switch (storageType) {
case remote : return "remote";
case local : return "local";
case any : return "any";
default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'");
}
}
private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters);
return new HttpResponse(200) {
@Override
public void render(OutputStream outputStream) throws IOException {
logStream.transferTo(outputStream);
}
};
}
private HttpResponse metrics(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
List<ProtonMetrics> protonMetrics = controller.serviceRegistry().configServer().getProtonMetrics(deployment);
return buildResponseFromProtonMetrics(protonMetrics);
}
private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
boolean requireTests = ! requestObject.field("skipTests").asBool();
boolean reTrigger = requestObject.field("reTrigger").asBool();
String triggered = reTrigger
? controller.applications().deploymentTrigger()
.reTrigger(id, type).type().jobName()
: controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests)
.stream().map(job -> job.type().jobName()).collect(joining(", "));
return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered"
: "Triggered " + triggered + " for " + id);
}
private HttpResponse pause(ApplicationId id, JobType type) {
Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause);
controller.applications().deploymentTrigger().pauseJob(id, type, until);
return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause);
}
private HttpResponse resume(ApplicationId id, JobType type) {
controller.applications().deploymentTrigger().resumeJob(id, type);
return new MessageResponse(type.jobName() + " for " + id + " resumed");
}
private void toSlime(Cursor object, com.yahoo.vespa.hosted.controller.Application application, HttpRequest request) {
object.setString("tenant", application.id().tenant().value());
object.setString("application", application.id().application().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/job/",
request.getUri()).toString());
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
application.instances().values().stream().findFirst().ifPresent(instance -> {
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
});
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request);
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
if (deploymentSpec.instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec.requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
globalEndpointsToSlime(object, instance);
List<Deployment> deployments = deploymentSpec.instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor deploymentsArray = object.setArray("deployments");
for (Deployment deployment : deployments) {
Cursor deploymentObject = deploymentsArray.addObject();
if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty())
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/instance/" + instance.name().value() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
}
private void globalEndpointsToSlime(Cursor object, Instance instance) {
var globalEndpointUrls = new LinkedHashSet<String>();
controller.routing().endpointsOf(instance.id())
.requiresRotation()
.not().legacy()
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalEndpointUrls::add);
var globalRotationsArray = object.setArray("globalRotations");
globalEndpointUrls.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
}
private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) {
com.yahoo.vespa.hosted.controller.Application application = status.application();
object.setString("tenant", instance.id().tenant().value());
object.setString("application", instance.id().application().value());
object.setString("instance", instance.id().instance().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + instance.id().tenant().value() +
"/application/" + instance.id().application().value() +
"/instance/" + instance.id().instance().value() + "/job/",
request.getUri()).toString());
application.latestVersion().ifPresent(version -> {
sourceRevisionToSlime(version.source(), object.setObject("source"));
version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
version.commit().ifPresent(commit -> object.setString("commit", commit));
});
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if (application.deploymentSpec().instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec().requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
globalEndpointsToSlime(object, instance);
List<Deployment> deployments =
application.deploymentSpec().instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor instancesArray = object.setArray("instances");
for (Deployment deployment : deployments) {
Cursor deploymentObject = instancesArray.addObject();
if (deployment.zone().environment() == Environment.prod) {
if (instance.rotations().size() == 1) {
toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment),
deploymentObject);
}
if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) {
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
}
}
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("instance", instance.id().instance().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
status.jobSteps().keySet().stream()
.filter(job -> job.application().instance().equals(instance.name()))
.filter(job -> job.type().isProduction() && job.type().isDeployment())
.map(job -> job.type().zone(controller.system()))
.filter(zone -> ! instance.deployments().containsKey(zone))
.forEach(zone -> {
Cursor deploymentObject = instancesArray.addObject();
deploymentObject.setString("environment", zone.environment().value());
deploymentObject.setString("region", zone.region().value());
});
application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key)));
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().getInstance(id)
.orElseThrow(() -> new NotExistsException(id + " not found"));
DeploymentId deploymentId = new DeploymentId(instance.id(),
ZoneId.from(environment, region));
Deployment deployment = instance.deployments().get(deploymentId.zoneId());
if (deployment == null)
throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId());
Slime slime = new Slime();
toSlime(slime.setObject(), deploymentId, deployment, request);
return new SlimeJsonResponse(slime);
}
private void toSlime(Cursor object, Change change) {
change.platform().ifPresent(version -> object.setString("version", version.toString()));
change.application()
.filter(version -> !version.isUnknown())
.ifPresent(version -> toSlime(version, object.setObject("revision")));
}
private void toSlime(Endpoint endpoint, Cursor object) {
object.setString("cluster", endpoint.cluster().value());
object.setBool("tls", endpoint.tls());
object.setString("url", endpoint.url().toString());
object.setString("scope", endpointScopeString(endpoint.scope()));
object.setString("routingMethod", routingMethodString(endpoint.routingMethod()));
}
private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) {
response.setString("tenant", deploymentId.applicationId().tenant().value());
response.setString("application", deploymentId.applicationId().application().value());
response.setString("instance", deploymentId.applicationId().instance().value());
response.setString("environment", deploymentId.zoneId().environment().value());
response.setString("region", deploymentId.zoneId().region().value());
var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId()));
var endpointArray = response.setArray("endpoints");
for (var endpoint : controller.routing().endpointsOf(deploymentId)
.scope(Endpoint.Scope.zone)
.not().legacy()) {
toSlime(endpoint, endpointArray.addObject());
}
var globalEndpoints = controller.routing().endpointsOf(application, deploymentId.applicationId().instance())
.not().legacy()
.targets(deploymentId.zoneId());
for (var endpoint : globalEndpoints) {
toSlime(endpoint, endpointArray.addObject());
}
response.setString("nodes", withPathAndQuery("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/", "recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString());
response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString());
response.setString("version", deployment.version().toFullString());
response.setString("revision", deployment.applicationVersion().id());
response.setLong("deployTimeEpochMs", deployment.at().toEpochMilli());
controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId())
.ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", deployment.at().plus(deploymentTimeToLive).toEpochMilli()));
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
var instance = application.instances().get(deploymentId.applicationId().instance());
if (instance != null) {
if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod)
toSlime(instance.rotations(), instance.rotationStatus(), deployment, response);
JobType.from(controller.system(), deployment.zone())
.map(type -> new JobId(instance.id(), type))
.map(status.jobSteps()::get)
.ifPresent(stepStatus -> {
JobControllerApiHandlerHelper.applicationVersionToSlime(
response.setObject("applicationVersion"), deployment.applicationVersion());
if (!status.jobsToRun().containsKey(stepStatus.job().get()))
response.setString("status", "complete");
else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true))
response.setString("status", "pending");
else response.setString("status", "running");
});
}
Cursor activity = response.setObject("activity");
deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried",
instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten",
instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
DeploymentMetrics metrics = deployment.metrics();
Cursor metricsObject = response.setObject("metrics");
metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond());
metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond());
metricsObject.setDouble("documentCount", metrics.documentCount());
metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis());
metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli()));
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if ( ! applicationVersion.isUnknown()) {
object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong());
object.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if (revision.isEmpty()) return;
object.setString("gitRepository", revision.get().repository());
object.setString("gitBranch", revision.get().branch());
object.setString("gitCommit", revision.get().commit());
}
private void toSlime(RotationState state, Cursor object) {
Cursor bcpStatus = object.setObject("bcpStatus");
bcpStatus.setString("rotationStatus", rotationStateString(state));
}
private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) {
var array = object.setArray("endpointStatus");
for (var rotation : rotations) {
var statusObject = array.addObject();
var targets = status.of(rotation.rotationId());
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("rotationId", rotation.rotationId().asString());
statusObject.setString("clusterId", rotation.clusterId().value());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli());
}
}
private URI monitoringSystemUri(DeploymentId deploymentId) {
return controller.zoneRegistry().getMonitoringSystemUri(deploymentId);
}
/**
* Returns a non-broken, released version at least as old as the oldest platform the given application is on.
*
* If no known version is applicable, the newest version at least as old as the oldest platform is selected,
* among all versions released for this system. If no such versions exists, throws an IllegalStateException.
*/
private Version compileVersion(TenantAndApplicationId id) {
Version oldestPlatform = controller.applications().oldestInstalledPlatform(id);
VersionStatus versionStatus = controller.versionStatus();
return versionStatus.versions().stream()
.filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low))
.filter(VespaVersion::isReleased)
.map(VespaVersion::versionNumber)
.filter(version -> ! version.isAfter(oldestPlatform))
.max(Comparator.naturalOrder())
.orElseGet(() -> controller.mavenRepository().metadata().versions().stream()
.filter(version -> ! version.isAfter(oldestPlatform))
.filter(version -> ! versionStatus.versions().stream()
.map(VespaVersion::versionNumber)
.collect(Collectors.toSet()).contains(version))
.max(Comparator.naturalOrder())
.orElseThrow(() -> new IllegalStateException("No available releases of " +
controller.mavenRepository().artifactId())));
}
private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
ZoneId zone = ZoneId.from(environment, region);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
var deploymentId = new DeploymentId(instance.id(), zone);
setGlobalRotationStatus(deploymentId, inService, request);
setGlobalEndpointStatus(deploymentId, inService, request);
return new MessageResponse(String.format("Successfully set %s in %s %s service",
instance.id().toShortString(), zone, inService ? "in" : "out of"));
}
/** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */
private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
var status = inService ? GlobalRouting.Status.in : GlobalRouting.Status.out;
controller.routing().policies().setGlobalRoutingStatus(deployment, status, agent);
}
/** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */
private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var requestData = toSlime(request.getData()).get();
var reason = mandatory("reason", requestData).asString();
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
long timestamp = controller.clock().instant().getEpochSecond();
var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp);
controller.routing().setGlobalRotationStatus(deployment, endpointStatus);
}
private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Slime slime = new Slime();
Cursor array = slime.setObject().setArray("globalrotationoverride");
controller.routing().globalRotationStatus(deploymentId)
.forEach((endpoint, status) -> {
array.addString(endpoint.upstreamIdOf(deploymentId));
Cursor statusObject = array.addObject();
statusObject.setString("status", status.getStatus().name());
statusObject.setString("reason", status.getReason() == null ? "" : status.getReason());
statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent());
statusObject.setLong("timestamp", status.getEpoch());
});
return new SlimeJsonResponse(slime);
}
private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().requireInstance(applicationId);
ZoneId zone = ZoneId.from(environment, region);
RotationId rotation = findRotationId(instance, endpointId);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
Slime slime = new Slime();
Cursor response = slime.setObject();
toSlime(instance.rotationStatus().of(rotation, deployment), response);
return new SlimeJsonResponse(slime);
}
private HttpResponse metering(String tenant, String application, HttpRequest request) {
Slime slime = new Slime();
Cursor root = slime.setObject();
MeteringData meteringData = controller.serviceRegistry()
.meteringService()
.getMeteringData(TenantName.from(tenant), ApplicationName.from(application));
ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringData.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringData.getLastMonth();
Cursor lastmonth = root.setObject("lastmonth");
lastmonth.setDouble("cpu", lastMonth.getCpuCores());
lastmonth.setDouble("mem", lastMonth.getMemoryGb());
lastmonth.setDouble("disk", lastMonth.getDiskGb());
Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory();
Cursor details = root.setObject("details");
Cursor detailsCpu = details.setObject("cpu");
Cursor detailsMem = details.setObject("mem");
Cursor detailsDisk = details.setObject("disk");
history.entrySet().stream()
.forEach(entry -> {
String instanceName = entry.getKey().instance().value();
Cursor detailsCpuApp = detailsCpu.setObject(instanceName);
Cursor detailsMemApp = detailsMem.setObject(instanceName);
Cursor detailsDiskApp = detailsDisk.setObject(instanceName);
Cursor detailsCpuData = detailsCpuApp.setArray("data");
Cursor detailsMemData = detailsMemApp.setArray("data");
Cursor detailsDiskData = detailsDiskApp.setArray("data");
entry.getValue().stream()
.forEach(resourceSnapshot -> {
Cursor cpu = detailsCpuData.addObject();
cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
cpu.setDouble("value", resourceSnapshot.getCpuCores());
Cursor mem = detailsMemData.addObject();
mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
mem.setDouble("value", resourceSnapshot.getMemoryGb());
Cursor disk = detailsDiskData.addObject();
disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
disk.setDouble("value", resourceSnapshot.getDiskGb());
});
});
return new SlimeJsonResponse(slime);
}
private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! instance.change().isEmpty()) {
instance.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", instance.change().isPinned());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
boolean suspended = controller.applications().isSuspended(deploymentId);
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setBool("suspended", suspended);
return new SlimeJsonResponse(slime);
}
private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region);
ServiceApiResponse response = new ServiceApiResponse(ZoneId.from(environment, region),
new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(),
controller.zoneRegistry().getConfigServerApiUris(ZoneId.from(environment, region)),
request.getUri());
response.setResponse(applicationView);
return response;
}
private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), ZoneId.from(environment, region));
if ("container-clustercontroller".equals((serviceName)) && restPath.contains("/status/")) {
String result = controller.serviceRegistry().configServer().getClusterControllerStatus(deploymentId, restPath);
return new HtmlResponse(result);
}
Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath);
ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(),
deploymentId.applicationId(),
controller.zoneRegistry().getConfigServerApiUris(deploymentId.zoneId()),
request.getUri());
response.setResponse(result, serviceName, restPath);
return response;
}
private HttpResponse updateTenant(String tenantName, HttpRequest request) {
getTenantOrThrow(tenantName);
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().update(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createTenant(String tenantName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().create(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest());
com.yahoo.vespa.hosted.controller.Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
if (controller.applications().getApplication(applicationId).isEmpty())
createApplication(tenantName, applicationName, request);
controller.applications().createInstance(applicationId.instance(instanceName));
Slime slime = new Slime();
toSlime(applicationId.instance(instanceName), slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
/** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */
private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) {
request = controller.auditLogger().log(request);
String versionString = readToString(request.getData());
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Version version = Version.fromString(versionString);
if (version.equals(Version.emptyVersion))
version = controller.systemVersion();
if ( ! systemHasVersion(version))
throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " +
"Version is not active in this system. " +
"Active versions: " + controller.versionStatus().versions()
.stream()
.map(VespaVersion::versionNumber)
.map(Version::toString)
.collect(joining(", ")));
Change change = Change.of(version);
if (pin)
change = change.withPin();
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Trigger deployment to the last known application package for the given application. */
private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) {
controller.auditLogger().log(request);
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */
private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = application.get().require(id.instance()).change();
if (change.isEmpty()) {
response.append("No deployment in progress for ").append(id).append(" at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Schedule restart of deployment, or specific host in a deployment */
private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
RestartFilter restartFilter = new RestartFilter()
.withHostName(Optional.ofNullable(request.getProperty("hostname")).map(HostName::from))
.withClusterType(Optional.ofNullable(request.getProperty("clusterType")).map(ClusterSpec.Type::from))
.withClusterId(Optional.ofNullable(request.getProperty("clusterId")).map(ClusterSpec.Id::from));
controller.applications().restart(deploymentId, restartFilter);
return new MessageResponse("Requested restart of " + deploymentId);
}
private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) {
if ( ! type.environment().isManuallyDeployed() && ! isOperator(request))
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("applicationZip"))
throw new IllegalArgumentException("Missing required form part 'applicationZip'");
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(id.tenant(),
Optional.of(id.instance()),
Optional.of(type.zone(controller.system())),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions"))
.map(json -> SlimeUtils.jsonToSlime(json).get())
.flatMap(options -> optional("vespaVersion", options))
.map(Version::fromString);
controller.jobController().deploy(id, type, version, applicationPackage);
RunId runId = controller.jobController().last(id, type).get().id();
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("message", "Deployment started in " + runId +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<com.yahoo.vespa.hosted.controller.Application> application = controller.applications().getApplication(TenantAndApplicationId.from(applicationId));
Inspector sourceRevision = deployOptions.field("sourceRevision");
Inspector buildNumber = deployOptions.field("buildNumber");
if (sourceRevision.valid() != buildNumber.valid())
throw new IllegalArgumentException("Source revision and build number must both be provided, or not");
Optional<ApplicationVersion> applicationVersion = Optional.empty();
if (sourceRevision.valid()) {
if (applicationPackage.isPresent())
throw new IllegalArgumentException("Application version and application package can't both be provided.");
applicationVersion = Optional.of(ApplicationVersion.from(toSourceRevision(sourceRevision),
buildNumber.asLong()));
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
boolean deployDirectly = deployOptions.field("deployDirectly").asBool();
Optional<Version> vespaVersion = optional("vespaVersion", deployOptions).map(Version::new);
if (deployDirectly && applicationPackage.isEmpty() && applicationVersion.isEmpty() && vespaVersion.isEmpty()) {
Optional<Deployment> deployment = controller.applications().getInstance(applicationId)
.map(Instance::deployments)
.flatMap(deployments -> Optional.ofNullable(deployments.get(zone)));
if(deployment.isEmpty())
throw new IllegalArgumentException("Can't redeploy application, no deployment currently exist");
ApplicationVersion version = deployment.get().applicationVersion();
if(version.isUnknown())
throw new IllegalArgumentException("Can't redeploy application, application version is unknown");
applicationVersion = Optional.of(version);
vespaVersion = Optional.of(deployment.get().version());
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
Optional.of(applicationId.instance()),
Optional.of(zone),
aPackage,
Optional.of(requireUserPrincipal(request))));
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass);
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if (tenant.isEmpty())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
controller.tenants().delete(tenant.get().name(),
accessControlRequests.credentials(tenant.get().name(),
toSlime(request.getData()).get(),
request.getJDiscRequest()));
return tenant(tenant.get(), request);
}
private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
return new MessageResponse("Deleted application " + id);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty()) {
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
}
return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
controller.applications().deactivate(id.applicationId(), id.zoneId());
return new MessageResponse("Deactivated " + id);
}
/** Returns test config for indicated job, with production deployments of the default instance. */
private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
HashSet<DeploymentId> deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toCollection(HashSet::new));
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.routing().zoneEndpointsOf(deployments),
controller.applications().contentClustersByZone(deployments)));
}
private static SourceRevision toSourceRevision(Inspector object) {
if (!object.field("repository").valid() ||
!object.field("branch").valid() ||
!object.field("commit").valid()) {
throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\".");
}
return new SourceRevision(object.field("repository").asString(),
object.field("branch").asString(),
object.field("commit").asString());
}
private Tenant getTenantOrThrow(String tenantName) {
return controller.tenants().get(tenantName)
.orElseThrow(() -> new NotExistsException(new TenantId(tenantName)));
}
private void toSlime(Cursor object, Tenant tenant, HttpRequest request) {
object.setString("tenant", tenant.name().value());
object.setString("type", tenantType(tenant));
List<com.yahoo.vespa.hosted.controller.Application> applications = controller.applications().asList(tenant.name());
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
object.setString("athensDomain", athenzTenant.domain().getName());
object.setString("property", athenzTenant.property().id());
athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString()));
athenzTenant.contact().ifPresent(c -> {
object.setString("propertyUrl", c.propertyUrl().toString());
object.setString("contactsUrl", c.url().toString());
object.setString("issueCreationUrl", c.issueTrackerUrl().toString());
Cursor contactsArray = object.setArray("contacts");
c.persons().forEach(persons -> {
Cursor personArray = contactsArray.addArray();
persons.forEach(personArray::addString);
});
});
break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
cloudTenant.creator().ifPresent(creator -> object.setString("creator", creator.getName()));
Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys");
cloudTenant.developerKeys().forEach((key, user) -> {
Cursor keyObject = pemDeveloperKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", user.getName());
});
break;
}
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
Cursor applicationArray = object.setArray("applications");
for (com.yahoo.vespa.hosted.controller.Application application : applications) {
DeploymentStatus status = controller.jobController().deploymentStatus(application);
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, status, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
}
private void toSlime(ClusterResources resources, Cursor object) {
object.setLong("nodes", resources.nodes());
object.setLong("groups", resources.groups());
toSlime(resources.nodeResources(), object.setObject("nodeResources"));
if ( ! controller.zoneRegistry().system().isPublic())
object.setDouble("cost", Math.round(resources.nodes() * resources.nodeResources().cost() * 100.0 / 3.0) / 100.0);
}
private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", valueOf(resources.diskSpeed()));
object.setString("storageType", valueOf(resources.storageType()));
}
private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) {
object.setString("tenant", tenant.name().value());
Cursor metaData = object.setObject("metaData");
metaData.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
metaData.setString("athensDomain", athenzTenant.domain().getName());
metaData.setString("property", athenzTenant.property().id());
break;
case cloud: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString());
}
/** Returns a copy of the given URI with the host and port from the given URI, the path set to the given path and the query set to given query*/
private URI withPathAndQuery(String newPath, String newQuery, URI uri) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, newQuery, null);
}
catch (URISyntaxException e) {
throw new RuntimeException("Will not happen", e);
}
}
/** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */
private URI withPath(String newPath, URI uri) {
return withPathAndQuery(newPath, null, uri);
}
private long asLong(String valueOrNull, long defaultWhenNull) {
if (valueOrNull == null) return defaultWhenNull;
try {
return Long.parseLong(valueOrNull);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'");
}
}
private void toSlime(Run run, Cursor object) {
object.setLong("id", run.id().number());
object.setString("version", run.versions().targetPlatform().toFullString());
if ( ! run.versions().targetApplication().isUnknown())
toSlime(run.versions().targetApplication(), object.setObject("revision"));
object.setString("reason", "unknown reason");
object.setLong("at", run.end().orElse(run.start()).toEpochMilli());
}
private Slime toSlime(InputStream jsonStream) {
try {
byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000);
return SlimeUtils.jsonToSlime(jsonBytes);
} catch (IOException e) {
throw new RuntimeException();
}
}
private static Principal requireUserPrincipal(HttpRequest request) {
Principal principal = request.getJDiscRequest().getUserPrincipal();
if (principal == null) throw new InternalServerErrorException("Expected a user principal");
return principal;
}
private Inspector mandatory(String key, Inspector object) {
if ( ! object.field(key).valid())
throw new IllegalArgumentException("'" + key + "' is missing");
return object.field(key);
}
private Optional<String> optional(String key, Inspector object) {
return SlimeUtils.optionalString(object.field(key));
}
private static String path(Object... elements) {
return Joiner.on("/").join(elements);
}
private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value(),
request.getUri()).toString());
}
private void toSlime(ApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value() +
"/instance/" + id.instance().value(),
request.getUri()).toString());
}
private Slime toSlime(ActivateResult result) {
Slime slime = new Slime();
Cursor object = slime.setObject();
object.setString("revisionId", result.revisionId().id());
object.setLong("applicationZipSize", result.applicationZipSizeBytes());
Cursor logArray = object.setArray("prepareMessages");
if (result.prepareResponse().log != null) {
for (Log logMessage : result.prepareResponse().log) {
Cursor logObject = logArray.addObject();
logObject.setLong("time", logMessage.time);
logObject.setString("level", logMessage.level);
logObject.setString("message", logMessage.message);
}
}
Cursor changeObject = object.setObject("configChangeActions");
Cursor restartActionsArray = changeObject.setArray("restart");
for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) {
Cursor restartActionObject = restartActionsArray.addObject();
restartActionObject.setString("clusterName", restartAction.clusterName);
restartActionObject.setString("clusterType", restartAction.clusterType);
restartActionObject.setString("serviceType", restartAction.serviceType);
serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services"));
stringsToSlime(restartAction.messages, restartActionObject.setArray("messages"));
}
Cursor refeedActionsArray = changeObject.setArray("refeed");
for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) {
Cursor refeedActionObject = refeedActionsArray.addObject();
refeedActionObject.setString("name", refeedAction.name);
refeedActionObject.setBool("allowed", refeedAction.allowed);
refeedActionObject.setString("documentType", refeedAction.documentType);
refeedActionObject.setString("clusterName", refeedAction.clusterName);
serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services"));
stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages"));
}
return slime;
}
private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) {
for (ServiceInfo serviceInfo : serviceInfoList) {
Cursor serviceInfoObject = array.addObject();
serviceInfoObject.setString("serviceName", serviceInfo.serviceName);
serviceInfoObject.setString("serviceType", serviceInfo.serviceType);
serviceInfoObject.setString("configId", serviceInfo.configId);
serviceInfoObject.setString("hostName", serviceInfo.hostName);
}
}
private void stringsToSlime(List<String> strings, Cursor array) {
for (String string : strings)
array.addString(string);
}
private String readToString(InputStream stream) {
Scanner scanner = new Scanner(stream).useDelimiter("\\A");
if ( ! scanner.hasNext()) return null;
return scanner.next();
}
private boolean systemHasVersion(Version version) {
return controller.versionStatus().versions().stream().anyMatch(v -> v.versionNumber().equals(version));
}
private static boolean recurseOverTenants(HttpRequest request) {
return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive"));
}
private static boolean recurseOverApplications(HttpRequest request) {
return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive"));
}
private static boolean recurseOverDeployments(HttpRequest request) {
return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive"));
}
private static boolean showOnlyProductionInstances(HttpRequest request) {
return "true".equals(request.getProperty("production"));
}
private static String tenantType(Tenant tenant) {
switch (tenant.type()) {
case athenz: return "ATHENS";
case cloud: return "CLOUD";
default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName());
}
}
private static ApplicationId appIdFromPath(Path path) {
return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance"));
}
private static JobType jobTypeFromPath(Path path) {
return JobType.fromJobName(path.get("jobtype"));
}
private static RunId runIdFromPath(Path path) {
long number = Long.parseLong(path.get("number"));
return new RunId(appIdFromPath(path), jobTypeFromPath(path), number);
}
private HttpResponse submit(String tenant, String application, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
Optional<String> repository = optional("repository", submitOptions);
Optional<String> branch = optional("branch", submitOptions);
Optional<String> commit = optional("commit", submitOptions);
Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent()
? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get()))
: Optional.empty();
Optional<String> sourceUrl = optional("sourceUrl", submitOptions);
Optional<String> authorEmail = optional("authorEmail", submitOptions);
sourceUrl.map(URI::create).ifPresent(url -> {
if (url.getHost() == null || url.getScheme() == null)
throw new IllegalArgumentException("Source URL must include scheme and host");
});
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true);
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
Optional.empty(),
Optional.empty(),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
sourceUrl,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
private HttpResponse removeAllProdDeployments(String tenant, String application) {
JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application,
Optional.empty(), Optional.empty(), Optional.empty(), 1,
ApplicationPackage.deploymentRemoval(), new byte[0]);
return new MessageResponse("All deployments removed");
}
private static Map<String, byte[]> parseDataParts(HttpRequest request) {
String contentHash = request.getHeader("x-Content-Hash");
if (contentHash == null)
return new MultipartParser().parse(request);
DigestInputStream digester = Signatures.sha256Digester(request.getData());
var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri());
if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash)))
throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash");
return dataParts;
}
private static RotationId findRotationId(Instance instance, Optional<String> endpointId) {
if (instance.rotations().isEmpty()) {
throw new NotExistsException("global rotation does not exist for " + instance);
}
if (endpointId.isPresent()) {
return instance.rotations().stream()
.filter(r -> r.endpointId().id().equals(endpointId.get()))
.map(AssignedRotation::rotationId)
.findFirst()
.orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() +
" does not exist for " + instance));
} else if (instance.rotations().size() > 1) {
throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given");
}
return instance.rotations().get(0).rotationId();
}
private static String rotationStateString(RotationState state) {
switch (state) {
case in: return "IN";
case out: return "OUT";
}
return "UNKNOWN";
}
private static String endpointScopeString(Endpoint.Scope scope) {
switch (scope) {
case region: return "region";
case global: return "global";
case zone: return "zone";
}
throw new IllegalArgumentException("Unknown endpoint scope " + scope);
}
private static String routingMethodString(RoutingMethod method) {
switch (method) {
case exclusive: return "exclusive";
case shared: return "shared";
case sharedLayer4: return "sharedLayer4";
}
throw new IllegalArgumentException("Unknown routing method " + method);
}
private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) {
return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName))
.filter(cls::isInstance)
.map(cls::cast)
.orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request"));
}
/** Returns whether given request is by an operator */
private static boolean isOperator(HttpRequest request) {
var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class);
return securityContext.roles().stream()
.map(Role::definition)
.anyMatch(definition -> definition == RoleDefinition.hostedOperator);
}
} |
tenant/application/environment/region/instance is the legacy order, change this to tenant/application/instance/environment/region | private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/tenant")) return tenants(request);
if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/metrics")) return metrics(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
return ErrorResponse.notFoundError("Nothing at " + path);
} | if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/metrics")) return metrics(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region")); | private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/tenant")) return tenants(request);
if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/metrics")) return metrics(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
return ErrorResponse.notFoundError("Nothing at " + path);
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestConfigSerializer testConfigSerializer;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
}
@Override
public Duration getTimeout() {
return Duration.ofMinutes(20);
}
@Override
public HttpResponse handle(HttpRequest request) {
try {
Path path = new Path(request.getUri(), OPTIONAL_PREFIX);
switch (request.getMethod()) {
case GET: return handleGET(path, request);
case PUT: return handlePUT(path, request);
case POST: return handlePOST(path, request);
case PATCH: return handlePATCH(path, request);
case DELETE: return handleDELETE(path, request);
case OPTIONS: return handleOPTIONS();
default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
}
}
catch (ForbiddenException e) {
return ErrorResponse.forbidden(Exceptions.toMessageString(e));
}
catch (NotAuthorizedException e) {
return ErrorResponse.unauthorized(Exceptions.toMessageString(e));
}
catch (NotExistsException e) {
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
}
catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
catch (ConfigServerException e) {
switch (e.getErrorCode()) {
case NOT_FOUND:
return new ErrorResponse(NOT_FOUND, e.getErrorCode().name(), Exceptions.toMessageString(e));
case ACTIVATION_CONFLICT:
return new ErrorResponse(CONFLICT, e.getErrorCode().name(), Exceptions.toMessageString(e));
case INTERNAL_SERVER_ERROR:
return new ErrorResponse(INTERNAL_SERVER_ERROR, e.getErrorCode().name(), Exceptions.toMessageString(e));
default:
return new ErrorResponse(BAD_REQUEST, e.getErrorCode().name(), Exceptions.toMessageString(e));
}
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handlePUT(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePATCH(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleDELETE(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeAllProdDeployments(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleOPTIONS() {
EmptyResponse response = new EmptyResponse();
response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS");
return response;
}
private HttpResponse recursiveRoot(HttpRequest request) {
Slime slime = new Slime();
Cursor tenantArray = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
toSlime(tenantArray.addObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse root(HttpRequest request) {
return recurseOverTenants(request)
? recursiveRoot(request)
: new ResourceResponse(request, "tenant");
}
private HttpResponse tenants(HttpRequest request) {
Slime slime = new Slime();
Cursor response = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject());
return new SlimeJsonResponse(slime);
}
private HttpResponse tenant(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenant(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenant(Tenant tenant, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
if (controller.tenants().get(tenantName).isEmpty())
return ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist");
Slime slime = new Slime();
Cursor applicationArray = slime.setArray();
for (com.yahoo.vespa.hosted.controller.Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true)) {
Cursor applicationObject = applicationArray.addObject();
applicationObject.setString("tenant", application.id().tenant().value());
applicationObject.setString("application", application.id().application().value());
applicationObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value(),
request.getUri()).toString());
Cursor instanceArray = applicationObject.setArray("instances");
for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet()
: application.instances().keySet()) {
Cursor instanceObject = instanceArray.addObject();
instanceObject.setString("instance", instance.value());
instanceObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/instance/" + instance.value(),
request.getUri()).toString());
}
}
}
return new SlimeJsonResponse(slime);
}
private HttpResponse devApplicationPackage(ApplicationId id, JobType type) {
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Only manually deployed zones have dev packages");
ZoneId zone = type.zone(controller.system());
byte[] applicationPackage = controller.applications().applicationStore().getDev(id, zone);
return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage);
}
private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse compileVersion(String tenantName, String applicationName) {
Slime slime = new Slime();
slime.setObject().setString("compileVersion",
compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString());
return new SlimeJsonResponse(slime);
}
private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
Principal user = request.getJDiscRequest().getUserPrincipal();
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withDeveloperKey(developerKey, user);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Principal user = ((CloudTenant) controller.tenants().require(TenantName.from(tenantName))).developerKeys().get(developerKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withoutDeveloperKey(developerKey);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) {
keys.forEach((key, principal) -> {
Cursor keyObject = keysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", principal.getName());
});
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withoutDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes.");
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
Inspector majorVersionField = requestObject.field("majorVersion");
if (majorVersionField.valid()) {
Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong();
application = application.withMajorVersion(majorVersion);
messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion));
}
Inspector pemDeployKeyField = requestObject.field("pemDeployKey");
if (pemDeployKeyField.valid()) {
String pemDeployKey = pemDeployKeyField.asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
application = application.withDeployKey(deployKey);
messageBuilder.add("Added deploy key " + pemDeployKey);
}
controller.applications().store(application);
});
return new MessageResponse(messageBuilder.toString());
}
private com.yahoo.vespa.hosted.controller.Application getApplication(String tenantName, String applicationName) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
return controller.applications().getApplication(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private Instance getInstance(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
return controller.applications().getInstance(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, id);
Slime slime = new Slime();
Cursor nodesArray = slime.setObject().setArray("nodes");
for (Node node : nodes) {
Cursor nodeObject = nodesArray.addObject();
nodeObject.setString("hostname", node.hostname().value());
nodeObject.setString("state", valueOf(node.state()));
node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.flavor());
toSlime(node.resources(), nodeObject);
nodeObject.setBool("fastDisk", node.resources().diskSpeed() == NodeResources.DiskSpeed.fast);
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
return new SlimeJsonResponse(slime);
}
private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id);
Slime slime = new Slime();
Cursor clustersObject = slime.setObject().setObject("clusters");
for (Cluster cluster : application.clusters().values()) {
Cursor clusterObject = clustersObject.setObject(cluster.id().value());
toSlime(cluster.min(), clusterObject.setObject("min"));
toSlime(cluster.max(), clusterObject.setObject("max"));
toSlime(cluster.current(), clusterObject.setObject("current"));
cluster.target().ifPresent(target -> toSlime(target, clusterObject.setObject("target")));
cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested")));
}
return new SlimeJsonResponse(slime);
}
private static String valueOf(Node.State state) {
switch (state) {
case failed: return "failed";
case parked: return "parked";
case dirty: return "dirty";
case ready: return "ready";
case active: return "active";
case inactive: return "inactive";
case reserved: return "reserved";
case provisioned: return "provisioned";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ServiceState state) {
switch (state) {
case expectedUp: return "expectedUp";
case allowedDown: return "allowedDown";
case unorchestrated: return "unorchestrated";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ClusterType type) {
switch (type) {
case admin: return "admin";
case content: return "content";
case container: return "container";
case combined: return "combined";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
private static String valueOf(NodeResources.DiskSpeed diskSpeed) {
switch (diskSpeed) {
case fast : return "fast";
case slow : return "slow";
case any : return "any";
default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'");
}
}
private static String valueOf(NodeResources.StorageType storageType) {
switch (storageType) {
case remote : return "remote";
case local : return "local";
case any : return "any";
default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'");
}
}
private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters);
return new HttpResponse(200) {
@Override
public void render(OutputStream outputStream) throws IOException {
logStream.transferTo(outputStream);
}
};
}
private HttpResponse metrics(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
List<ProtonMetrics> protonMetrics = controller.serviceRegistry().configServer().getProtonMetrics(deployment);
return buildResponseFromProtonMetrics(protonMetrics);
}
private JsonResponse buildResponseFromProtonMetrics(List<ProtonMetrics> protonMetrics) {
try {
var jsonObject = new JSONObject();
var jsonArray = new JSONArray();
for (ProtonMetrics metrics : protonMetrics) {
jsonArray.put(metrics.toJson());
}
jsonObject.put("metrics", jsonArray);
return new JsonResponse(200, jsonObject.toString());
} catch (JSONException e) {
log.severe("Unable to build JsonResponse with Proton data");
return new JsonResponse(500, "");
}
}
private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
boolean requireTests = ! requestObject.field("skipTests").asBool();
boolean reTrigger = requestObject.field("reTrigger").asBool();
String triggered = reTrigger
? controller.applications().deploymentTrigger()
.reTrigger(id, type).type().jobName()
: controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests)
.stream().map(job -> job.type().jobName()).collect(joining(", "));
return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered"
: "Triggered " + triggered + " for " + id);
}
private HttpResponse pause(ApplicationId id, JobType type) {
Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause);
controller.applications().deploymentTrigger().pauseJob(id, type, until);
return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause);
}
private HttpResponse resume(ApplicationId id, JobType type) {
controller.applications().deploymentTrigger().resumeJob(id, type);
return new MessageResponse(type.jobName() + " for " + id + " resumed");
}
private void toSlime(Cursor object, com.yahoo.vespa.hosted.controller.Application application, HttpRequest request) {
object.setString("tenant", application.id().tenant().value());
object.setString("application", application.id().application().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/job/",
request.getUri()).toString());
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
application.instances().values().stream().findFirst().ifPresent(instance -> {
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
});
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request);
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
if (deploymentSpec.instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec.requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
globalEndpointsToSlime(object, instance);
List<Deployment> deployments = deploymentSpec.instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor deploymentsArray = object.setArray("deployments");
for (Deployment deployment : deployments) {
Cursor deploymentObject = deploymentsArray.addObject();
if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty())
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/instance/" + instance.name().value() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
}
private void globalEndpointsToSlime(Cursor object, Instance instance) {
var globalEndpointUrls = new LinkedHashSet<String>();
controller.routing().endpointsOf(instance.id())
.requiresRotation()
.not().legacy()
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalEndpointUrls::add);
var globalRotationsArray = object.setArray("globalRotations");
globalEndpointUrls.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
}
private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) {
com.yahoo.vespa.hosted.controller.Application application = status.application();
object.setString("tenant", instance.id().tenant().value());
object.setString("application", instance.id().application().value());
object.setString("instance", instance.id().instance().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + instance.id().tenant().value() +
"/application/" + instance.id().application().value() +
"/instance/" + instance.id().instance().value() + "/job/",
request.getUri()).toString());
application.latestVersion().ifPresent(version -> {
sourceRevisionToSlime(version.source(), object.setObject("source"));
version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
version.commit().ifPresent(commit -> object.setString("commit", commit));
});
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if (application.deploymentSpec().instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec().requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
globalEndpointsToSlime(object, instance);
List<Deployment> deployments =
application.deploymentSpec().instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor instancesArray = object.setArray("instances");
for (Deployment deployment : deployments) {
Cursor deploymentObject = instancesArray.addObject();
if (deployment.zone().environment() == Environment.prod) {
if (instance.rotations().size() == 1) {
toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment),
deploymentObject);
}
if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) {
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
}
}
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("instance", instance.id().instance().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
status.jobSteps().keySet().stream()
.filter(job -> job.application().instance().equals(instance.name()))
.filter(job -> job.type().isProduction() && job.type().isDeployment())
.map(job -> job.type().zone(controller.system()))
.filter(zone -> ! instance.deployments().containsKey(zone))
.forEach(zone -> {
Cursor deploymentObject = instancesArray.addObject();
deploymentObject.setString("environment", zone.environment().value());
deploymentObject.setString("region", zone.region().value());
});
application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key)));
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().getInstance(id)
.orElseThrow(() -> new NotExistsException(id + " not found"));
DeploymentId deploymentId = new DeploymentId(instance.id(),
ZoneId.from(environment, region));
Deployment deployment = instance.deployments().get(deploymentId.zoneId());
if (deployment == null)
throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId());
Slime slime = new Slime();
toSlime(slime.setObject(), deploymentId, deployment, request);
return new SlimeJsonResponse(slime);
}
private void toSlime(Cursor object, Change change) {
change.platform().ifPresent(version -> object.setString("version", version.toString()));
change.application()
.filter(version -> !version.isUnknown())
.ifPresent(version -> toSlime(version, object.setObject("revision")));
}
private void toSlime(Endpoint endpoint, Cursor object) {
object.setString("cluster", endpoint.cluster().value());
object.setBool("tls", endpoint.tls());
object.setString("url", endpoint.url().toString());
object.setString("scope", endpointScopeString(endpoint.scope()));
object.setString("routingMethod", routingMethodString(endpoint.routingMethod()));
}
private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) {
response.setString("tenant", deploymentId.applicationId().tenant().value());
response.setString("application", deploymentId.applicationId().application().value());
response.setString("instance", deploymentId.applicationId().instance().value());
response.setString("environment", deploymentId.zoneId().environment().value());
response.setString("region", deploymentId.zoneId().region().value());
var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId()));
var endpointArray = response.setArray("endpoints");
for (var endpoint : controller.routing().endpointsOf(deploymentId)
.scope(Endpoint.Scope.zone)
.not().legacy()) {
toSlime(endpoint, endpointArray.addObject());
}
var globalEndpoints = controller.routing().endpointsOf(application, deploymentId.applicationId().instance())
.not().legacy()
.targets(deploymentId.zoneId());
for (var endpoint : globalEndpoints) {
toSlime(endpoint, endpointArray.addObject());
}
response.setString("nodes", withPathAndQuery("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/", "recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString());
response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString());
response.setString("version", deployment.version().toFullString());
response.setString("revision", deployment.applicationVersion().id());
response.setLong("deployTimeEpochMs", deployment.at().toEpochMilli());
controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId())
.ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", deployment.at().plus(deploymentTimeToLive).toEpochMilli()));
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
var instance = application.instances().get(deploymentId.applicationId().instance());
if (instance != null) {
if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod)
toSlime(instance.rotations(), instance.rotationStatus(), deployment, response);
JobType.from(controller.system(), deployment.zone())
.map(type -> new JobId(instance.id(), type))
.map(status.jobSteps()::get)
.ifPresent(stepStatus -> {
JobControllerApiHandlerHelper.applicationVersionToSlime(
response.setObject("applicationVersion"), deployment.applicationVersion());
if (!status.jobsToRun().containsKey(stepStatus.job().get()))
response.setString("status", "complete");
else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true))
response.setString("status", "pending");
else response.setString("status", "running");
});
}
Cursor activity = response.setObject("activity");
deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried",
instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten",
instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
DeploymentMetrics metrics = deployment.metrics();
Cursor metricsObject = response.setObject("metrics");
metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond());
metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond());
metricsObject.setDouble("documentCount", metrics.documentCount());
metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis());
metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli()));
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if ( ! applicationVersion.isUnknown()) {
object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong());
object.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if (revision.isEmpty()) return;
object.setString("gitRepository", revision.get().repository());
object.setString("gitBranch", revision.get().branch());
object.setString("gitCommit", revision.get().commit());
}
private void toSlime(RotationState state, Cursor object) {
Cursor bcpStatus = object.setObject("bcpStatus");
bcpStatus.setString("rotationStatus", rotationStateString(state));
}
private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) {
var array = object.setArray("endpointStatus");
for (var rotation : rotations) {
var statusObject = array.addObject();
var targets = status.of(rotation.rotationId());
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("rotationId", rotation.rotationId().asString());
statusObject.setString("clusterId", rotation.clusterId().value());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli());
}
}
private URI monitoringSystemUri(DeploymentId deploymentId) {
return controller.zoneRegistry().getMonitoringSystemUri(deploymentId);
}
/**
* Returns a non-broken, released version at least as old as the oldest platform the given application is on.
*
* If no known version is applicable, the newest version at least as old as the oldest platform is selected,
* among all versions released for this system. If no such versions exists, throws an IllegalStateException.
*/
private Version compileVersion(TenantAndApplicationId id) {
Version oldestPlatform = controller.applications().oldestInstalledPlatform(id);
VersionStatus versionStatus = controller.versionStatus();
return versionStatus.versions().stream()
.filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low))
.filter(VespaVersion::isReleased)
.map(VespaVersion::versionNumber)
.filter(version -> ! version.isAfter(oldestPlatform))
.max(Comparator.naturalOrder())
.orElseGet(() -> controller.mavenRepository().metadata().versions().stream()
.filter(version -> ! version.isAfter(oldestPlatform))
.filter(version -> ! versionStatus.versions().stream()
.map(VespaVersion::versionNumber)
.collect(Collectors.toSet()).contains(version))
.max(Comparator.naturalOrder())
.orElseThrow(() -> new IllegalStateException("No available releases of " +
controller.mavenRepository().artifactId())));
}
private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
ZoneId zone = ZoneId.from(environment, region);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
var deploymentId = new DeploymentId(instance.id(), zone);
setGlobalRotationStatus(deploymentId, inService, request);
setGlobalEndpointStatus(deploymentId, inService, request);
return new MessageResponse(String.format("Successfully set %s in %s %s service",
instance.id().toShortString(), zone, inService ? "in" : "out of"));
}
/** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */
private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
var status = inService ? GlobalRouting.Status.in : GlobalRouting.Status.out;
controller.routing().policies().setGlobalRoutingStatus(deployment, status, agent);
}
/** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */
private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var requestData = toSlime(request.getData()).get();
var reason = mandatory("reason", requestData).asString();
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
long timestamp = controller.clock().instant().getEpochSecond();
var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp);
controller.routing().setGlobalRotationStatus(deployment, endpointStatus);
}
private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Slime slime = new Slime();
Cursor array = slime.setObject().setArray("globalrotationoverride");
controller.routing().globalRotationStatus(deploymentId)
.forEach((endpoint, status) -> {
array.addString(endpoint.upstreamIdOf(deploymentId));
Cursor statusObject = array.addObject();
statusObject.setString("status", status.getStatus().name());
statusObject.setString("reason", status.getReason() == null ? "" : status.getReason());
statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent());
statusObject.setLong("timestamp", status.getEpoch());
});
return new SlimeJsonResponse(slime);
}
private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().requireInstance(applicationId);
ZoneId zone = ZoneId.from(environment, region);
RotationId rotation = findRotationId(instance, endpointId);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
Slime slime = new Slime();
Cursor response = slime.setObject();
toSlime(instance.rotationStatus().of(rotation, deployment), response);
return new SlimeJsonResponse(slime);
}
private HttpResponse metering(String tenant, String application, HttpRequest request) {
Slime slime = new Slime();
Cursor root = slime.setObject();
MeteringData meteringData = controller.serviceRegistry()
.meteringService()
.getMeteringData(TenantName.from(tenant), ApplicationName.from(application));
ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringData.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringData.getLastMonth();
Cursor lastmonth = root.setObject("lastmonth");
lastmonth.setDouble("cpu", lastMonth.getCpuCores());
lastmonth.setDouble("mem", lastMonth.getMemoryGb());
lastmonth.setDouble("disk", lastMonth.getDiskGb());
Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory();
Cursor details = root.setObject("details");
Cursor detailsCpu = details.setObject("cpu");
Cursor detailsMem = details.setObject("mem");
Cursor detailsDisk = details.setObject("disk");
history.entrySet().stream()
.forEach(entry -> {
String instanceName = entry.getKey().instance().value();
Cursor detailsCpuApp = detailsCpu.setObject(instanceName);
Cursor detailsMemApp = detailsMem.setObject(instanceName);
Cursor detailsDiskApp = detailsDisk.setObject(instanceName);
Cursor detailsCpuData = detailsCpuApp.setArray("data");
Cursor detailsMemData = detailsMemApp.setArray("data");
Cursor detailsDiskData = detailsDiskApp.setArray("data");
entry.getValue().stream()
.forEach(resourceSnapshot -> {
Cursor cpu = detailsCpuData.addObject();
cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
cpu.setDouble("value", resourceSnapshot.getCpuCores());
Cursor mem = detailsMemData.addObject();
mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
mem.setDouble("value", resourceSnapshot.getMemoryGb());
Cursor disk = detailsDiskData.addObject();
disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
disk.setDouble("value", resourceSnapshot.getDiskGb());
});
});
return new SlimeJsonResponse(slime);
}
private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! instance.change().isEmpty()) {
instance.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", instance.change().isPinned());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
boolean suspended = controller.applications().isSuspended(deploymentId);
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setBool("suspended", suspended);
return new SlimeJsonResponse(slime);
}
private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region);
ServiceApiResponse response = new ServiceApiResponse(ZoneId.from(environment, region),
new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(),
controller.zoneRegistry().getConfigServerApiUris(ZoneId.from(environment, region)),
request.getUri());
response.setResponse(applicationView);
return response;
}
private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), ZoneId.from(environment, region));
if ("container-clustercontroller".equals((serviceName)) && restPath.contains("/status/")) {
String result = controller.serviceRegistry().configServer().getClusterControllerStatus(deploymentId, restPath);
return new HtmlResponse(result);
}
Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath);
ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(),
deploymentId.applicationId(),
controller.zoneRegistry().getConfigServerApiUris(deploymentId.zoneId()),
request.getUri());
response.setResponse(result, serviceName, restPath);
return response;
}
private HttpResponse updateTenant(String tenantName, HttpRequest request) {
getTenantOrThrow(tenantName);
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().update(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createTenant(String tenantName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().create(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest());
com.yahoo.vespa.hosted.controller.Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
if (controller.applications().getApplication(applicationId).isEmpty())
createApplication(tenantName, applicationName, request);
controller.applications().createInstance(applicationId.instance(instanceName));
Slime slime = new Slime();
toSlime(applicationId.instance(instanceName), slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
/** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */
private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) {
request = controller.auditLogger().log(request);
String versionString = readToString(request.getData());
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Version version = Version.fromString(versionString);
if (version.equals(Version.emptyVersion))
version = controller.systemVersion();
if ( ! systemHasVersion(version))
throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " +
"Version is not active in this system. " +
"Active versions: " + controller.versionStatus().versions()
.stream()
.map(VespaVersion::versionNumber)
.map(Version::toString)
.collect(joining(", ")));
Change change = Change.of(version);
if (pin)
change = change.withPin();
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Trigger deployment to the last known application package for the given application. */
private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) {
controller.auditLogger().log(request);
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */
private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = application.get().require(id.instance()).change();
if (change.isEmpty()) {
response.append("No deployment in progress for ").append(id).append(" at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Schedule restart of deployment, or specific host in a deployment */
private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
RestartFilter restartFilter = new RestartFilter()
.withHostName(Optional.ofNullable(request.getProperty("hostname")).map(HostName::from))
.withClusterType(Optional.ofNullable(request.getProperty("clusterType")).map(ClusterSpec.Type::from))
.withClusterId(Optional.ofNullable(request.getProperty("clusterId")).map(ClusterSpec.Id::from));
controller.applications().restart(deploymentId, restartFilter);
return new MessageResponse("Requested restart of " + deploymentId);
}
private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) {
if ( ! type.environment().isManuallyDeployed() && ! isOperator(request))
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("applicationZip"))
throw new IllegalArgumentException("Missing required form part 'applicationZip'");
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(id.tenant(),
Optional.of(id.instance()),
Optional.of(type.zone(controller.system())),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions"))
.map(json -> SlimeUtils.jsonToSlime(json).get())
.flatMap(options -> optional("vespaVersion", options))
.map(Version::fromString);
controller.jobController().deploy(id, type, version, applicationPackage);
RunId runId = controller.jobController().last(id, type).get().id();
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("message", "Deployment started in " + runId +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<com.yahoo.vespa.hosted.controller.Application> application = controller.applications().getApplication(TenantAndApplicationId.from(applicationId));
Inspector sourceRevision = deployOptions.field("sourceRevision");
Inspector buildNumber = deployOptions.field("buildNumber");
if (sourceRevision.valid() != buildNumber.valid())
throw new IllegalArgumentException("Source revision and build number must both be provided, or not");
Optional<ApplicationVersion> applicationVersion = Optional.empty();
if (sourceRevision.valid()) {
if (applicationPackage.isPresent())
throw new IllegalArgumentException("Application version and application package can't both be provided.");
applicationVersion = Optional.of(ApplicationVersion.from(toSourceRevision(sourceRevision),
buildNumber.asLong()));
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
boolean deployDirectly = deployOptions.field("deployDirectly").asBool();
Optional<Version> vespaVersion = optional("vespaVersion", deployOptions).map(Version::new);
if (deployDirectly && applicationPackage.isEmpty() && applicationVersion.isEmpty() && vespaVersion.isEmpty()) {
Optional<Deployment> deployment = controller.applications().getInstance(applicationId)
.map(Instance::deployments)
.flatMap(deployments -> Optional.ofNullable(deployments.get(zone)));
if(deployment.isEmpty())
throw new IllegalArgumentException("Can't redeploy application, no deployment currently exist");
ApplicationVersion version = deployment.get().applicationVersion();
if(version.isUnknown())
throw new IllegalArgumentException("Can't redeploy application, application version is unknown");
applicationVersion = Optional.of(version);
vespaVersion = Optional.of(deployment.get().version());
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
Optional.of(applicationId.instance()),
Optional.of(zone),
aPackage,
Optional.of(requireUserPrincipal(request))));
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass);
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if (tenant.isEmpty())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
controller.tenants().delete(tenant.get().name(),
accessControlRequests.credentials(tenant.get().name(),
toSlime(request.getData()).get(),
request.getJDiscRequest()));
return tenant(tenant.get(), request);
}
private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
return new MessageResponse("Deleted application " + id);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty()) {
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
}
return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
controller.applications().deactivate(id.applicationId(), id.zoneId());
return new MessageResponse("Deactivated " + id);
}
/** Returns test config for indicated job, with production deployments of the default instance. */
private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
HashSet<DeploymentId> deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toCollection(HashSet::new));
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.routing().zoneEndpointsOf(deployments),
controller.applications().contentClustersByZone(deployments)));
}
private static SourceRevision toSourceRevision(Inspector object) {
if (!object.field("repository").valid() ||
!object.field("branch").valid() ||
!object.field("commit").valid()) {
throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\".");
}
return new SourceRevision(object.field("repository").asString(),
object.field("branch").asString(),
object.field("commit").asString());
}
private Tenant getTenantOrThrow(String tenantName) {
return controller.tenants().get(tenantName)
.orElseThrow(() -> new NotExistsException(new TenantId(tenantName)));
}
private void toSlime(Cursor object, Tenant tenant, HttpRequest request) {
object.setString("tenant", tenant.name().value());
object.setString("type", tenantType(tenant));
List<com.yahoo.vespa.hosted.controller.Application> applications = controller.applications().asList(tenant.name());
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
object.setString("athensDomain", athenzTenant.domain().getName());
object.setString("property", athenzTenant.property().id());
athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString()));
athenzTenant.contact().ifPresent(c -> {
object.setString("propertyUrl", c.propertyUrl().toString());
object.setString("contactsUrl", c.url().toString());
object.setString("issueCreationUrl", c.issueTrackerUrl().toString());
Cursor contactsArray = object.setArray("contacts");
c.persons().forEach(persons -> {
Cursor personArray = contactsArray.addArray();
persons.forEach(personArray::addString);
});
});
break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
cloudTenant.creator().ifPresent(creator -> object.setString("creator", creator.getName()));
Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys");
cloudTenant.developerKeys().forEach((key, user) -> {
Cursor keyObject = pemDeveloperKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", user.getName());
});
break;
}
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
Cursor applicationArray = object.setArray("applications");
for (com.yahoo.vespa.hosted.controller.Application application : applications) {
DeploymentStatus status = controller.jobController().deploymentStatus(application);
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, status, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
}
private void toSlime(ClusterResources resources, Cursor object) {
object.setLong("nodes", resources.nodes());
object.setLong("groups", resources.groups());
toSlime(resources.nodeResources(), object.setObject("nodeResources"));
if ( ! controller.zoneRegistry().system().isPublic())
object.setDouble("cost", Math.round(resources.nodes() * resources.nodeResources().cost() * 100.0 / 3.0) / 100.0);
}
private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", valueOf(resources.diskSpeed()));
object.setString("storageType", valueOf(resources.storageType()));
}
private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) {
object.setString("tenant", tenant.name().value());
Cursor metaData = object.setObject("metaData");
metaData.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
metaData.setString("athensDomain", athenzTenant.domain().getName());
metaData.setString("property", athenzTenant.property().id());
break;
case cloud: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString());
}
/** Returns a copy of the given URI with the host and port from the given URI, the path set to the given path and the query set to given query*/
private URI withPathAndQuery(String newPath, String newQuery, URI uri) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, newQuery, null);
}
catch (URISyntaxException e) {
throw new RuntimeException("Will not happen", e);
}
}
/** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */
private URI withPath(String newPath, URI uri) {
return withPathAndQuery(newPath, null, uri);
}
private long asLong(String valueOrNull, long defaultWhenNull) {
if (valueOrNull == null) return defaultWhenNull;
try {
return Long.parseLong(valueOrNull);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'");
}
}
private void toSlime(Run run, Cursor object) {
object.setLong("id", run.id().number());
object.setString("version", run.versions().targetPlatform().toFullString());
if ( ! run.versions().targetApplication().isUnknown())
toSlime(run.versions().targetApplication(), object.setObject("revision"));
object.setString("reason", "unknown reason");
object.setLong("at", run.end().orElse(run.start()).toEpochMilli());
}
private Slime toSlime(InputStream jsonStream) {
try {
byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000);
return SlimeUtils.jsonToSlime(jsonBytes);
} catch (IOException e) {
throw new RuntimeException();
}
}
private static Principal requireUserPrincipal(HttpRequest request) {
Principal principal = request.getJDiscRequest().getUserPrincipal();
if (principal == null) throw new InternalServerErrorException("Expected a user principal");
return principal;
}
private Inspector mandatory(String key, Inspector object) {
if ( ! object.field(key).valid())
throw new IllegalArgumentException("'" + key + "' is missing");
return object.field(key);
}
private Optional<String> optional(String key, Inspector object) {
return SlimeUtils.optionalString(object.field(key));
}
private static String path(Object... elements) {
return Joiner.on("/").join(elements);
}
private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value(),
request.getUri()).toString());
}
private void toSlime(ApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value() +
"/instance/" + id.instance().value(),
request.getUri()).toString());
}
private Slime toSlime(ActivateResult result) {
Slime slime = new Slime();
Cursor object = slime.setObject();
object.setString("revisionId", result.revisionId().id());
object.setLong("applicationZipSize", result.applicationZipSizeBytes());
Cursor logArray = object.setArray("prepareMessages");
if (result.prepareResponse().log != null) {
for (Log logMessage : result.prepareResponse().log) {
Cursor logObject = logArray.addObject();
logObject.setLong("time", logMessage.time);
logObject.setString("level", logMessage.level);
logObject.setString("message", logMessage.message);
}
}
Cursor changeObject = object.setObject("configChangeActions");
Cursor restartActionsArray = changeObject.setArray("restart");
for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) {
Cursor restartActionObject = restartActionsArray.addObject();
restartActionObject.setString("clusterName", restartAction.clusterName);
restartActionObject.setString("clusterType", restartAction.clusterType);
restartActionObject.setString("serviceType", restartAction.serviceType);
serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services"));
stringsToSlime(restartAction.messages, restartActionObject.setArray("messages"));
}
Cursor refeedActionsArray = changeObject.setArray("refeed");
for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) {
Cursor refeedActionObject = refeedActionsArray.addObject();
refeedActionObject.setString("name", refeedAction.name);
refeedActionObject.setBool("allowed", refeedAction.allowed);
refeedActionObject.setString("documentType", refeedAction.documentType);
refeedActionObject.setString("clusterName", refeedAction.clusterName);
serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services"));
stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages"));
}
return slime;
}
private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) {
for (ServiceInfo serviceInfo : serviceInfoList) {
Cursor serviceInfoObject = array.addObject();
serviceInfoObject.setString("serviceName", serviceInfo.serviceName);
serviceInfoObject.setString("serviceType", serviceInfo.serviceType);
serviceInfoObject.setString("configId", serviceInfo.configId);
serviceInfoObject.setString("hostName", serviceInfo.hostName);
}
}
private void stringsToSlime(List<String> strings, Cursor array) {
for (String string : strings)
array.addString(string);
}
private String readToString(InputStream stream) {
Scanner scanner = new Scanner(stream).useDelimiter("\\A");
if ( ! scanner.hasNext()) return null;
return scanner.next();
}
private boolean systemHasVersion(Version version) {
return controller.versionStatus().versions().stream().anyMatch(v -> v.versionNumber().equals(version));
}
private static boolean recurseOverTenants(HttpRequest request) {
return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive"));
}
private static boolean recurseOverApplications(HttpRequest request) {
return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive"));
}
private static boolean recurseOverDeployments(HttpRequest request) {
return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive"));
}
private static boolean showOnlyProductionInstances(HttpRequest request) {
return "true".equals(request.getProperty("production"));
}
private static String tenantType(Tenant tenant) {
switch (tenant.type()) {
case athenz: return "ATHENS";
case cloud: return "CLOUD";
default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName());
}
}
private static ApplicationId appIdFromPath(Path path) {
return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance"));
}
private static JobType jobTypeFromPath(Path path) {
return JobType.fromJobName(path.get("jobtype"));
}
private static RunId runIdFromPath(Path path) {
long number = Long.parseLong(path.get("number"));
return new RunId(appIdFromPath(path), jobTypeFromPath(path), number);
}
private HttpResponse submit(String tenant, String application, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
Optional<String> repository = optional("repository", submitOptions);
Optional<String> branch = optional("branch", submitOptions);
Optional<String> commit = optional("commit", submitOptions);
Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent()
? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get()))
: Optional.empty();
Optional<String> sourceUrl = optional("sourceUrl", submitOptions);
Optional<String> authorEmail = optional("authorEmail", submitOptions);
sourceUrl.map(URI::create).ifPresent(url -> {
if (url.getHost() == null || url.getScheme() == null)
throw new IllegalArgumentException("Source URL must include scheme and host");
});
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true);
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
Optional.empty(),
Optional.empty(),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
sourceUrl,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
private HttpResponse removeAllProdDeployments(String tenant, String application) {
JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application,
Optional.empty(), Optional.empty(), Optional.empty(), 1,
ApplicationPackage.deploymentRemoval(), new byte[0]);
return new MessageResponse("All deployments removed");
}
private static Map<String, byte[]> parseDataParts(HttpRequest request) {
String contentHash = request.getHeader("x-Content-Hash");
if (contentHash == null)
return new MultipartParser().parse(request);
DigestInputStream digester = Signatures.sha256Digester(request.getData());
var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri());
if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash)))
throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash");
return dataParts;
}
private static RotationId findRotationId(Instance instance, Optional<String> endpointId) {
if (instance.rotations().isEmpty()) {
throw new NotExistsException("global rotation does not exist for " + instance);
}
if (endpointId.isPresent()) {
return instance.rotations().stream()
.filter(r -> r.endpointId().id().equals(endpointId.get()))
.map(AssignedRotation::rotationId)
.findFirst()
.orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() +
" does not exist for " + instance));
} else if (instance.rotations().size() > 1) {
throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given");
}
return instance.rotations().get(0).rotationId();
}
private static String rotationStateString(RotationState state) {
switch (state) {
case in: return "IN";
case out: return "OUT";
}
return "UNKNOWN";
}
private static String endpointScopeString(Endpoint.Scope scope) {
switch (scope) {
case region: return "region";
case global: return "global";
case zone: return "zone";
}
throw new IllegalArgumentException("Unknown endpoint scope " + scope);
}
private static String routingMethodString(RoutingMethod method) {
switch (method) {
case exclusive: return "exclusive";
case shared: return "shared";
case sharedLayer4: return "sharedLayer4";
}
throw new IllegalArgumentException("Unknown routing method " + method);
}
private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) {
return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName))
.filter(cls::isInstance)
.map(cls::cast)
.orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request"));
}
/** Returns whether given request is by an operator */
private static boolean isOperator(HttpRequest request) {
var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class);
return securityContext.roles().stream()
.map(Role::definition)
.anyMatch(definition -> definition == RoleDefinition.hostedOperator);
}
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestConfigSerializer testConfigSerializer;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
}
@Override
public Duration getTimeout() {
return Duration.ofMinutes(20);
}
@Override
public HttpResponse handle(HttpRequest request) {
try {
Path path = new Path(request.getUri(), OPTIONAL_PREFIX);
switch (request.getMethod()) {
case GET: return handleGET(path, request);
case PUT: return handlePUT(path, request);
case POST: return handlePOST(path, request);
case PATCH: return handlePATCH(path, request);
case DELETE: return handleDELETE(path, request);
case OPTIONS: return handleOPTIONS();
default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
}
}
catch (ForbiddenException e) {
return ErrorResponse.forbidden(Exceptions.toMessageString(e));
}
catch (NotAuthorizedException e) {
return ErrorResponse.unauthorized(Exceptions.toMessageString(e));
}
catch (NotExistsException e) {
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
}
catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
catch (ConfigServerException e) {
switch (e.getErrorCode()) {
case NOT_FOUND:
return new ErrorResponse(NOT_FOUND, e.getErrorCode().name(), Exceptions.toMessageString(e));
case ACTIVATION_CONFLICT:
return new ErrorResponse(CONFLICT, e.getErrorCode().name(), Exceptions.toMessageString(e));
case INTERNAL_SERVER_ERROR:
return new ErrorResponse(INTERNAL_SERVER_ERROR, e.getErrorCode().name(), Exceptions.toMessageString(e));
default:
return new ErrorResponse(BAD_REQUEST, e.getErrorCode().name(), Exceptions.toMessageString(e));
}
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handlePUT(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePATCH(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleDELETE(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeAllProdDeployments(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleOPTIONS() {
EmptyResponse response = new EmptyResponse();
response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS");
return response;
}
private HttpResponse recursiveRoot(HttpRequest request) {
Slime slime = new Slime();
Cursor tenantArray = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
toSlime(tenantArray.addObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse root(HttpRequest request) {
return recurseOverTenants(request)
? recursiveRoot(request)
: new ResourceResponse(request, "tenant");
}
private HttpResponse tenants(HttpRequest request) {
Slime slime = new Slime();
Cursor response = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject());
return new SlimeJsonResponse(slime);
}
private HttpResponse tenant(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenant(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenant(Tenant tenant, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
if (controller.tenants().get(tenantName).isEmpty())
return ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist");
Slime slime = new Slime();
Cursor applicationArray = slime.setArray();
for (com.yahoo.vespa.hosted.controller.Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true)) {
Cursor applicationObject = applicationArray.addObject();
applicationObject.setString("tenant", application.id().tenant().value());
applicationObject.setString("application", application.id().application().value());
applicationObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value(),
request.getUri()).toString());
Cursor instanceArray = applicationObject.setArray("instances");
for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet()
: application.instances().keySet()) {
Cursor instanceObject = instanceArray.addObject();
instanceObject.setString("instance", instance.value());
instanceObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/instance/" + instance.value(),
request.getUri()).toString());
}
}
}
return new SlimeJsonResponse(slime);
}
private HttpResponse devApplicationPackage(ApplicationId id, JobType type) {
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Only manually deployed zones have dev packages");
ZoneId zone = type.zone(controller.system());
byte[] applicationPackage = controller.applications().applicationStore().getDev(id, zone);
return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage);
}
private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse compileVersion(String tenantName, String applicationName) {
Slime slime = new Slime();
slime.setObject().setString("compileVersion",
compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString());
return new SlimeJsonResponse(slime);
}
private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
Principal user = request.getJDiscRequest().getUserPrincipal();
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withDeveloperKey(developerKey, user);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Principal user = ((CloudTenant) controller.tenants().require(TenantName.from(tenantName))).developerKeys().get(developerKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withoutDeveloperKey(developerKey);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) {
keys.forEach((key, principal) -> {
Cursor keyObject = keysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", principal.getName());
});
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withoutDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes.");
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
Inspector majorVersionField = requestObject.field("majorVersion");
if (majorVersionField.valid()) {
Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong();
application = application.withMajorVersion(majorVersion);
messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion));
}
Inspector pemDeployKeyField = requestObject.field("pemDeployKey");
if (pemDeployKeyField.valid()) {
String pemDeployKey = pemDeployKeyField.asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
application = application.withDeployKey(deployKey);
messageBuilder.add("Added deploy key " + pemDeployKey);
}
controller.applications().store(application);
});
return new MessageResponse(messageBuilder.toString());
}
private com.yahoo.vespa.hosted.controller.Application getApplication(String tenantName, String applicationName) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
return controller.applications().getApplication(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private Instance getInstance(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
return controller.applications().getInstance(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, id);
Slime slime = new Slime();
Cursor nodesArray = slime.setObject().setArray("nodes");
for (Node node : nodes) {
Cursor nodeObject = nodesArray.addObject();
nodeObject.setString("hostname", node.hostname().value());
nodeObject.setString("state", valueOf(node.state()));
node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.flavor());
toSlime(node.resources(), nodeObject);
nodeObject.setBool("fastDisk", node.resources().diskSpeed() == NodeResources.DiskSpeed.fast);
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
return new SlimeJsonResponse(slime);
}
private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id);
Slime slime = new Slime();
Cursor clustersObject = slime.setObject().setObject("clusters");
for (Cluster cluster : application.clusters().values()) {
Cursor clusterObject = clustersObject.setObject(cluster.id().value());
toSlime(cluster.min(), clusterObject.setObject("min"));
toSlime(cluster.max(), clusterObject.setObject("max"));
toSlime(cluster.current(), clusterObject.setObject("current"));
cluster.target().ifPresent(target -> toSlime(target, clusterObject.setObject("target")));
cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested")));
}
return new SlimeJsonResponse(slime);
}
private static String valueOf(Node.State state) {
switch (state) {
case failed: return "failed";
case parked: return "parked";
case dirty: return "dirty";
case ready: return "ready";
case active: return "active";
case inactive: return "inactive";
case reserved: return "reserved";
case provisioned: return "provisioned";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ServiceState state) {
switch (state) {
case expectedUp: return "expectedUp";
case allowedDown: return "allowedDown";
case unorchestrated: return "unorchestrated";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ClusterType type) {
switch (type) {
case admin: return "admin";
case content: return "content";
case container: return "container";
case combined: return "combined";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
private static String valueOf(NodeResources.DiskSpeed diskSpeed) {
switch (diskSpeed) {
case fast : return "fast";
case slow : return "slow";
case any : return "any";
default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'");
}
}
private static String valueOf(NodeResources.StorageType storageType) {
switch (storageType) {
case remote : return "remote";
case local : return "local";
case any : return "any";
default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'");
}
}
private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters);
return new HttpResponse(200) {
@Override
public void render(OutputStream outputStream) throws IOException {
logStream.transferTo(outputStream);
}
};
}
private HttpResponse metrics(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
List<ProtonMetrics> protonMetrics = controller.serviceRegistry().configServer().getProtonMetrics(deployment);
return buildResponseFromProtonMetrics(protonMetrics);
}
private JsonResponse buildResponseFromProtonMetrics(List<ProtonMetrics> protonMetrics) {
try {
var jsonObject = new JSONObject();
var jsonArray = new JSONArray();
for (ProtonMetrics metrics : protonMetrics) {
jsonArray.put(metrics.toJson());
}
jsonObject.put("metrics", jsonArray);
return new JsonResponse(200, jsonObject.toString());
} catch (JSONException e) {
log.severe("Unable to build JsonResponse with Proton data");
return new JsonResponse(500, "");
}
}
private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
boolean requireTests = ! requestObject.field("skipTests").asBool();
boolean reTrigger = requestObject.field("reTrigger").asBool();
String triggered = reTrigger
? controller.applications().deploymentTrigger()
.reTrigger(id, type).type().jobName()
: controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests)
.stream().map(job -> job.type().jobName()).collect(joining(", "));
return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered"
: "Triggered " + triggered + " for " + id);
}
private HttpResponse pause(ApplicationId id, JobType type) {
Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause);
controller.applications().deploymentTrigger().pauseJob(id, type, until);
return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause);
}
private HttpResponse resume(ApplicationId id, JobType type) {
controller.applications().deploymentTrigger().resumeJob(id, type);
return new MessageResponse(type.jobName() + " for " + id + " resumed");
}
private void toSlime(Cursor object, com.yahoo.vespa.hosted.controller.Application application, HttpRequest request) {
object.setString("tenant", application.id().tenant().value());
object.setString("application", application.id().application().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/job/",
request.getUri()).toString());
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
application.instances().values().stream().findFirst().ifPresent(instance -> {
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
});
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request);
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
if (deploymentSpec.instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec.requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
globalEndpointsToSlime(object, instance);
List<Deployment> deployments = deploymentSpec.instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor deploymentsArray = object.setArray("deployments");
for (Deployment deployment : deployments) {
Cursor deploymentObject = deploymentsArray.addObject();
if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty())
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/instance/" + instance.name().value() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
}
private void globalEndpointsToSlime(Cursor object, Instance instance) {
var globalEndpointUrls = new LinkedHashSet<String>();
controller.routing().endpointsOf(instance.id())
.requiresRotation()
.not().legacy()
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalEndpointUrls::add);
var globalRotationsArray = object.setArray("globalRotations");
globalEndpointUrls.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
}
private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) {
com.yahoo.vespa.hosted.controller.Application application = status.application();
object.setString("tenant", instance.id().tenant().value());
object.setString("application", instance.id().application().value());
object.setString("instance", instance.id().instance().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + instance.id().tenant().value() +
"/application/" + instance.id().application().value() +
"/instance/" + instance.id().instance().value() + "/job/",
request.getUri()).toString());
application.latestVersion().ifPresent(version -> {
sourceRevisionToSlime(version.source(), object.setObject("source"));
version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
version.commit().ifPresent(commit -> object.setString("commit", commit));
});
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if (application.deploymentSpec().instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec().requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
globalEndpointsToSlime(object, instance);
List<Deployment> deployments =
application.deploymentSpec().instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor instancesArray = object.setArray("instances");
for (Deployment deployment : deployments) {
Cursor deploymentObject = instancesArray.addObject();
if (deployment.zone().environment() == Environment.prod) {
if (instance.rotations().size() == 1) {
toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment),
deploymentObject);
}
if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) {
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
}
}
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("instance", instance.id().instance().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
status.jobSteps().keySet().stream()
.filter(job -> job.application().instance().equals(instance.name()))
.filter(job -> job.type().isProduction() && job.type().isDeployment())
.map(job -> job.type().zone(controller.system()))
.filter(zone -> ! instance.deployments().containsKey(zone))
.forEach(zone -> {
Cursor deploymentObject = instancesArray.addObject();
deploymentObject.setString("environment", zone.environment().value());
deploymentObject.setString("region", zone.region().value());
});
application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key)));
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().getInstance(id)
.orElseThrow(() -> new NotExistsException(id + " not found"));
DeploymentId deploymentId = new DeploymentId(instance.id(),
ZoneId.from(environment, region));
Deployment deployment = instance.deployments().get(deploymentId.zoneId());
if (deployment == null)
throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId());
Slime slime = new Slime();
toSlime(slime.setObject(), deploymentId, deployment, request);
return new SlimeJsonResponse(slime);
}
private void toSlime(Cursor object, Change change) {
change.platform().ifPresent(version -> object.setString("version", version.toString()));
change.application()
.filter(version -> !version.isUnknown())
.ifPresent(version -> toSlime(version, object.setObject("revision")));
}
private void toSlime(Endpoint endpoint, Cursor object) {
object.setString("cluster", endpoint.cluster().value());
object.setBool("tls", endpoint.tls());
object.setString("url", endpoint.url().toString());
object.setString("scope", endpointScopeString(endpoint.scope()));
object.setString("routingMethod", routingMethodString(endpoint.routingMethod()));
}
private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) {
response.setString("tenant", deploymentId.applicationId().tenant().value());
response.setString("application", deploymentId.applicationId().application().value());
response.setString("instance", deploymentId.applicationId().instance().value());
response.setString("environment", deploymentId.zoneId().environment().value());
response.setString("region", deploymentId.zoneId().region().value());
var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId()));
var endpointArray = response.setArray("endpoints");
for (var endpoint : controller.routing().endpointsOf(deploymentId)
.scope(Endpoint.Scope.zone)
.not().legacy()) {
toSlime(endpoint, endpointArray.addObject());
}
var globalEndpoints = controller.routing().endpointsOf(application, deploymentId.applicationId().instance())
.not().legacy()
.targets(deploymentId.zoneId());
for (var endpoint : globalEndpoints) {
toSlime(endpoint, endpointArray.addObject());
}
response.setString("nodes", withPathAndQuery("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/", "recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString());
response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString());
response.setString("version", deployment.version().toFullString());
response.setString("revision", deployment.applicationVersion().id());
response.setLong("deployTimeEpochMs", deployment.at().toEpochMilli());
controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId())
.ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", deployment.at().plus(deploymentTimeToLive).toEpochMilli()));
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
var instance = application.instances().get(deploymentId.applicationId().instance());
if (instance != null) {
if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod)
toSlime(instance.rotations(), instance.rotationStatus(), deployment, response);
JobType.from(controller.system(), deployment.zone())
.map(type -> new JobId(instance.id(), type))
.map(status.jobSteps()::get)
.ifPresent(stepStatus -> {
JobControllerApiHandlerHelper.applicationVersionToSlime(
response.setObject("applicationVersion"), deployment.applicationVersion());
if (!status.jobsToRun().containsKey(stepStatus.job().get()))
response.setString("status", "complete");
else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true))
response.setString("status", "pending");
else response.setString("status", "running");
});
}
Cursor activity = response.setObject("activity");
deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried",
instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten",
instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
DeploymentMetrics metrics = deployment.metrics();
Cursor metricsObject = response.setObject("metrics");
metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond());
metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond());
metricsObject.setDouble("documentCount", metrics.documentCount());
metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis());
metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli()));
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if ( ! applicationVersion.isUnknown()) {
object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong());
object.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if (revision.isEmpty()) return;
object.setString("gitRepository", revision.get().repository());
object.setString("gitBranch", revision.get().branch());
object.setString("gitCommit", revision.get().commit());
}
private void toSlime(RotationState state, Cursor object) {
Cursor bcpStatus = object.setObject("bcpStatus");
bcpStatus.setString("rotationStatus", rotationStateString(state));
}
private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) {
var array = object.setArray("endpointStatus");
for (var rotation : rotations) {
var statusObject = array.addObject();
var targets = status.of(rotation.rotationId());
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("rotationId", rotation.rotationId().asString());
statusObject.setString("clusterId", rotation.clusterId().value());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli());
}
}
private URI monitoringSystemUri(DeploymentId deploymentId) {
return controller.zoneRegistry().getMonitoringSystemUri(deploymentId);
}
/**
* Returns a non-broken, released version at least as old as the oldest platform the given application is on.
*
* If no known version is applicable, the newest version at least as old as the oldest platform is selected,
* among all versions released for this system. If no such versions exists, throws an IllegalStateException.
*/
private Version compileVersion(TenantAndApplicationId id) {
Version oldestPlatform = controller.applications().oldestInstalledPlatform(id);
VersionStatus versionStatus = controller.versionStatus();
return versionStatus.versions().stream()
.filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low))
.filter(VespaVersion::isReleased)
.map(VespaVersion::versionNumber)
.filter(version -> ! version.isAfter(oldestPlatform))
.max(Comparator.naturalOrder())
.orElseGet(() -> controller.mavenRepository().metadata().versions().stream()
.filter(version -> ! version.isAfter(oldestPlatform))
.filter(version -> ! versionStatus.versions().stream()
.map(VespaVersion::versionNumber)
.collect(Collectors.toSet()).contains(version))
.max(Comparator.naturalOrder())
.orElseThrow(() -> new IllegalStateException("No available releases of " +
controller.mavenRepository().artifactId())));
}
private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
ZoneId zone = ZoneId.from(environment, region);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
var deploymentId = new DeploymentId(instance.id(), zone);
setGlobalRotationStatus(deploymentId, inService, request);
setGlobalEndpointStatus(deploymentId, inService, request);
return new MessageResponse(String.format("Successfully set %s in %s %s service",
instance.id().toShortString(), zone, inService ? "in" : "out of"));
}
/** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */
private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
var status = inService ? GlobalRouting.Status.in : GlobalRouting.Status.out;
controller.routing().policies().setGlobalRoutingStatus(deployment, status, agent);
}
/** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */
private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var requestData = toSlime(request.getData()).get();
var reason = mandatory("reason", requestData).asString();
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
long timestamp = controller.clock().instant().getEpochSecond();
var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp);
controller.routing().setGlobalRotationStatus(deployment, endpointStatus);
}
private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Slime slime = new Slime();
Cursor array = slime.setObject().setArray("globalrotationoverride");
controller.routing().globalRotationStatus(deploymentId)
.forEach((endpoint, status) -> {
array.addString(endpoint.upstreamIdOf(deploymentId));
Cursor statusObject = array.addObject();
statusObject.setString("status", status.getStatus().name());
statusObject.setString("reason", status.getReason() == null ? "" : status.getReason());
statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent());
statusObject.setLong("timestamp", status.getEpoch());
});
return new SlimeJsonResponse(slime);
}
private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().requireInstance(applicationId);
ZoneId zone = ZoneId.from(environment, region);
RotationId rotation = findRotationId(instance, endpointId);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
Slime slime = new Slime();
Cursor response = slime.setObject();
toSlime(instance.rotationStatus().of(rotation, deployment), response);
return new SlimeJsonResponse(slime);
}
private HttpResponse metering(String tenant, String application, HttpRequest request) {
Slime slime = new Slime();
Cursor root = slime.setObject();
MeteringData meteringData = controller.serviceRegistry()
.meteringService()
.getMeteringData(TenantName.from(tenant), ApplicationName.from(application));
ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringData.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringData.getLastMonth();
Cursor lastmonth = root.setObject("lastmonth");
lastmonth.setDouble("cpu", lastMonth.getCpuCores());
lastmonth.setDouble("mem", lastMonth.getMemoryGb());
lastmonth.setDouble("disk", lastMonth.getDiskGb());
Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory();
Cursor details = root.setObject("details");
Cursor detailsCpu = details.setObject("cpu");
Cursor detailsMem = details.setObject("mem");
Cursor detailsDisk = details.setObject("disk");
history.entrySet().stream()
.forEach(entry -> {
String instanceName = entry.getKey().instance().value();
Cursor detailsCpuApp = detailsCpu.setObject(instanceName);
Cursor detailsMemApp = detailsMem.setObject(instanceName);
Cursor detailsDiskApp = detailsDisk.setObject(instanceName);
Cursor detailsCpuData = detailsCpuApp.setArray("data");
Cursor detailsMemData = detailsMemApp.setArray("data");
Cursor detailsDiskData = detailsDiskApp.setArray("data");
entry.getValue().stream()
.forEach(resourceSnapshot -> {
Cursor cpu = detailsCpuData.addObject();
cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
cpu.setDouble("value", resourceSnapshot.getCpuCores());
Cursor mem = detailsMemData.addObject();
mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
mem.setDouble("value", resourceSnapshot.getMemoryGb());
Cursor disk = detailsDiskData.addObject();
disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
disk.setDouble("value", resourceSnapshot.getDiskGb());
});
});
return new SlimeJsonResponse(slime);
}
private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! instance.change().isEmpty()) {
instance.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", instance.change().isPinned());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
boolean suspended = controller.applications().isSuspended(deploymentId);
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setBool("suspended", suspended);
return new SlimeJsonResponse(slime);
}
private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region);
ServiceApiResponse response = new ServiceApiResponse(ZoneId.from(environment, region),
new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(),
controller.zoneRegistry().getConfigServerApiUris(ZoneId.from(environment, region)),
request.getUri());
response.setResponse(applicationView);
return response;
}
private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), ZoneId.from(environment, region));
if ("container-clustercontroller".equals((serviceName)) && restPath.contains("/status/")) {
String result = controller.serviceRegistry().configServer().getClusterControllerStatus(deploymentId, restPath);
return new HtmlResponse(result);
}
Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath);
ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(),
deploymentId.applicationId(),
controller.zoneRegistry().getConfigServerApiUris(deploymentId.zoneId()),
request.getUri());
response.setResponse(result, serviceName, restPath);
return response;
}
private HttpResponse updateTenant(String tenantName, HttpRequest request) {
getTenantOrThrow(tenantName);
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().update(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createTenant(String tenantName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().create(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest());
com.yahoo.vespa.hosted.controller.Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
if (controller.applications().getApplication(applicationId).isEmpty())
createApplication(tenantName, applicationName, request);
controller.applications().createInstance(applicationId.instance(instanceName));
Slime slime = new Slime();
toSlime(applicationId.instance(instanceName), slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
/** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */
private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) {
request = controller.auditLogger().log(request);
String versionString = readToString(request.getData());
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Version version = Version.fromString(versionString);
if (version.equals(Version.emptyVersion))
version = controller.systemVersion();
if ( ! systemHasVersion(version))
throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " +
"Version is not active in this system. " +
"Active versions: " + controller.versionStatus().versions()
.stream()
.map(VespaVersion::versionNumber)
.map(Version::toString)
.collect(joining(", ")));
Change change = Change.of(version);
if (pin)
change = change.withPin();
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Trigger deployment to the last known application package for the given application. */
private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) {
controller.auditLogger().log(request);
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */
private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = application.get().require(id.instance()).change();
if (change.isEmpty()) {
response.append("No deployment in progress for ").append(id).append(" at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Schedule restart of deployment, or specific host in a deployment */
private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
RestartFilter restartFilter = new RestartFilter()
.withHostName(Optional.ofNullable(request.getProperty("hostname")).map(HostName::from))
.withClusterType(Optional.ofNullable(request.getProperty("clusterType")).map(ClusterSpec.Type::from))
.withClusterId(Optional.ofNullable(request.getProperty("clusterId")).map(ClusterSpec.Id::from));
controller.applications().restart(deploymentId, restartFilter);
return new MessageResponse("Requested restart of " + deploymentId);
}
private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) {
if ( ! type.environment().isManuallyDeployed() && ! isOperator(request))
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("applicationZip"))
throw new IllegalArgumentException("Missing required form part 'applicationZip'");
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(id.tenant(),
Optional.of(id.instance()),
Optional.of(type.zone(controller.system())),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions"))
.map(json -> SlimeUtils.jsonToSlime(json).get())
.flatMap(options -> optional("vespaVersion", options))
.map(Version::fromString);
controller.jobController().deploy(id, type, version, applicationPackage);
RunId runId = controller.jobController().last(id, type).get().id();
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("message", "Deployment started in " + runId +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<com.yahoo.vespa.hosted.controller.Application> application = controller.applications().getApplication(TenantAndApplicationId.from(applicationId));
Inspector sourceRevision = deployOptions.field("sourceRevision");
Inspector buildNumber = deployOptions.field("buildNumber");
if (sourceRevision.valid() != buildNumber.valid())
throw new IllegalArgumentException("Source revision and build number must both be provided, or not");
Optional<ApplicationVersion> applicationVersion = Optional.empty();
if (sourceRevision.valid()) {
if (applicationPackage.isPresent())
throw new IllegalArgumentException("Application version and application package can't both be provided.");
applicationVersion = Optional.of(ApplicationVersion.from(toSourceRevision(sourceRevision),
buildNumber.asLong()));
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
boolean deployDirectly = deployOptions.field("deployDirectly").asBool();
Optional<Version> vespaVersion = optional("vespaVersion", deployOptions).map(Version::new);
if (deployDirectly && applicationPackage.isEmpty() && applicationVersion.isEmpty() && vespaVersion.isEmpty()) {
Optional<Deployment> deployment = controller.applications().getInstance(applicationId)
.map(Instance::deployments)
.flatMap(deployments -> Optional.ofNullable(deployments.get(zone)));
if(deployment.isEmpty())
throw new IllegalArgumentException("Can't redeploy application, no deployment currently exist");
ApplicationVersion version = deployment.get().applicationVersion();
if(version.isUnknown())
throw new IllegalArgumentException("Can't redeploy application, application version is unknown");
applicationVersion = Optional.of(version);
vespaVersion = Optional.of(deployment.get().version());
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
Optional.of(applicationId.instance()),
Optional.of(zone),
aPackage,
Optional.of(requireUserPrincipal(request))));
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass);
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if (tenant.isEmpty())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
controller.tenants().delete(tenant.get().name(),
accessControlRequests.credentials(tenant.get().name(),
toSlime(request.getData()).get(),
request.getJDiscRequest()));
return tenant(tenant.get(), request);
}
private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
return new MessageResponse("Deleted application " + id);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty()) {
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
}
return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
controller.applications().deactivate(id.applicationId(), id.zoneId());
return new MessageResponse("Deactivated " + id);
}
/** Returns test config for indicated job, with production deployments of the default instance. */
private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
HashSet<DeploymentId> deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toCollection(HashSet::new));
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.routing().zoneEndpointsOf(deployments),
controller.applications().contentClustersByZone(deployments)));
}
private static SourceRevision toSourceRevision(Inspector object) {
if (!object.field("repository").valid() ||
!object.field("branch").valid() ||
!object.field("commit").valid()) {
throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\".");
}
return new SourceRevision(object.field("repository").asString(),
object.field("branch").asString(),
object.field("commit").asString());
}
private Tenant getTenantOrThrow(String tenantName) {
return controller.tenants().get(tenantName)
.orElseThrow(() -> new NotExistsException(new TenantId(tenantName)));
}
private void toSlime(Cursor object, Tenant tenant, HttpRequest request) {
object.setString("tenant", tenant.name().value());
object.setString("type", tenantType(tenant));
List<com.yahoo.vespa.hosted.controller.Application> applications = controller.applications().asList(tenant.name());
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
object.setString("athensDomain", athenzTenant.domain().getName());
object.setString("property", athenzTenant.property().id());
athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString()));
athenzTenant.contact().ifPresent(c -> {
object.setString("propertyUrl", c.propertyUrl().toString());
object.setString("contactsUrl", c.url().toString());
object.setString("issueCreationUrl", c.issueTrackerUrl().toString());
Cursor contactsArray = object.setArray("contacts");
c.persons().forEach(persons -> {
Cursor personArray = contactsArray.addArray();
persons.forEach(personArray::addString);
});
});
break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
cloudTenant.creator().ifPresent(creator -> object.setString("creator", creator.getName()));
Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys");
cloudTenant.developerKeys().forEach((key, user) -> {
Cursor keyObject = pemDeveloperKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", user.getName());
});
break;
}
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
Cursor applicationArray = object.setArray("applications");
for (com.yahoo.vespa.hosted.controller.Application application : applications) {
DeploymentStatus status = controller.jobController().deploymentStatus(application);
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, status, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
}
private void toSlime(ClusterResources resources, Cursor object) {
object.setLong("nodes", resources.nodes());
object.setLong("groups", resources.groups());
toSlime(resources.nodeResources(), object.setObject("nodeResources"));
if ( ! controller.zoneRegistry().system().isPublic())
object.setDouble("cost", Math.round(resources.nodes() * resources.nodeResources().cost() * 100.0 / 3.0) / 100.0);
}
private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", valueOf(resources.diskSpeed()));
object.setString("storageType", valueOf(resources.storageType()));
}
private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) {
object.setString("tenant", tenant.name().value());
Cursor metaData = object.setObject("metaData");
metaData.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
metaData.setString("athensDomain", athenzTenant.domain().getName());
metaData.setString("property", athenzTenant.property().id());
break;
case cloud: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString());
}
/** Returns a copy of the given URI with the host and port from the given URI, the path set to the given path and the query set to given query*/
private URI withPathAndQuery(String newPath, String newQuery, URI uri) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, newQuery, null);
}
catch (URISyntaxException e) {
throw new RuntimeException("Will not happen", e);
}
}
/** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */
private URI withPath(String newPath, URI uri) {
return withPathAndQuery(newPath, null, uri);
}
private long asLong(String valueOrNull, long defaultWhenNull) {
if (valueOrNull == null) return defaultWhenNull;
try {
return Long.parseLong(valueOrNull);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'");
}
}
private void toSlime(Run run, Cursor object) {
object.setLong("id", run.id().number());
object.setString("version", run.versions().targetPlatform().toFullString());
if ( ! run.versions().targetApplication().isUnknown())
toSlime(run.versions().targetApplication(), object.setObject("revision"));
object.setString("reason", "unknown reason");
object.setLong("at", run.end().orElse(run.start()).toEpochMilli());
}
private Slime toSlime(InputStream jsonStream) {
try {
byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000);
return SlimeUtils.jsonToSlime(jsonBytes);
} catch (IOException e) {
throw new RuntimeException();
}
}
private static Principal requireUserPrincipal(HttpRequest request) {
Principal principal = request.getJDiscRequest().getUserPrincipal();
if (principal == null) throw new InternalServerErrorException("Expected a user principal");
return principal;
}
private Inspector mandatory(String key, Inspector object) {
if ( ! object.field(key).valid())
throw new IllegalArgumentException("'" + key + "' is missing");
return object.field(key);
}
private Optional<String> optional(String key, Inspector object) {
return SlimeUtils.optionalString(object.field(key));
}
private static String path(Object... elements) {
return Joiner.on("/").join(elements);
}
private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value(),
request.getUri()).toString());
}
private void toSlime(ApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value() +
"/instance/" + id.instance().value(),
request.getUri()).toString());
}
private Slime toSlime(ActivateResult result) {
Slime slime = new Slime();
Cursor object = slime.setObject();
object.setString("revisionId", result.revisionId().id());
object.setLong("applicationZipSize", result.applicationZipSizeBytes());
Cursor logArray = object.setArray("prepareMessages");
if (result.prepareResponse().log != null) {
for (Log logMessage : result.prepareResponse().log) {
Cursor logObject = logArray.addObject();
logObject.setLong("time", logMessage.time);
logObject.setString("level", logMessage.level);
logObject.setString("message", logMessage.message);
}
}
Cursor changeObject = object.setObject("configChangeActions");
Cursor restartActionsArray = changeObject.setArray("restart");
for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) {
Cursor restartActionObject = restartActionsArray.addObject();
restartActionObject.setString("clusterName", restartAction.clusterName);
restartActionObject.setString("clusterType", restartAction.clusterType);
restartActionObject.setString("serviceType", restartAction.serviceType);
serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services"));
stringsToSlime(restartAction.messages, restartActionObject.setArray("messages"));
}
Cursor refeedActionsArray = changeObject.setArray("refeed");
for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) {
Cursor refeedActionObject = refeedActionsArray.addObject();
refeedActionObject.setString("name", refeedAction.name);
refeedActionObject.setBool("allowed", refeedAction.allowed);
refeedActionObject.setString("documentType", refeedAction.documentType);
refeedActionObject.setString("clusterName", refeedAction.clusterName);
serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services"));
stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages"));
}
return slime;
}
private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) {
for (ServiceInfo serviceInfo : serviceInfoList) {
Cursor serviceInfoObject = array.addObject();
serviceInfoObject.setString("serviceName", serviceInfo.serviceName);
serviceInfoObject.setString("serviceType", serviceInfo.serviceType);
serviceInfoObject.setString("configId", serviceInfo.configId);
serviceInfoObject.setString("hostName", serviceInfo.hostName);
}
}
private void stringsToSlime(List<String> strings, Cursor array) {
for (String string : strings)
array.addString(string);
}
private String readToString(InputStream stream) {
Scanner scanner = new Scanner(stream).useDelimiter("\\A");
if ( ! scanner.hasNext()) return null;
return scanner.next();
}
private boolean systemHasVersion(Version version) {
return controller.versionStatus().versions().stream().anyMatch(v -> v.versionNumber().equals(version));
}
private static boolean recurseOverTenants(HttpRequest request) {
return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive"));
}
private static boolean recurseOverApplications(HttpRequest request) {
return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive"));
}
private static boolean recurseOverDeployments(HttpRequest request) {
return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive"));
}
private static boolean showOnlyProductionInstances(HttpRequest request) {
return "true".equals(request.getProperty("production"));
}
private static String tenantType(Tenant tenant) {
switch (tenant.type()) {
case athenz: return "ATHENS";
case cloud: return "CLOUD";
default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName());
}
}
private static ApplicationId appIdFromPath(Path path) {
return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance"));
}
private static JobType jobTypeFromPath(Path path) {
return JobType.fromJobName(path.get("jobtype"));
}
private static RunId runIdFromPath(Path path) {
long number = Long.parseLong(path.get("number"));
return new RunId(appIdFromPath(path), jobTypeFromPath(path), number);
}
private HttpResponse submit(String tenant, String application, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
Optional<String> repository = optional("repository", submitOptions);
Optional<String> branch = optional("branch", submitOptions);
Optional<String> commit = optional("commit", submitOptions);
Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent()
? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get()))
: Optional.empty();
Optional<String> sourceUrl = optional("sourceUrl", submitOptions);
Optional<String> authorEmail = optional("authorEmail", submitOptions);
sourceUrl.map(URI::create).ifPresent(url -> {
if (url.getHost() == null || url.getScheme() == null)
throw new IllegalArgumentException("Source URL must include scheme and host");
});
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true);
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
Optional.empty(),
Optional.empty(),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
sourceUrl,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
private HttpResponse removeAllProdDeployments(String tenant, String application) {
JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application,
Optional.empty(), Optional.empty(), Optional.empty(), 1,
ApplicationPackage.deploymentRemoval(), new byte[0]);
return new MessageResponse("All deployments removed");
}
private static Map<String, byte[]> parseDataParts(HttpRequest request) {
String contentHash = request.getHeader("x-Content-Hash");
if (contentHash == null)
return new MultipartParser().parse(request);
DigestInputStream digester = Signatures.sha256Digester(request.getData());
var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri());
if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash)))
throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash");
return dataParts;
}
private static RotationId findRotationId(Instance instance, Optional<String> endpointId) {
if (instance.rotations().isEmpty()) {
throw new NotExistsException("global rotation does not exist for " + instance);
}
if (endpointId.isPresent()) {
return instance.rotations().stream()
.filter(r -> r.endpointId().id().equals(endpointId.get()))
.map(AssignedRotation::rotationId)
.findFirst()
.orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() +
" does not exist for " + instance));
} else if (instance.rotations().size() > 1) {
throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given");
}
return instance.rotations().get(0).rotationId();
}
private static String rotationStateString(RotationState state) {
switch (state) {
case in: return "IN";
case out: return "OUT";
}
return "UNKNOWN";
}
private static String endpointScopeString(Endpoint.Scope scope) {
switch (scope) {
case region: return "region";
case global: return "global";
case zone: return "zone";
}
throw new IllegalArgumentException("Unknown endpoint scope " + scope);
}
private static String routingMethodString(RoutingMethod method) {
switch (method) {
case exclusive: return "exclusive";
case shared: return "shared";
case sharedLayer4: return "sharedLayer4";
}
throw new IllegalArgumentException("Unknown routing method " + method);
}
private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) {
return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName))
.filter(cls::isInstance)
.map(cls::cast)
.orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request"));
}
/** Returns whether given request is by an operator */
private static boolean isOperator(HttpRequest request) {
var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class);
return securityContext.roles().stream()
.map(Role::definition)
.anyMatch(definition -> definition == RoleDefinition.hostedOperator);
}
} |
Consider pulling this out into a separate test | public void testBasics() throws Exception {
StorageCluster storage = parse("<content id=\"foofighters\"><documents/>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>\n");
assertEquals(1, storage.getChildren().size());
{
StorServerConfig.Builder builder = new StorServerConfig.Builder();
storage.getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(false, config.is_distributor());
assertEquals("foofighters", config.cluster_name());
}
{
StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder();
storage.getChildren().get("0").getConfig(builder);
StorCommunicationmanagerConfig config = new StorCommunicationmanagerConfig(builder);
assertFalse(config.mbus().dispatch_on_encode());
}
} | assertFalse(config.mbus().dispatch_on_encode()); | public void testBasics() {
StorageCluster storage = parse("<content id=\"foofighters\"><documents/>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>\n");
assertEquals(1, storage.getChildren().size());
StorServerConfig.Builder builder = new StorServerConfig.Builder();
storage.getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertFalse(config.is_distributor());
assertEquals("foofighters", config.cluster_name());
} | class StorageClusterTest {
StorageCluster parse(String xml, Flavor flavor) {
MockRoot root = new MockRoot("", new DeployState.Builder()
.applicationPackage(new MockApplicationPackage.Builder().build())
.modelHostProvisioner(new SingleNodeProvisioner(flavor)).build());
return parse(xml, root);
}
StorageCluster parse(String xml, Flavor flavor, ModelContext.Properties properties) {
MockRoot root = new MockRoot("", new DeployState.Builder()
.applicationPackage(new MockApplicationPackage.Builder().build())
.modelHostProvisioner(new SingleNodeProvisioner(flavor))
.properties(properties).build());
return parse(xml, root);
}
StorageCluster parse(String xml) {
MockRoot root = new MockRoot();
return parse(xml, root);
}
StorageCluster parse(String xml, MockRoot root) {
root.getDeployState().getDocumentModel().getDocumentManager().add(
new NewDocumentType(new NewDocumentType.Name("music"))
);
root.getDeployState().getDocumentModel().getDocumentManager().add(
new NewDocumentType(new NewDocumentType.Name("movies"))
);
ContentCluster cluster = ContentClusterUtils.createCluster(xml, root);
root.freezeModelTopology();
return cluster.getStorageNodes();
}
@Test
@Test
public void testMerges() {
StorServerConfig.Builder builder = new StorServerConfig.Builder();
parse("" +
"<content id=\"foofighters\">\n" +
" <documents/>" +
" <tuning>" +
" <merges max-per-node=\"1K\" max-queue-size=\"10K\"/>\n" +
" </tuning>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>"
).getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(1024, config.max_merges_per_node());
assertEquals(1024*10, config.max_merge_queue_size());
}
@Test
public void testVisitors() throws Exception {
StorVisitorConfig.Builder builder = new StorVisitorConfig.Builder();
parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" <visitors thread-count=\"7\" max-queue-size=\"1000\">\n" +
" <max-concurrent fixed=\"42\" variable=\"100\"/>\n" +
" </visitors>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>"
).getConfig(builder);
StorVisitorConfig config = new StorVisitorConfig(builder);
assertEquals(42, config.maxconcurrentvisitors_fixed());
assertEquals(100, config.maxconcurrentvisitors_variable());
assertEquals(7, config.visitorthreads());
assertEquals(1000, config.maxvisitorqueuesize());
}
@Test
public void testPersistenceThreads() {
StorageCluster stc = parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" <persistence-threads count=\"7\"/>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>",
new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build())
);
{
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
stc.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(7, config.num_threads());
assertFalse(config.enable_multibit_split_optimalization());
assertEquals(1, config.num_response_threads());
}
{
assertEquals(1, stc.getChildren().size());
StorageNode sn = stc.getChildren().values().iterator().next();
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
sn.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(7, config.num_threads());
}
}
@Test
public void testResponseThreads() {
StorageCluster stc = parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" <persistence-threads count=\"7\"/>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>",
new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build())
);
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
stc.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(1, config.num_response_threads());
assertEquals(7, config.num_threads());
}
@Test
public void testPersistenceThreadsOld() {
StorageCluster stc = parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" <persistence-threads>\n" +
" <thread lowest-priority=\"VERY_LOW\" count=\"2\"/>\n" +
" <thread lowest-priority=\"VERY_HIGH\" count=\"1\"/>\n" +
" <thread count=\"1\"/>\n" +
" </persistence-threads>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>",
new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build())
);
{
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
stc.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(4, config.num_threads());
assertFalse(config.enable_multibit_split_optimalization());
}
{
assertEquals(1, stc.getChildren().size());
StorageNode sn = stc.getChildren().values().iterator().next();
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
sn.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(4, config.num_threads());
}
}
@Test
public void testNoPersistenceThreads() {
StorageCluster stc = parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>",
new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build())
);
{
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
stc.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(8, config.num_threads());
}
{
assertEquals(1, stc.getChildren().size());
StorageNode sn = stc.getChildren().values().iterator().next();
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
sn.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(9, config.num_threads());
}
}
@Test
public void integrity_checker_explicitly_disabled_when_not_running_with_vds_provider() {
StorIntegritycheckerConfig.Builder builder = new StorIntegritycheckerConfig.Builder();
parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>"
).getConfig(builder);
StorIntegritycheckerConfig config = new StorIntegritycheckerConfig(builder);
assertEquals("-------", config.weeklycycle());
}
@Test
public void testCapacity() {
String xml =
"<cluster id=\"storage\">\n" +
" <documents/>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\" capacity=\"1.5\"/>\n" +
" <node distribution-key=\"2\" hostalias=\"mockhost\" capacity=\"2.0\"/>\n" +
" </group>\n" +
"</cluster>";
ContentCluster cluster = ContentClusterUtils.createCluster(xml, new MockRoot());
for (int i = 0; i < 3; ++i) {
StorageNode node = cluster.getStorageNodes().getChildren().get("" + i);
StorServerConfig.Builder builder = new StorServerConfig.Builder();
cluster.getStorageNodes().getConfig(builder);
node.getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(1.0 + (double)i * 0.5, config.node_capacity(), 0.001);
}
}
@Test
public void testRootFolder() {
String xml =
"<cluster id=\"storage\">\n" +
" <documents/>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
"</cluster>";
ContentCluster cluster = ContentClusterUtils.createCluster(xml, new MockRoot());
StorageNode node = cluster.getStorageNodes().getChildren().get("0");
{
StorServerConfig.Builder builder = new StorServerConfig.Builder();
cluster.getStorageNodes().getConfig(builder);
node.getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(getDefaults().underVespaHome("var/db/vespa/search/storage/storage/0"), config.root_folder());
}
{
StorServerConfig.Builder builder = new StorServerConfig.Builder();
cluster.getDistributorNodes().getConfig(builder);
cluster.getDistributorNodes().getChildren().get("0").getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(getDefaults().underVespaHome("var/db/vespa/search/storage/distributor/0"), config.root_folder());
}
}
@Test
public void testGenericPersistenceTuning() {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>" +
"<engine>\n" +
" <fail-partition-on-error>true</fail-partition-on-error>\n" +
" <revert-time>34m</revert-time>\n" +
" <recovery-time>5d</recovery-time>\n" +
"</engine>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
"</cluster>";
ContentCluster cluster = ContentClusterUtils.createCluster(xml, new MockRoot());
PersistenceConfig.Builder builder = new PersistenceConfig.Builder();
cluster.getStorageNodes().getConfig(builder);
PersistenceConfig config = new PersistenceConfig(builder);
assertTrue(config.fail_partition_on_error());
assertEquals(34 * 60, config.revert_time_period());
assertEquals(5 * 24 * 60 * 60, config.keep_remove_time_period());
}
@Test
public void requireThatUserDoesNotSpecifyBothGroupAndNodes() {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>\n" +
"<engine>\n" +
" <fail-partition-on-error>true</fail-partition-on-error>\n" +
" <revert-time>34m</revert-time>\n" +
" <recovery-time>5d</recovery-time>\n" +
"</engine>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" <nodes>\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </nodes>\n" +
"</cluster>";
try {
final MockRoot root = new MockRoot();
root.getDeployState().getDocumentModel().getDocumentManager().add(
new NewDocumentType(new NewDocumentType.Name("music"))
);
ContentClusterUtils.createCluster(xml, root);
fail("Did not fail when having both group and nodes");
} catch (RuntimeException e) {
e.printStackTrace();
assertEquals("Both group and nodes exists, only one of these tags is legal", e.getMessage());
}
}
@Test
public void requireThatGroupNamesMustBeUniqueAmongstSiblings() {
String xml =
"<cluster id=\"storage\">\n" +
" <redundancy>2</redundancy>" +
" <documents/>\n" +
" <group>\n" +
" <distribution partitions=\"*\"/>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
"</cluster>";
try {
ContentClusterUtils.createCluster(xml, new MockRoot());
fail("Did not get exception with duplicate group names");
} catch (RuntimeException e) {
assertEquals("Cluster 'storage' has multiple groups with name 'bar' in the same subgroup. " +
"Group sibling names must be unique.", e.getMessage());
}
}
@Test
public void requireThatGroupNamesCanBeDuplicatedAcrossLevels() {
String xml =
"<cluster id=\"storage\">\n" +
" <redundancy>2</redundancy>" +
"<documents/>\n" +
" <group>\n" +
" <distribution partitions=\"*\"/>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <group distribution-key=\"0\" name=\"foo\">\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
" <group distribution-key=\"0\" name=\"foo\">\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
" </group>\n" +
"</cluster>";
ContentClusterUtils.createCluster(xml, new MockRoot());
}
@Test
public void requireThatNestedGroupsRequireDistribution() {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>\n" +
" <group>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" <group distribution-key=\"0\" name=\"baz\">\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
"</cluster>";
try {
ContentClusterUtils.createCluster(xml, new MockRoot());
fail("Did not get exception with missing distribution element");
} catch (RuntimeException e) {
assertEquals("'distribution' attribute is required with multiple subgroups", e.getMessage());
}
}
} | class StorageClusterTest {
StorageCluster parse(String xml, Flavor flavor) {
MockRoot root = new MockRoot("", new DeployState.Builder()
.applicationPackage(new MockApplicationPackage.Builder().build())
.modelHostProvisioner(new SingleNodeProvisioner(flavor)).build());
return parse(xml, root);
}
StorageCluster parse(String xml) {
MockRoot root = new MockRoot();
return parse(xml, root);
}
StorageCluster parse(String xml, MockRoot root) {
root.getDeployState().getDocumentModel().getDocumentManager().add(
new NewDocumentType(new NewDocumentType.Name("music"))
);
root.getDeployState().getDocumentModel().getDocumentManager().add(
new NewDocumentType(new NewDocumentType.Name("movies"))
);
ContentCluster cluster = ContentClusterUtils.createCluster(xml, root);
root.freezeModelTopology();
return cluster.getStorageNodes();
}
@Test
@Test
public void testCommunicationManagerDefaults() {
StorageCluster storage = parse("<content id=\"foofighters\"><documents/>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>\n");
StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder();
storage.getChildren().get("0").getConfig(builder);
StorCommunicationmanagerConfig config = new StorCommunicationmanagerConfig(builder);
assertFalse(config.mbus().dispatch_on_encode());
assertFalse(config.mbus().dispatch_on_decode());
assertEquals(4, config.mbus().num_threads());
assertEquals(StorCommunicationmanagerConfig.Mbus.Optimize_for.LATENCY, config.mbus().optimize_for());
}
@Test
public void testMerges() {
StorServerConfig.Builder builder = new StorServerConfig.Builder();
parse("" +
"<content id=\"foofighters\">\n" +
" <documents/>" +
" <tuning>" +
" <merges max-per-node=\"1K\" max-queue-size=\"10K\"/>\n" +
" </tuning>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</content>"
).getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(1024, config.max_merges_per_node());
assertEquals(1024*10, config.max_merge_queue_size());
}
@Test
public void testVisitors() {
StorVisitorConfig.Builder builder = new StorVisitorConfig.Builder();
parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" <visitors thread-count=\"7\" max-queue-size=\"1000\">\n" +
" <max-concurrent fixed=\"42\" variable=\"100\"/>\n" +
" </visitors>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>"
).getConfig(builder);
StorVisitorConfig config = new StorVisitorConfig(builder);
assertEquals(42, config.maxconcurrentvisitors_fixed());
assertEquals(100, config.maxconcurrentvisitors_variable());
assertEquals(7, config.visitorthreads());
assertEquals(1000, config.maxvisitorqueuesize());
}
@Test
public void testPersistenceThreads() {
StorageCluster stc = parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" <persistence-threads count=\"7\"/>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>",
new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build())
);
{
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
stc.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(7, config.num_threads());
assertFalse(config.enable_multibit_split_optimalization());
assertEquals(1, config.num_response_threads());
}
{
assertEquals(1, stc.getChildren().size());
StorageNode sn = stc.getChildren().values().iterator().next();
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
sn.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(7, config.num_threads());
}
}
@Test
public void testResponseThreads() {
StorageCluster stc = parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" <persistence-threads count=\"7\"/>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>",
new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build())
);
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
stc.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(1, config.num_response_threads());
assertEquals(7, config.num_threads());
}
@Test
public void testPersistenceThreadsOld() {
StorageCluster stc = parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" <persistence-threads>\n" +
" <thread lowest-priority=\"VERY_LOW\" count=\"2\"/>\n" +
" <thread lowest-priority=\"VERY_HIGH\" count=\"1\"/>\n" +
" <thread count=\"1\"/>\n" +
" </persistence-threads>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>",
new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build())
);
{
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
stc.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(4, config.num_threads());
assertFalse(config.enable_multibit_split_optimalization());
}
{
assertEquals(1, stc.getChildren().size());
StorageNode sn = stc.getChildren().values().iterator().next();
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
sn.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(4, config.num_threads());
}
}
@Test
public void testNoPersistenceThreads() {
StorageCluster stc = parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <tuning>\n" +
" </tuning>\n" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>",
new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build())
);
{
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
stc.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(8, config.num_threads());
}
{
assertEquals(1, stc.getChildren().size());
StorageNode sn = stc.getChildren().values().iterator().next();
StorFilestorConfig.Builder builder = new StorFilestorConfig.Builder();
sn.getConfig(builder);
StorFilestorConfig config = new StorFilestorConfig(builder);
assertEquals(9, config.num_threads());
}
}
@Test
public void integrity_checker_explicitly_disabled_when_not_running_with_vds_provider() {
StorIntegritycheckerConfig.Builder builder = new StorIntegritycheckerConfig.Builder();
parse(
"<cluster id=\"bees\">\n" +
" <documents/>" +
" <group>" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>" +
" </group>" +
"</cluster>"
).getConfig(builder);
StorIntegritycheckerConfig config = new StorIntegritycheckerConfig(builder);
assertEquals("-------", config.weeklycycle());
}
@Test
public void testCapacity() {
String xml =
"<cluster id=\"storage\">\n" +
" <documents/>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\" capacity=\"1.5\"/>\n" +
" <node distribution-key=\"2\" hostalias=\"mockhost\" capacity=\"2.0\"/>\n" +
" </group>\n" +
"</cluster>";
ContentCluster cluster = ContentClusterUtils.createCluster(xml, new MockRoot());
for (int i = 0; i < 3; ++i) {
StorageNode node = cluster.getStorageNodes().getChildren().get("" + i);
StorServerConfig.Builder builder = new StorServerConfig.Builder();
cluster.getStorageNodes().getConfig(builder);
node.getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(1.0 + (double)i * 0.5, config.node_capacity(), 0.001);
}
}
@Test
public void testRootFolder() {
String xml =
"<cluster id=\"storage\">\n" +
" <documents/>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
"</cluster>";
ContentCluster cluster = ContentClusterUtils.createCluster(xml, new MockRoot());
StorageNode node = cluster.getStorageNodes().getChildren().get("0");
{
StorServerConfig.Builder builder = new StorServerConfig.Builder();
cluster.getStorageNodes().getConfig(builder);
node.getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(getDefaults().underVespaHome("var/db/vespa/search/storage/storage/0"), config.root_folder());
}
{
StorServerConfig.Builder builder = new StorServerConfig.Builder();
cluster.getDistributorNodes().getConfig(builder);
cluster.getDistributorNodes().getChildren().get("0").getConfig(builder);
StorServerConfig config = new StorServerConfig(builder);
assertEquals(getDefaults().underVespaHome("var/db/vespa/search/storage/distributor/0"), config.root_folder());
}
}
@Test
public void testGenericPersistenceTuning() {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>" +
"<engine>\n" +
" <fail-partition-on-error>true</fail-partition-on-error>\n" +
" <revert-time>34m</revert-time>\n" +
" <recovery-time>5d</recovery-time>\n" +
"</engine>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
"</cluster>";
ContentCluster cluster = ContentClusterUtils.createCluster(xml, new MockRoot());
PersistenceConfig.Builder builder = new PersistenceConfig.Builder();
cluster.getStorageNodes().getConfig(builder);
PersistenceConfig config = new PersistenceConfig(builder);
assertTrue(config.fail_partition_on_error());
assertEquals(34 * 60, config.revert_time_period());
assertEquals(5 * 24 * 60 * 60, config.keep_remove_time_period());
}
@Test
public void requireThatUserDoesNotSpecifyBothGroupAndNodes() {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>\n" +
"<engine>\n" +
" <fail-partition-on-error>true</fail-partition-on-error>\n" +
" <revert-time>34m</revert-time>\n" +
" <recovery-time>5d</recovery-time>\n" +
"</engine>" +
" <group>\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" <nodes>\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </nodes>\n" +
"</cluster>";
try {
final MockRoot root = new MockRoot();
root.getDeployState().getDocumentModel().getDocumentManager().add(
new NewDocumentType(new NewDocumentType.Name("music"))
);
ContentClusterUtils.createCluster(xml, root);
fail("Did not fail when having both group and nodes");
} catch (RuntimeException e) {
e.printStackTrace();
assertEquals("Both group and nodes exists, only one of these tags is legal", e.getMessage());
}
}
@Test
public void requireThatGroupNamesMustBeUniqueAmongstSiblings() {
String xml =
"<cluster id=\"storage\">\n" +
" <redundancy>2</redundancy>" +
" <documents/>\n" +
" <group>\n" +
" <distribution partitions=\"*\"/>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
"</cluster>";
try {
ContentClusterUtils.createCluster(xml, new MockRoot());
fail("Did not get exception with duplicate group names");
} catch (RuntimeException e) {
assertEquals("Cluster 'storage' has multiple groups with name 'bar' in the same subgroup. " +
"Group sibling names must be unique.", e.getMessage());
}
}
@Test
public void requireThatGroupNamesCanBeDuplicatedAcrossLevels() {
String xml =
"<cluster id=\"storage\">\n" +
" <redundancy>2</redundancy>" +
"<documents/>\n" +
" <group>\n" +
" <distribution partitions=\"*\"/>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <group distribution-key=\"0\" name=\"foo\">\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
" <group distribution-key=\"0\" name=\"foo\">\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
" </group>\n" +
"</cluster>";
ContentClusterUtils.createCluster(xml, new MockRoot());
}
@Test
public void requireThatNestedGroupsRequireDistribution() {
String xml =
"<cluster id=\"storage\">\n" +
"<documents/>\n" +
" <group>\n" +
" <group distribution-key=\"0\" name=\"bar\">\n" +
" <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" <group distribution-key=\"0\" name=\"baz\">\n" +
" <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" +
" </group>\n" +
" </group>\n" +
"</cluster>";
try {
ContentClusterUtils.createCluster(xml, new MockRoot());
fail("Did not get exception with missing distribution element");
} catch (RuntimeException e) {
assertEquals("'distribution' attribute is required with multiple subgroups", e.getMessage());
}
}
} |
Why was taking the lock removed here? | public void deleteLocalSession(LocalSession session) {
long sessionId = session.getSessionId();
log.log(Level.FINE, "Deleting local session " + sessionId);
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
localSessionCache.removeSession(sessionId);
NestedTransaction transaction = new NestedTransaction();
deleteLocalSession(session, transaction);
transaction.commit();
} | log.log(Level.FINE, "Deleting local session " + sessionId); | public void deleteLocalSession(LocalSession session) {
long sessionId = session.getSessionId();
try (Lock lock = lock(sessionId)) {
log.log(Level.FINE, "Deleting local session " + sessionId);
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
localSessionCache.removeSession(sessionId);
NestedTransaction transaction = new NestedTransaction();
deleteLocalSession(session, transaction);
transaction.commit();
}
} | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSession = 0;
private final SessionCache<LocalSession> localSessionCache = new SessionCache<>();
private final SessionCache<RemoteSession> remoteSessionCache = new SessionCache<>();
private final Map<Long, SessionStateWatcher> sessionStateWatchers = new HashMap<>();
private final Duration sessionLifetime;
private final Clock clock;
private final Curator curator;
private final Executor zkWatcherExecutor;
private final TenantFileSystemDirs tenantFileSystemDirs;
private final BooleanFlag distributeApplicationPackage;
private final MetricUpdater metrics;
private final Curator.DirectoryCache directoryCache;
private final TenantApplications applicationRepo;
private final SessionPreparer sessionPreparer;
private final Path sessionsPath;
private final TenantName tenantName;
private final GlobalComponentRegistry componentRegistry;
private final Path locksPath;
public SessionRepository(TenantName tenantName,
GlobalComponentRegistry componentRegistry,
TenantApplications applicationRepo,
FlagSource flagSource,
SessionPreparer sessionPreparer) {
this.tenantName = tenantName;
this.componentRegistry = componentRegistry;
this.sessionsPath = TenantRepository.getSessionsPath(tenantName);
this.clock = componentRegistry.getClock();
this.curator = componentRegistry.getCurator();
this.sessionLifetime = Duration.ofSeconds(componentRegistry.getConfigserverConfig().sessionLifetime());
this.zkWatcherExecutor = command -> componentRegistry.getZkWatcherExecutor().execute(tenantName, command);
this.tenantFileSystemDirs = new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName);
this.applicationRepo = applicationRepo;
this.sessionPreparer = sessionPreparer;
this.distributeApplicationPackage = Flags.CONFIGSERVER_DISTRIBUTE_APPLICATION_PACKAGE.bindTo(flagSource);
this.metrics = componentRegistry.getMetrics().getOrCreateMetricUpdater(Metrics.createDimensions(tenantName));
this.locksPath = TenantRepository.getLocksPath(tenantName);
loadLocalSessions();
initializeRemoteSessions();
this.directoryCache = curator.createDirectoryCache(sessionsPath.getAbsolute(), false, false, componentRegistry.getZkCacheExecutor());
this.directoryCache.addListener(this::childEvent);
this.directoryCache.start();
}
public synchronized void addLocalSession(LocalSession session) {
localSessionCache.addSession(session);
long sessionId = session.getSessionId();
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
RemoteSession remoteSession = createRemoteSession(sessionId);
addSesssionStateWatcher(sessionId, fileCache, remoteSession, Optional.of(session));
}
public LocalSession getLocalSession(long sessionId) {
return localSessionCache.getSession(sessionId);
}
public List<LocalSession> getLocalSessions() {
return localSessionCache.getSessions();
}
private void loadLocalSessions() {
File[] sessions = tenantFileSystemDirs.sessionsPath().listFiles(sessionApplicationsFilter);
if (sessions == null) return;
for (File session : sessions) {
try {
addLocalSession(createSessionFromId(Long.parseLong(session.getName())));
} catch (IllegalArgumentException e) {
log.log(Level.WARNING, "Could not load local session '" +
session.getAbsolutePath() + "':" + e.getMessage() + ", skipping it.");
}
}
}
public ConfigChangeActions prepareLocalSession(LocalSession session,
DeployLogger logger,
PrepareParams params,
Optional<ApplicationSet> currentActiveApplicationSet,
Path tenantPath,
Instant now) {
applicationRepo.createApplication(params.getApplicationId());
logger.log(Level.FINE, "Created application " + params.getApplicationId());
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
Curator.CompletionWaiter waiter = sessionZooKeeperClient.createPrepareWaiter();
ConfigChangeActions actions = sessionPreparer.prepare(applicationRepo.getHostValidator(), logger, params,
currentActiveApplicationSet, tenantPath, now,
getSessionAppDir(sessionId),
session.getApplicationPackage(), sessionZooKeeperClient);
session.setPrepared();
waiter.awaitCompletion(params.getTimeoutBudget().timeLeft());
return actions;
}
public void deleteExpiredSessions(Map<ApplicationId, Long> activeSessions) {
log.log(Level.FINE, "Purging old sessions");
try {
for (LocalSession candidate : localSessionCache.getSessions()) {
Instant createTime = candidate.getCreateTime();
log.log(Level.FINE, "Candidate session for deletion: " + candidate.getSessionId() + ", created: " + createTime);
if (hasExpired(candidate) && !isActiveSession(candidate)) {
deleteLocalSession(candidate);
} else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) {
ApplicationId applicationId = candidate.getApplicationId();
Long activeSession = activeSessions.get(applicationId);
if (activeSession == null || activeSession != candidate.getSessionId()) {
deleteLocalSession(candidate);
log.log(Level.INFO, "Deleted inactive session " + candidate.getSessionId() + " created " +
createTime + " for '" + applicationId + "'");
}
}
}
} catch (Throwable e) {
log.log(Level.WARNING, "Error when purging old sessions ", e);
}
log.log(Level.FINE, "Done purging old sessions");
}
private boolean hasExpired(LocalSession candidate) {
return (candidate.getCreateTime().plus(sessionLifetime).isBefore(clock.instant()));
}
private boolean isActiveSession(LocalSession candidate) {
return candidate.getStatus() == Session.Status.ACTIVATE;
}
/** Add transactions to delete this session to the given nested transaction */
public void deleteLocalSession(LocalSession session, NestedTransaction transaction) {
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
transaction.add(sessionZooKeeperClient.deleteTransaction(), FileTransaction.class);
transaction.add(FileTransaction.from(FileOperations.delete(getSessionAppDir(sessionId).getAbsolutePath())));
}
public void close() {
deleteAllSessions();
tenantFileSystemDirs.delete();
try {
if (directoryCache != null) {
directoryCache.close();
}
} catch (Exception e) {
log.log(Level.WARNING, "Exception when closing path cache", e);
} finally {
checkForRemovedSessions(new ArrayList<>());
}
}
private void deleteAllSessions() {
List<LocalSession> sessions = new ArrayList<>(localSessionCache.getSessions());
for (LocalSession session : sessions) {
deleteLocalSession(session);
}
}
public RemoteSession getRemoteSession(long sessionId) {
return remoteSessionCache.getSession(sessionId);
}
public List<Long> getRemoteSessions() {
return getSessionList(curator.getChildren(sessionsPath));
}
public void addRemoteSession(RemoteSession session) {
remoteSessionCache.addSession(session);
metrics.incAddedSessions();
}
public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) {
int deleted = 0;
for (long sessionId : getRemoteSessions()) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
if (session.getStatus() == Session.Status.ACTIVATE) continue;
if (sessionHasExpired(session.getCreateTime(), expiryTime, clock)) {
log.log(Level.INFO, "Remote session " + sessionId + " for " + tenantName + " has expired, deleting it");
session.delete();
deleted++;
}
}
return deleted;
}
private boolean sessionHasExpired(Instant created, Duration expiryTime, Clock clock) {
return (created.plus(expiryTime).isBefore(clock.instant()));
}
private List<Long> getSessionListFromDirectoryCache(List<ChildData> children) {
return getSessionList(children.stream()
.map(child -> Path.fromString(child.getPath()).getName())
.collect(Collectors.toList()));
}
private List<Long> getSessionList(List<String> children) {
return children.stream().map(Long::parseLong).collect(Collectors.toList());
}
private void initializeRemoteSessions() throws NumberFormatException {
getRemoteSessions().forEach(this::sessionAdded);
}
private synchronized void sessionsChanged() throws NumberFormatException {
List<Long> sessions = getSessionListFromDirectoryCache(directoryCache.getCurrentData());
checkForRemovedSessions(sessions);
checkForAddedSessions(sessions);
}
private void checkForRemovedSessions(List<Long> sessions) {
for (RemoteSession session : remoteSessionCache.getSessions())
if ( ! sessions.contains(session.getSessionId()))
sessionRemoved(session.getSessionId());
}
private void checkForAddedSessions(List<Long> sessions) {
for (Long sessionId : sessions)
if (remoteSessionCache.getSession(sessionId) == null)
sessionAdded(sessionId);
}
/**
* A session for which we don't have a watcher, i.e. hitherto unknown to us.
*
* @param sessionId session id for the new session
*/
public void sessionAdded(long sessionId) {
try (var lock = lock(sessionId)) {
log.log(Level.FINE, () -> "Adding remote session to SessionRepository: " + sessionId);
RemoteSession remoteSession = createRemoteSession(sessionId);
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
fileCache.addListener(this::nodeChanged);
loadSessionIfActive(remoteSession);
addRemoteSession(remoteSession);
Optional<LocalSession> localSession = Optional.empty();
if (distributeApplicationPackage())
localSession = createLocalSessionUsingDistributedApplicationPackage(sessionId);
addSesssionStateWatcher(sessionId, fileCache, remoteSession, localSession);
}
}
boolean distributeApplicationPackage() {
return distributeApplicationPackage.value();
}
private void sessionRemoved(long sessionId) {
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
remoteSessionCache.removeSession(sessionId);
metrics.incRemovedSessions();
}
private void loadSessionIfActive(RemoteSession session) {
for (ApplicationId applicationId : applicationRepo.activeApplications()) {
if (applicationRepo.requireActiveSessionOf(applicationId) == session.getSessionId()) {
log.log(Level.FINE, () -> "Found active application for session " + session.getSessionId() + " , loading it");
applicationRepo.reloadConfig(session.ensureApplicationLoaded());
log.log(Level.INFO, session.logPre() + "Application activated successfully: " + applicationId + " (generation " + session.getSessionId() + ")");
return;
}
}
}
private void nodeChanged() {
zkWatcherExecutor.execute(() -> {
Multiset<Session.Status> sessionMetrics = HashMultiset.create();
for (RemoteSession session : remoteSessionCache.getSessions()) {
sessionMetrics.add(session.getStatus());
}
metrics.setNewSessions(sessionMetrics.count(Session.Status.NEW));
metrics.setPreparedSessions(sessionMetrics.count(Session.Status.PREPARE));
metrics.setActivatedSessions(sessionMetrics.count(Session.Status.ACTIVATE));
metrics.setDeactivatedSessions(sessionMetrics.count(Session.Status.DEACTIVATE));
});
}
@SuppressWarnings("unused")
private void childEvent(CuratorFramework ignored, PathChildrenCacheEvent event) {
zkWatcherExecutor.execute(() -> {
log.log(Level.FINE, () -> "Got child event: " + event);
switch (event.getType()) {
case CHILD_ADDED:
sessionsChanged();
synchronizeOnNew(getSessionListFromDirectoryCache(Collections.singletonList(event.getData())));
break;
case CHILD_REMOVED:
case CONNECTION_RECONNECTED:
sessionsChanged();
break;
}
});
}
private void synchronizeOnNew(List<Long> sessionList) {
for (long sessionId : sessionList) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
log.log(Level.FINE, () -> session.logPre() + "Confirming upload for session " + sessionId);
session.confirmUpload();
}
}
/**
* Creates a new deployment session from an application package.
*
* @param applicationDirectory a File pointing to an application.
* @param applicationId application id for this new session.
* @param timeoutBudget Timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSession(File applicationDirectory, ApplicationId applicationId,
TimeoutBudget timeoutBudget, Optional<Long> activeSessionId) {
return create(applicationDirectory, applicationId, activeSessionId, false, timeoutBudget);
}
public RemoteSession createRemoteSession(long sessionId) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new RemoteSession(tenantName, sessionId, componentRegistry, sessionZKClient);
}
private void ensureSessionPathDoesNotExist(long sessionId) {
Path sessionPath = getSessionPath(sessionId);
if (componentRegistry.getConfigCurator().exists(sessionPath.getAbsolute())) {
throw new IllegalArgumentException("Path " + sessionPath.getAbsolute() + " already exists in ZooKeeper");
}
}
private ApplicationPackage createApplication(File userDir,
File configApplicationDir,
ApplicationId applicationId,
long sessionId,
Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) {
long deployTimestamp = System.currentTimeMillis();
String user = System.getenv("USER");
if (user == null) {
user = "unknown";
}
DeployData deployData = new DeployData(user, userDir.getAbsolutePath(), applicationId, deployTimestamp,
internalRedeploy, sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSession));
return FilesApplicationPackage.fromFileWithDeployData(configApplicationDir, deployData);
}
private LocalSession createSessionFromApplication(ApplicationPackage applicationPackage,
long sessionId,
TimeoutBudget timeoutBudget,
Clock clock) {
log.log(Level.FINE, TenantRepository.logPre(tenantName) + "Creating session " + sessionId + " in ZooKeeper");
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
sessionZKClient.createNewSession(clock.instant());
Curator.CompletionWaiter waiter = sessionZKClient.getUploadWaiter();
LocalSession session = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
waiter.awaitCompletion(timeoutBudget.timeLeft());
return session;
}
/**
* Creates a new deployment session from an already existing session.
*
* @param existingSession the session to use as base
* @param logger a deploy logger where the deploy log will be written.
* @param internalRedeploy whether this session is for a system internal redeploy — not an application package change
* @param timeoutBudget timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSessionFromExisting(Session existingSession,
DeployLogger logger,
boolean internalRedeploy,
TimeoutBudget timeoutBudget) {
File existingApp = getSessionAppDir(existingSession.getSessionId());
ApplicationId existingApplicationId = existingSession.getApplicationId();
Optional<Long> activeSessionId = getActiveSessionId(existingApplicationId);
logger.log(Level.FINE, "Create new session for application id '" + existingApplicationId + "' from existing active session " + activeSessionId);
LocalSession session = create(existingApp, existingApplicationId, activeSessionId, internalRedeploy, timeoutBudget);
session.setApplicationId(existingApplicationId);
if (distributeApplicationPackage() && existingSession.getApplicationPackageReference() != null) {
session.setApplicationPackageReference(existingSession.getApplicationPackageReference());
}
session.setVespaVersion(existingSession.getVespaVersion());
session.setDockerImageRepository(existingSession.getDockerImageRepository());
session.setAthenzDomain(existingSession.getAthenzDomain());
return session;
}
private LocalSession create(File applicationFile, ApplicationId applicationId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy, TimeoutBudget timeoutBudget) {
long sessionId = getNextSessionId();
try {
ensureSessionPathDoesNotExist(sessionId);
ApplicationPackage app = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, internalRedeploy);
return createSessionFromApplication(app, sessionId, timeoutBudget, clock);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
/**
* This method is used when creating a session based on a remote session and the distributed application package
* It does not wait for session being created on other servers
*/
private LocalSession createLocalSession(File applicationFile, ApplicationId applicationId, long sessionId) {
try {
Optional<Long> currentlyActiveSessionId = getActiveSessionId(applicationId);
ApplicationPackage applicationPackage = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, false);
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZooKeeperClient, applicationRepo);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
private ApplicationPackage createApplicationPackage(File applicationFile, ApplicationId applicationId,
long sessionId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) throws IOException {
File userApplicationDir = getSessionAppDir(sessionId);
copyApp(applicationFile, userApplicationDir);
ApplicationPackage applicationPackage = createApplication(applicationFile,
userApplicationDir,
applicationId,
sessionId,
currentlyActiveSessionId,
internalRedeploy);
applicationPackage.writeMetaData();
return applicationPackage;
}
private void copyApp(File sourceDir, File destinationDir) throws IOException {
if (destinationDir.exists())
throw new RuntimeException("Destination dir " + destinationDir + " already exists");
if (! sourceDir.isDirectory())
throw new IllegalArgumentException(sourceDir.getAbsolutePath() + " is not a directory");
java.nio.file.Path tempDestinationDir = Files.createTempDirectory(destinationDir.getParentFile().toPath(), "app-package");
log.log(Level.FINE, "Copying dir " + sourceDir.getAbsolutePath() + " to " + tempDestinationDir.toFile().getAbsolutePath());
IOUtils.copyDirectory(sourceDir, tempDestinationDir.toFile());
log.log(Level.FINE, "Moving " + tempDestinationDir + " to " + destinationDir.getAbsolutePath());
Files.move(tempDestinationDir, destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE);
}
/**
* Returns a new session instance for the given session id.
*/
LocalSession createSessionFromId(long sessionId) {
File sessionDir = getAndValidateExistingSessionAppDir(sessionId);
ApplicationPackage applicationPackage = FilesApplicationPackage.fromFile(sessionDir);
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
}
/**
* Returns a new local session for the given session id if it does not already exist.
* Will also add the session to the local session cache if necessary
*/
public Optional<LocalSession> createLocalSessionUsingDistributedApplicationPackage(long sessionId) {
if (applicationRepo.hasLocalSession(sessionId)) {
log.log(Level.FINE, "Local session for session id " + sessionId + " already exists");
return Optional.of(createSessionFromId(sessionId));
}
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
FileReference fileReference = sessionZKClient.readApplicationPackageReference();
log.log(Level.FINE, "File reference for session id " + sessionId + ": " + fileReference);
if (fileReference != null) {
File rootDir = new File(Defaults.getDefaults().underVespaHome(componentRegistry.getConfigserverConfig().fileReferencesDir()));
File sessionDir;
FileDirectory fileDirectory = new FileDirectory(rootDir);
try {
sessionDir = fileDirectory.getFile(fileReference);
} catch (IllegalArgumentException e) {
log.log(Level.INFO, "File reference for session id " + sessionId + ": " + fileReference + " not found in " + fileDirectory);
return Optional.empty();
}
ApplicationId applicationId = sessionZKClient.readApplicationId();
log.log(Level.INFO, "Creating local session for session id " + sessionId);
LocalSession localSession = createLocalSession(sessionDir, applicationId, sessionId);
addLocalSession(localSession);
return Optional.of(localSession);
}
return Optional.empty();
}
private Optional<Long> getActiveSessionId(ApplicationId applicationId) {
List<ApplicationId> applicationIds = applicationRepo.activeApplications();
return applicationIds.contains(applicationId)
? Optional.of(applicationRepo.requireActiveSessionOf(applicationId))
: Optional.empty();
}
private long getNextSessionId() {
return new SessionCounter(componentRegistry.getConfigCurator(), tenantName).nextSessionId();
}
public Path getSessionPath(long sessionId) {
return sessionsPath.append(String.valueOf(sessionId));
}
Path getSessionStatePath(long sessionId) {
return getSessionPath(sessionId).append(ConfigCurator.SESSIONSTATE_ZK_SUBPATH);
}
private SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) {
String serverId = componentRegistry.getConfigserverConfig().serverId();
Optional<NodeFlavors> nodeFlavors = componentRegistry.getZone().nodeFlavors();
Path sessionPath = getSessionPath(sessionId);
return new SessionZooKeeperClient(curator, componentRegistry.getConfigCurator(), sessionPath, serverId, nodeFlavors);
}
private File getAndValidateExistingSessionAppDir(long sessionId) {
File appDir = getSessionAppDir(sessionId);
if (!appDir.exists() || !appDir.isDirectory()) {
throw new IllegalArgumentException("Unable to find correct application directory for session " + sessionId);
}
return appDir;
}
private File getSessionAppDir(long sessionId) {
return new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName).getUserApplicationDir(sessionId);
}
private void addSesssionStateWatcher(long sessionId, Curator.FileCache fileCache, RemoteSession remoteSession, Optional<LocalSession> localSession) {
if (sessionStateWatchers.containsKey(sessionId)) {
localSession.ifPresent(session -> sessionStateWatchers.get(sessionId).addLocalSession(session));
} else {
sessionStateWatchers.put(sessionId, new SessionStateWatcher(fileCache, applicationRepo, remoteSession,
localSession, metrics, zkWatcherExecutor, this));
}
}
@Override
public String toString() {
return getLocalSessions().toString();
}
/** Returns the lock for session operations for the given session id. */
public Lock lock(long sessionId) {
return curator.lock(lockPath(sessionId), Duration.ofMinutes(1));
}
private Path lockPath(long sessionId) {
return locksPath.append(String.valueOf(sessionId));
}
private static class FileTransaction extends AbstractTransaction {
public static FileTransaction from(FileOperation operation) {
FileTransaction transaction = new FileTransaction();
transaction.add(operation);
return transaction;
}
@Override
public void prepare() { }
@Override
public void commit() {
for (Operation operation : operations())
((FileOperation)operation).commit();
}
}
/** Factory for file operations */
private static class FileOperations {
/** Creates an operation which recursively deletes the given path */
public static DeleteOperation delete(String pathToDelete) {
return new DeleteOperation(pathToDelete);
}
}
private interface FileOperation extends Transaction.Operation {
void commit();
}
/**
* Recursively deletes this path and everything below.
* Succeeds with no action if the path does not exist.
*/
private static class DeleteOperation implements FileOperation {
private final String pathToDelete;
DeleteOperation(String pathToDelete) {
this.pathToDelete = pathToDelete;
}
@Override
public void commit() {
IOUtils.recursiveDeleteDir(new File(pathToDelete));
}
}
} | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSession = 0;
private final SessionCache<LocalSession> localSessionCache = new SessionCache<>();
private final SessionCache<RemoteSession> remoteSessionCache = new SessionCache<>();
private final Map<Long, SessionStateWatcher> sessionStateWatchers = new HashMap<>();
private final Duration sessionLifetime;
private final Clock clock;
private final Curator curator;
private final Executor zkWatcherExecutor;
private final TenantFileSystemDirs tenantFileSystemDirs;
private final BooleanFlag distributeApplicationPackage;
private final MetricUpdater metrics;
private final Curator.DirectoryCache directoryCache;
private final TenantApplications applicationRepo;
private final SessionPreparer sessionPreparer;
private final Path sessionsPath;
private final TenantName tenantName;
private final GlobalComponentRegistry componentRegistry;
private final Path locksPath;
public SessionRepository(TenantName tenantName,
GlobalComponentRegistry componentRegistry,
TenantApplications applicationRepo,
FlagSource flagSource,
SessionPreparer sessionPreparer) {
this.tenantName = tenantName;
this.componentRegistry = componentRegistry;
this.sessionsPath = TenantRepository.getSessionsPath(tenantName);
this.clock = componentRegistry.getClock();
this.curator = componentRegistry.getCurator();
this.sessionLifetime = Duration.ofSeconds(componentRegistry.getConfigserverConfig().sessionLifetime());
this.zkWatcherExecutor = command -> componentRegistry.getZkWatcherExecutor().execute(tenantName, command);
this.tenantFileSystemDirs = new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName);
this.applicationRepo = applicationRepo;
this.sessionPreparer = sessionPreparer;
this.distributeApplicationPackage = Flags.CONFIGSERVER_DISTRIBUTE_APPLICATION_PACKAGE.bindTo(flagSource);
this.metrics = componentRegistry.getMetrics().getOrCreateMetricUpdater(Metrics.createDimensions(tenantName));
this.locksPath = TenantRepository.getLocksPath(tenantName);
loadLocalSessions();
initializeRemoteSessions();
this.directoryCache = curator.createDirectoryCache(sessionsPath.getAbsolute(), false, false, componentRegistry.getZkCacheExecutor());
this.directoryCache.addListener(this::childEvent);
this.directoryCache.start();
}
public synchronized void addLocalSession(LocalSession session) {
localSessionCache.addSession(session);
long sessionId = session.getSessionId();
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
RemoteSession remoteSession = createRemoteSession(sessionId);
addSesssionStateWatcher(sessionId, fileCache, remoteSession, Optional.of(session));
}
public LocalSession getLocalSession(long sessionId) {
return localSessionCache.getSession(sessionId);
}
public List<LocalSession> getLocalSessions() {
return localSessionCache.getSessions();
}
private void loadLocalSessions() {
File[] sessions = tenantFileSystemDirs.sessionsPath().listFiles(sessionApplicationsFilter);
if (sessions == null) return;
for (File session : sessions) {
try {
addLocalSession(createSessionFromId(Long.parseLong(session.getName())));
} catch (IllegalArgumentException e) {
log.log(Level.WARNING, "Could not load local session '" +
session.getAbsolutePath() + "':" + e.getMessage() + ", skipping it.");
}
}
}
public ConfigChangeActions prepareLocalSession(LocalSession session,
DeployLogger logger,
PrepareParams params,
Optional<ApplicationSet> currentActiveApplicationSet,
Path tenantPath,
Instant now) {
applicationRepo.createApplication(params.getApplicationId());
logger.log(Level.FINE, "Created application " + params.getApplicationId());
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
Curator.CompletionWaiter waiter = sessionZooKeeperClient.createPrepareWaiter();
ConfigChangeActions actions = sessionPreparer.prepare(applicationRepo.getHostValidator(), logger, params,
currentActiveApplicationSet, tenantPath, now,
getSessionAppDir(sessionId),
session.getApplicationPackage(), sessionZooKeeperClient);
session.setPrepared();
waiter.awaitCompletion(params.getTimeoutBudget().timeLeft());
return actions;
}
public void deleteExpiredSessions(Map<ApplicationId, Long> activeSessions) {
log.log(Level.FINE, "Purging old sessions");
try {
for (LocalSession candidate : localSessionCache.getSessions()) {
Instant createTime = candidate.getCreateTime();
log.log(Level.FINE, "Candidate session for deletion: " + candidate.getSessionId() + ", created: " + createTime);
if (hasExpired(candidate) && !isActiveSession(candidate)) {
deleteLocalSession(candidate);
} else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) {
ApplicationId applicationId = candidate.getApplicationId();
Long activeSession = activeSessions.get(applicationId);
if (activeSession == null || activeSession != candidate.getSessionId()) {
deleteLocalSession(candidate);
log.log(Level.INFO, "Deleted inactive session " + candidate.getSessionId() + " created " +
createTime + " for '" + applicationId + "'");
}
}
}
} catch (Throwable e) {
log.log(Level.WARNING, "Error when purging old sessions ", e);
}
log.log(Level.FINE, "Done purging old sessions");
}
private boolean hasExpired(LocalSession candidate) {
return (candidate.getCreateTime().plus(sessionLifetime).isBefore(clock.instant()));
}
private boolean isActiveSession(LocalSession candidate) {
return candidate.getStatus() == Session.Status.ACTIVATE;
}
/** Add transactions to delete this session to the given nested transaction */
public void deleteLocalSession(LocalSession session, NestedTransaction transaction) {
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
transaction.add(sessionZooKeeperClient.deleteTransaction(), FileTransaction.class);
transaction.add(FileTransaction.from(FileOperations.delete(getSessionAppDir(sessionId).getAbsolutePath())));
}
public void close() {
deleteAllSessions();
tenantFileSystemDirs.delete();
try {
if (directoryCache != null) {
directoryCache.close();
}
} catch (Exception e) {
log.log(Level.WARNING, "Exception when closing path cache", e);
} finally {
checkForRemovedSessions(new ArrayList<>());
}
}
private void deleteAllSessions() {
List<LocalSession> sessions = new ArrayList<>(localSessionCache.getSessions());
for (LocalSession session : sessions) {
deleteLocalSession(session);
}
}
public RemoteSession getRemoteSession(long sessionId) {
return remoteSessionCache.getSession(sessionId);
}
public List<Long> getRemoteSessions() {
return getSessionList(curator.getChildren(sessionsPath));
}
public void addRemoteSession(RemoteSession session) {
remoteSessionCache.addSession(session);
metrics.incAddedSessions();
}
public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) {
int deleted = 0;
for (long sessionId : getRemoteSessions()) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
if (session.getStatus() == Session.Status.ACTIVATE) continue;
if (sessionHasExpired(session.getCreateTime(), expiryTime, clock)) {
log.log(Level.INFO, "Remote session " + sessionId + " for " + tenantName + " has expired, deleting it");
session.delete();
deleted++;
}
}
return deleted;
}
private boolean sessionHasExpired(Instant created, Duration expiryTime, Clock clock) {
return (created.plus(expiryTime).isBefore(clock.instant()));
}
private List<Long> getSessionListFromDirectoryCache(List<ChildData> children) {
return getSessionList(children.stream()
.map(child -> Path.fromString(child.getPath()).getName())
.collect(Collectors.toList()));
}
private List<Long> getSessionList(List<String> children) {
return children.stream().map(Long::parseLong).collect(Collectors.toList());
}
private void initializeRemoteSessions() throws NumberFormatException {
getRemoteSessions().forEach(this::sessionAdded);
}
private synchronized void sessionsChanged() throws NumberFormatException {
List<Long> sessions = getSessionListFromDirectoryCache(directoryCache.getCurrentData());
checkForRemovedSessions(sessions);
checkForAddedSessions(sessions);
}
private void checkForRemovedSessions(List<Long> sessions) {
for (RemoteSession session : remoteSessionCache.getSessions())
if ( ! sessions.contains(session.getSessionId()))
sessionRemoved(session.getSessionId());
}
private void checkForAddedSessions(List<Long> sessions) {
for (Long sessionId : sessions)
if (remoteSessionCache.getSession(sessionId) == null)
sessionAdded(sessionId);
}
/**
* A session for which we don't have a watcher, i.e. hitherto unknown to us.
*
* @param sessionId session id for the new session
*/
public void sessionAdded(long sessionId) {
try (var lock = lock(sessionId)) {
log.log(Level.FINE, () -> "Adding remote session to SessionRepository: " + sessionId);
RemoteSession remoteSession = createRemoteSession(sessionId);
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
fileCache.addListener(this::nodeChanged);
loadSessionIfActive(remoteSession);
addRemoteSession(remoteSession);
Optional<LocalSession> localSession = Optional.empty();
if (distributeApplicationPackage())
localSession = createLocalSessionUsingDistributedApplicationPackage(sessionId);
addSesssionStateWatcher(sessionId, fileCache, remoteSession, localSession);
}
}
boolean distributeApplicationPackage() {
return distributeApplicationPackage.value();
}
private void sessionRemoved(long sessionId) {
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
remoteSessionCache.removeSession(sessionId);
metrics.incRemovedSessions();
}
private void loadSessionIfActive(RemoteSession session) {
for (ApplicationId applicationId : applicationRepo.activeApplications()) {
if (applicationRepo.requireActiveSessionOf(applicationId) == session.getSessionId()) {
log.log(Level.FINE, () -> "Found active application for session " + session.getSessionId() + " , loading it");
applicationRepo.reloadConfig(session.ensureApplicationLoaded());
log.log(Level.INFO, session.logPre() + "Application activated successfully: " + applicationId + " (generation " + session.getSessionId() + ")");
return;
}
}
}
private void nodeChanged() {
zkWatcherExecutor.execute(() -> {
Multiset<Session.Status> sessionMetrics = HashMultiset.create();
for (RemoteSession session : remoteSessionCache.getSessions()) {
sessionMetrics.add(session.getStatus());
}
metrics.setNewSessions(sessionMetrics.count(Session.Status.NEW));
metrics.setPreparedSessions(sessionMetrics.count(Session.Status.PREPARE));
metrics.setActivatedSessions(sessionMetrics.count(Session.Status.ACTIVATE));
metrics.setDeactivatedSessions(sessionMetrics.count(Session.Status.DEACTIVATE));
});
}
@SuppressWarnings("unused")
private void childEvent(CuratorFramework ignored, PathChildrenCacheEvent event) {
zkWatcherExecutor.execute(() -> {
log.log(Level.FINE, () -> "Got child event: " + event);
switch (event.getType()) {
case CHILD_ADDED:
sessionsChanged();
synchronizeOnNew(getSessionListFromDirectoryCache(Collections.singletonList(event.getData())));
break;
case CHILD_REMOVED:
case CONNECTION_RECONNECTED:
sessionsChanged();
break;
}
});
}
private void synchronizeOnNew(List<Long> sessionList) {
for (long sessionId : sessionList) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
log.log(Level.FINE, () -> session.logPre() + "Confirming upload for session " + sessionId);
session.confirmUpload();
}
}
/**
* Creates a new deployment session from an application package.
*
* @param applicationDirectory a File pointing to an application.
* @param applicationId application id for this new session.
* @param timeoutBudget Timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSession(File applicationDirectory, ApplicationId applicationId,
TimeoutBudget timeoutBudget, Optional<Long> activeSessionId) {
return create(applicationDirectory, applicationId, activeSessionId, false, timeoutBudget);
}
public RemoteSession createRemoteSession(long sessionId) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new RemoteSession(tenantName, sessionId, componentRegistry, sessionZKClient);
}
private void ensureSessionPathDoesNotExist(long sessionId) {
Path sessionPath = getSessionPath(sessionId);
if (componentRegistry.getConfigCurator().exists(sessionPath.getAbsolute())) {
throw new IllegalArgumentException("Path " + sessionPath.getAbsolute() + " already exists in ZooKeeper");
}
}
private ApplicationPackage createApplication(File userDir,
File configApplicationDir,
ApplicationId applicationId,
long sessionId,
Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) {
long deployTimestamp = System.currentTimeMillis();
String user = System.getenv("USER");
if (user == null) {
user = "unknown";
}
DeployData deployData = new DeployData(user, userDir.getAbsolutePath(), applicationId, deployTimestamp,
internalRedeploy, sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSession));
return FilesApplicationPackage.fromFileWithDeployData(configApplicationDir, deployData);
}
private LocalSession createSessionFromApplication(ApplicationPackage applicationPackage,
long sessionId,
TimeoutBudget timeoutBudget,
Clock clock) {
log.log(Level.FINE, TenantRepository.logPre(tenantName) + "Creating session " + sessionId + " in ZooKeeper");
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
sessionZKClient.createNewSession(clock.instant());
Curator.CompletionWaiter waiter = sessionZKClient.getUploadWaiter();
LocalSession session = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
waiter.awaitCompletion(timeoutBudget.timeLeft());
return session;
}
/**
* Creates a new deployment session from an already existing session.
*
* @param existingSession the session to use as base
* @param logger a deploy logger where the deploy log will be written.
* @param internalRedeploy whether this session is for a system internal redeploy — not an application package change
* @param timeoutBudget timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSessionFromExisting(Session existingSession,
DeployLogger logger,
boolean internalRedeploy,
TimeoutBudget timeoutBudget) {
File existingApp = getSessionAppDir(existingSession.getSessionId());
ApplicationId existingApplicationId = existingSession.getApplicationId();
Optional<Long> activeSessionId = getActiveSessionId(existingApplicationId);
logger.log(Level.FINE, "Create new session for application id '" + existingApplicationId + "' from existing active session " + activeSessionId);
LocalSession session = create(existingApp, existingApplicationId, activeSessionId, internalRedeploy, timeoutBudget);
session.setApplicationId(existingApplicationId);
if (distributeApplicationPackage() && existingSession.getApplicationPackageReference() != null) {
session.setApplicationPackageReference(existingSession.getApplicationPackageReference());
}
session.setVespaVersion(existingSession.getVespaVersion());
session.setDockerImageRepository(existingSession.getDockerImageRepository());
session.setAthenzDomain(existingSession.getAthenzDomain());
return session;
}
private LocalSession create(File applicationFile, ApplicationId applicationId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy, TimeoutBudget timeoutBudget) {
long sessionId = getNextSessionId();
try {
ensureSessionPathDoesNotExist(sessionId);
ApplicationPackage app = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, internalRedeploy);
return createSessionFromApplication(app, sessionId, timeoutBudget, clock);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
/**
* This method is used when creating a session based on a remote session and the distributed application package
* It does not wait for session being created on other servers
*/
private LocalSession createLocalSession(File applicationFile, ApplicationId applicationId, long sessionId) {
try {
Optional<Long> currentlyActiveSessionId = getActiveSessionId(applicationId);
ApplicationPackage applicationPackage = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, false);
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZooKeeperClient, applicationRepo);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
private ApplicationPackage createApplicationPackage(File applicationFile, ApplicationId applicationId,
long sessionId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) throws IOException {
File userApplicationDir = getSessionAppDir(sessionId);
copyApp(applicationFile, userApplicationDir);
ApplicationPackage applicationPackage = createApplication(applicationFile,
userApplicationDir,
applicationId,
sessionId,
currentlyActiveSessionId,
internalRedeploy);
applicationPackage.writeMetaData();
return applicationPackage;
}
private void copyApp(File sourceDir, File destinationDir) throws IOException {
if (destinationDir.exists())
throw new RuntimeException("Destination dir " + destinationDir + " already exists");
if (! sourceDir.isDirectory())
throw new IllegalArgumentException(sourceDir.getAbsolutePath() + " is not a directory");
java.nio.file.Path tempDestinationDir = Files.createTempDirectory(destinationDir.getParentFile().toPath(), "app-package");
log.log(Level.FINE, "Copying dir " + sourceDir.getAbsolutePath() + " to " + tempDestinationDir.toFile().getAbsolutePath());
IOUtils.copyDirectory(sourceDir, tempDestinationDir.toFile());
log.log(Level.FINE, "Moving " + tempDestinationDir + " to " + destinationDir.getAbsolutePath());
Files.move(tempDestinationDir, destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE);
}
/**
* Returns a new session instance for the given session id.
*/
LocalSession createSessionFromId(long sessionId) {
File sessionDir = getAndValidateExistingSessionAppDir(sessionId);
ApplicationPackage applicationPackage = FilesApplicationPackage.fromFile(sessionDir);
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
}
/**
* Returns a new local session for the given session id if it does not already exist.
* Will also add the session to the local session cache if necessary
*/
public Optional<LocalSession> createLocalSessionUsingDistributedApplicationPackage(long sessionId) {
if (applicationRepo.hasLocalSession(sessionId)) {
log.log(Level.FINE, "Local session for session id " + sessionId + " already exists");
return Optional.of(createSessionFromId(sessionId));
}
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
FileReference fileReference = sessionZKClient.readApplicationPackageReference();
log.log(Level.FINE, "File reference for session id " + sessionId + ": " + fileReference);
if (fileReference != null) {
File rootDir = new File(Defaults.getDefaults().underVespaHome(componentRegistry.getConfigserverConfig().fileReferencesDir()));
File sessionDir;
FileDirectory fileDirectory = new FileDirectory(rootDir);
try {
sessionDir = fileDirectory.getFile(fileReference);
} catch (IllegalArgumentException e) {
log.log(Level.INFO, "File reference for session id " + sessionId + ": " + fileReference + " not found in " + fileDirectory);
return Optional.empty();
}
ApplicationId applicationId = sessionZKClient.readApplicationId();
log.log(Level.INFO, "Creating local session for session id " + sessionId);
LocalSession localSession = createLocalSession(sessionDir, applicationId, sessionId);
addLocalSession(localSession);
return Optional.of(localSession);
}
return Optional.empty();
}
private Optional<Long> getActiveSessionId(ApplicationId applicationId) {
List<ApplicationId> applicationIds = applicationRepo.activeApplications();
return applicationIds.contains(applicationId)
? Optional.of(applicationRepo.requireActiveSessionOf(applicationId))
: Optional.empty();
}
private long getNextSessionId() {
return new SessionCounter(componentRegistry.getConfigCurator(), tenantName).nextSessionId();
}
public Path getSessionPath(long sessionId) {
return sessionsPath.append(String.valueOf(sessionId));
}
Path getSessionStatePath(long sessionId) {
return getSessionPath(sessionId).append(ConfigCurator.SESSIONSTATE_ZK_SUBPATH);
}
private SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) {
String serverId = componentRegistry.getConfigserverConfig().serverId();
Optional<NodeFlavors> nodeFlavors = componentRegistry.getZone().nodeFlavors();
Path sessionPath = getSessionPath(sessionId);
return new SessionZooKeeperClient(curator, componentRegistry.getConfigCurator(), sessionPath, serverId, nodeFlavors);
}
private File getAndValidateExistingSessionAppDir(long sessionId) {
File appDir = getSessionAppDir(sessionId);
if (!appDir.exists() || !appDir.isDirectory()) {
throw new IllegalArgumentException("Unable to find correct application directory for session " + sessionId);
}
return appDir;
}
private File getSessionAppDir(long sessionId) {
return new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName).getUserApplicationDir(sessionId);
}
private void addSesssionStateWatcher(long sessionId, Curator.FileCache fileCache, RemoteSession remoteSession, Optional<LocalSession> localSession) {
if (sessionStateWatchers.containsKey(sessionId)) {
localSession.ifPresent(session -> sessionStateWatchers.get(sessionId).addLocalSession(session));
} else {
sessionStateWatchers.put(sessionId, new SessionStateWatcher(fileCache, applicationRepo, remoteSession,
localSession, metrics, zkWatcherExecutor, this));
}
}
@Override
public String toString() {
return getLocalSessions().toString();
}
/** Returns the lock for session operations for the given session id. */
public Lock lock(long sessionId) {
return curator.lock(lockPath(sessionId), Duration.ofMinutes(1));
}
private Path lockPath(long sessionId) {
return locksPath.append(String.valueOf(sessionId));
}
private static class FileTransaction extends AbstractTransaction {
public static FileTransaction from(FileOperation operation) {
FileTransaction transaction = new FileTransaction();
transaction.add(operation);
return transaction;
}
@Override
public void prepare() { }
@Override
public void commit() {
for (Operation operation : operations())
((FileOperation)operation).commit();
}
}
/** Factory for file operations */
private static class FileOperations {
/** Creates an operation which recursively deletes the given path */
public static DeleteOperation delete(String pathToDelete) {
return new DeleteOperation(pathToDelete);
}
}
private interface FileOperation extends Transaction.Operation {
void commit();
}
/**
* Recursively deletes this path and everything below.
* Succeeds with no action if the path does not exist.
*/
private static class DeleteOperation implements FileOperation {
private final String pathToDelete;
DeleteOperation(String pathToDelete) {
this.pathToDelete = pathToDelete;
}
@Override
public void commit() {
IOUtils.recursiveDeleteDir(new File(pathToDelete));
}
}
} |
I mistakenly thought the lock was not reentrant, so I think it is OK to add it back again | public void deleteLocalSession(LocalSession session) {
long sessionId = session.getSessionId();
log.log(Level.FINE, "Deleting local session " + sessionId);
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
localSessionCache.removeSession(sessionId);
NestedTransaction transaction = new NestedTransaction();
deleteLocalSession(session, transaction);
transaction.commit();
} | log.log(Level.FINE, "Deleting local session " + sessionId); | public void deleteLocalSession(LocalSession session) {
long sessionId = session.getSessionId();
try (Lock lock = lock(sessionId)) {
log.log(Level.FINE, "Deleting local session " + sessionId);
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
localSessionCache.removeSession(sessionId);
NestedTransaction transaction = new NestedTransaction();
deleteLocalSession(session, transaction);
transaction.commit();
}
} | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSession = 0;
private final SessionCache<LocalSession> localSessionCache = new SessionCache<>();
private final SessionCache<RemoteSession> remoteSessionCache = new SessionCache<>();
private final Map<Long, SessionStateWatcher> sessionStateWatchers = new HashMap<>();
private final Duration sessionLifetime;
private final Clock clock;
private final Curator curator;
private final Executor zkWatcherExecutor;
private final TenantFileSystemDirs tenantFileSystemDirs;
private final BooleanFlag distributeApplicationPackage;
private final MetricUpdater metrics;
private final Curator.DirectoryCache directoryCache;
private final TenantApplications applicationRepo;
private final SessionPreparer sessionPreparer;
private final Path sessionsPath;
private final TenantName tenantName;
private final GlobalComponentRegistry componentRegistry;
private final Path locksPath;
public SessionRepository(TenantName tenantName,
GlobalComponentRegistry componentRegistry,
TenantApplications applicationRepo,
FlagSource flagSource,
SessionPreparer sessionPreparer) {
this.tenantName = tenantName;
this.componentRegistry = componentRegistry;
this.sessionsPath = TenantRepository.getSessionsPath(tenantName);
this.clock = componentRegistry.getClock();
this.curator = componentRegistry.getCurator();
this.sessionLifetime = Duration.ofSeconds(componentRegistry.getConfigserverConfig().sessionLifetime());
this.zkWatcherExecutor = command -> componentRegistry.getZkWatcherExecutor().execute(tenantName, command);
this.tenantFileSystemDirs = new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName);
this.applicationRepo = applicationRepo;
this.sessionPreparer = sessionPreparer;
this.distributeApplicationPackage = Flags.CONFIGSERVER_DISTRIBUTE_APPLICATION_PACKAGE.bindTo(flagSource);
this.metrics = componentRegistry.getMetrics().getOrCreateMetricUpdater(Metrics.createDimensions(tenantName));
this.locksPath = TenantRepository.getLocksPath(tenantName);
loadLocalSessions();
initializeRemoteSessions();
this.directoryCache = curator.createDirectoryCache(sessionsPath.getAbsolute(), false, false, componentRegistry.getZkCacheExecutor());
this.directoryCache.addListener(this::childEvent);
this.directoryCache.start();
}
public synchronized void addLocalSession(LocalSession session) {
localSessionCache.addSession(session);
long sessionId = session.getSessionId();
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
RemoteSession remoteSession = createRemoteSession(sessionId);
addSesssionStateWatcher(sessionId, fileCache, remoteSession, Optional.of(session));
}
public LocalSession getLocalSession(long sessionId) {
return localSessionCache.getSession(sessionId);
}
public List<LocalSession> getLocalSessions() {
return localSessionCache.getSessions();
}
private void loadLocalSessions() {
File[] sessions = tenantFileSystemDirs.sessionsPath().listFiles(sessionApplicationsFilter);
if (sessions == null) return;
for (File session : sessions) {
try {
addLocalSession(createSessionFromId(Long.parseLong(session.getName())));
} catch (IllegalArgumentException e) {
log.log(Level.WARNING, "Could not load local session '" +
session.getAbsolutePath() + "':" + e.getMessage() + ", skipping it.");
}
}
}
public ConfigChangeActions prepareLocalSession(LocalSession session,
DeployLogger logger,
PrepareParams params,
Optional<ApplicationSet> currentActiveApplicationSet,
Path tenantPath,
Instant now) {
applicationRepo.createApplication(params.getApplicationId());
logger.log(Level.FINE, "Created application " + params.getApplicationId());
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
Curator.CompletionWaiter waiter = sessionZooKeeperClient.createPrepareWaiter();
ConfigChangeActions actions = sessionPreparer.prepare(applicationRepo.getHostValidator(), logger, params,
currentActiveApplicationSet, tenantPath, now,
getSessionAppDir(sessionId),
session.getApplicationPackage(), sessionZooKeeperClient);
session.setPrepared();
waiter.awaitCompletion(params.getTimeoutBudget().timeLeft());
return actions;
}
public void deleteExpiredSessions(Map<ApplicationId, Long> activeSessions) {
log.log(Level.FINE, "Purging old sessions");
try {
for (LocalSession candidate : localSessionCache.getSessions()) {
Instant createTime = candidate.getCreateTime();
log.log(Level.FINE, "Candidate session for deletion: " + candidate.getSessionId() + ", created: " + createTime);
if (hasExpired(candidate) && !isActiveSession(candidate)) {
deleteLocalSession(candidate);
} else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) {
ApplicationId applicationId = candidate.getApplicationId();
Long activeSession = activeSessions.get(applicationId);
if (activeSession == null || activeSession != candidate.getSessionId()) {
deleteLocalSession(candidate);
log.log(Level.INFO, "Deleted inactive session " + candidate.getSessionId() + " created " +
createTime + " for '" + applicationId + "'");
}
}
}
} catch (Throwable e) {
log.log(Level.WARNING, "Error when purging old sessions ", e);
}
log.log(Level.FINE, "Done purging old sessions");
}
private boolean hasExpired(LocalSession candidate) {
return (candidate.getCreateTime().plus(sessionLifetime).isBefore(clock.instant()));
}
private boolean isActiveSession(LocalSession candidate) {
return candidate.getStatus() == Session.Status.ACTIVATE;
}
/** Add transactions to delete this session to the given nested transaction */
public void deleteLocalSession(LocalSession session, NestedTransaction transaction) {
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
transaction.add(sessionZooKeeperClient.deleteTransaction(), FileTransaction.class);
transaction.add(FileTransaction.from(FileOperations.delete(getSessionAppDir(sessionId).getAbsolutePath())));
}
public void close() {
deleteAllSessions();
tenantFileSystemDirs.delete();
try {
if (directoryCache != null) {
directoryCache.close();
}
} catch (Exception e) {
log.log(Level.WARNING, "Exception when closing path cache", e);
} finally {
checkForRemovedSessions(new ArrayList<>());
}
}
private void deleteAllSessions() {
List<LocalSession> sessions = new ArrayList<>(localSessionCache.getSessions());
for (LocalSession session : sessions) {
deleteLocalSession(session);
}
}
public RemoteSession getRemoteSession(long sessionId) {
return remoteSessionCache.getSession(sessionId);
}
public List<Long> getRemoteSessions() {
return getSessionList(curator.getChildren(sessionsPath));
}
public void addRemoteSession(RemoteSession session) {
remoteSessionCache.addSession(session);
metrics.incAddedSessions();
}
public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) {
int deleted = 0;
for (long sessionId : getRemoteSessions()) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
if (session.getStatus() == Session.Status.ACTIVATE) continue;
if (sessionHasExpired(session.getCreateTime(), expiryTime, clock)) {
log.log(Level.INFO, "Remote session " + sessionId + " for " + tenantName + " has expired, deleting it");
session.delete();
deleted++;
}
}
return deleted;
}
private boolean sessionHasExpired(Instant created, Duration expiryTime, Clock clock) {
return (created.plus(expiryTime).isBefore(clock.instant()));
}
private List<Long> getSessionListFromDirectoryCache(List<ChildData> children) {
return getSessionList(children.stream()
.map(child -> Path.fromString(child.getPath()).getName())
.collect(Collectors.toList()));
}
private List<Long> getSessionList(List<String> children) {
return children.stream().map(Long::parseLong).collect(Collectors.toList());
}
private void initializeRemoteSessions() throws NumberFormatException {
getRemoteSessions().forEach(this::sessionAdded);
}
private synchronized void sessionsChanged() throws NumberFormatException {
List<Long> sessions = getSessionListFromDirectoryCache(directoryCache.getCurrentData());
checkForRemovedSessions(sessions);
checkForAddedSessions(sessions);
}
private void checkForRemovedSessions(List<Long> sessions) {
for (RemoteSession session : remoteSessionCache.getSessions())
if ( ! sessions.contains(session.getSessionId()))
sessionRemoved(session.getSessionId());
}
private void checkForAddedSessions(List<Long> sessions) {
for (Long sessionId : sessions)
if (remoteSessionCache.getSession(sessionId) == null)
sessionAdded(sessionId);
}
/**
* A session for which we don't have a watcher, i.e. hitherto unknown to us.
*
* @param sessionId session id for the new session
*/
public void sessionAdded(long sessionId) {
try (var lock = lock(sessionId)) {
log.log(Level.FINE, () -> "Adding remote session to SessionRepository: " + sessionId);
RemoteSession remoteSession = createRemoteSession(sessionId);
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
fileCache.addListener(this::nodeChanged);
loadSessionIfActive(remoteSession);
addRemoteSession(remoteSession);
Optional<LocalSession> localSession = Optional.empty();
if (distributeApplicationPackage())
localSession = createLocalSessionUsingDistributedApplicationPackage(sessionId);
addSesssionStateWatcher(sessionId, fileCache, remoteSession, localSession);
}
}
boolean distributeApplicationPackage() {
return distributeApplicationPackage.value();
}
private void sessionRemoved(long sessionId) {
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
remoteSessionCache.removeSession(sessionId);
metrics.incRemovedSessions();
}
private void loadSessionIfActive(RemoteSession session) {
for (ApplicationId applicationId : applicationRepo.activeApplications()) {
if (applicationRepo.requireActiveSessionOf(applicationId) == session.getSessionId()) {
log.log(Level.FINE, () -> "Found active application for session " + session.getSessionId() + " , loading it");
applicationRepo.reloadConfig(session.ensureApplicationLoaded());
log.log(Level.INFO, session.logPre() + "Application activated successfully: " + applicationId + " (generation " + session.getSessionId() + ")");
return;
}
}
}
private void nodeChanged() {
zkWatcherExecutor.execute(() -> {
Multiset<Session.Status> sessionMetrics = HashMultiset.create();
for (RemoteSession session : remoteSessionCache.getSessions()) {
sessionMetrics.add(session.getStatus());
}
metrics.setNewSessions(sessionMetrics.count(Session.Status.NEW));
metrics.setPreparedSessions(sessionMetrics.count(Session.Status.PREPARE));
metrics.setActivatedSessions(sessionMetrics.count(Session.Status.ACTIVATE));
metrics.setDeactivatedSessions(sessionMetrics.count(Session.Status.DEACTIVATE));
});
}
@SuppressWarnings("unused")
private void childEvent(CuratorFramework ignored, PathChildrenCacheEvent event) {
zkWatcherExecutor.execute(() -> {
log.log(Level.FINE, () -> "Got child event: " + event);
switch (event.getType()) {
case CHILD_ADDED:
sessionsChanged();
synchronizeOnNew(getSessionListFromDirectoryCache(Collections.singletonList(event.getData())));
break;
case CHILD_REMOVED:
case CONNECTION_RECONNECTED:
sessionsChanged();
break;
}
});
}
private void synchronizeOnNew(List<Long> sessionList) {
for (long sessionId : sessionList) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
log.log(Level.FINE, () -> session.logPre() + "Confirming upload for session " + sessionId);
session.confirmUpload();
}
}
/**
* Creates a new deployment session from an application package.
*
* @param applicationDirectory a File pointing to an application.
* @param applicationId application id for this new session.
* @param timeoutBudget Timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSession(File applicationDirectory, ApplicationId applicationId,
TimeoutBudget timeoutBudget, Optional<Long> activeSessionId) {
return create(applicationDirectory, applicationId, activeSessionId, false, timeoutBudget);
}
public RemoteSession createRemoteSession(long sessionId) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new RemoteSession(tenantName, sessionId, componentRegistry, sessionZKClient);
}
private void ensureSessionPathDoesNotExist(long sessionId) {
Path sessionPath = getSessionPath(sessionId);
if (componentRegistry.getConfigCurator().exists(sessionPath.getAbsolute())) {
throw new IllegalArgumentException("Path " + sessionPath.getAbsolute() + " already exists in ZooKeeper");
}
}
private ApplicationPackage createApplication(File userDir,
File configApplicationDir,
ApplicationId applicationId,
long sessionId,
Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) {
long deployTimestamp = System.currentTimeMillis();
String user = System.getenv("USER");
if (user == null) {
user = "unknown";
}
DeployData deployData = new DeployData(user, userDir.getAbsolutePath(), applicationId, deployTimestamp,
internalRedeploy, sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSession));
return FilesApplicationPackage.fromFileWithDeployData(configApplicationDir, deployData);
}
private LocalSession createSessionFromApplication(ApplicationPackage applicationPackage,
long sessionId,
TimeoutBudget timeoutBudget,
Clock clock) {
log.log(Level.FINE, TenantRepository.logPre(tenantName) + "Creating session " + sessionId + " in ZooKeeper");
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
sessionZKClient.createNewSession(clock.instant());
Curator.CompletionWaiter waiter = sessionZKClient.getUploadWaiter();
LocalSession session = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
waiter.awaitCompletion(timeoutBudget.timeLeft());
return session;
}
/**
* Creates a new deployment session from an already existing session.
*
* @param existingSession the session to use as base
* @param logger a deploy logger where the deploy log will be written.
* @param internalRedeploy whether this session is for a system internal redeploy — not an application package change
* @param timeoutBudget timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSessionFromExisting(Session existingSession,
DeployLogger logger,
boolean internalRedeploy,
TimeoutBudget timeoutBudget) {
File existingApp = getSessionAppDir(existingSession.getSessionId());
ApplicationId existingApplicationId = existingSession.getApplicationId();
Optional<Long> activeSessionId = getActiveSessionId(existingApplicationId);
logger.log(Level.FINE, "Create new session for application id '" + existingApplicationId + "' from existing active session " + activeSessionId);
LocalSession session = create(existingApp, existingApplicationId, activeSessionId, internalRedeploy, timeoutBudget);
session.setApplicationId(existingApplicationId);
if (distributeApplicationPackage() && existingSession.getApplicationPackageReference() != null) {
session.setApplicationPackageReference(existingSession.getApplicationPackageReference());
}
session.setVespaVersion(existingSession.getVespaVersion());
session.setDockerImageRepository(existingSession.getDockerImageRepository());
session.setAthenzDomain(existingSession.getAthenzDomain());
return session;
}
private LocalSession create(File applicationFile, ApplicationId applicationId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy, TimeoutBudget timeoutBudget) {
long sessionId = getNextSessionId();
try {
ensureSessionPathDoesNotExist(sessionId);
ApplicationPackage app = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, internalRedeploy);
return createSessionFromApplication(app, sessionId, timeoutBudget, clock);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
/**
* This method is used when creating a session based on a remote session and the distributed application package
* It does not wait for session being created on other servers
*/
private LocalSession createLocalSession(File applicationFile, ApplicationId applicationId, long sessionId) {
try {
Optional<Long> currentlyActiveSessionId = getActiveSessionId(applicationId);
ApplicationPackage applicationPackage = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, false);
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZooKeeperClient, applicationRepo);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
private ApplicationPackage createApplicationPackage(File applicationFile, ApplicationId applicationId,
long sessionId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) throws IOException {
File userApplicationDir = getSessionAppDir(sessionId);
copyApp(applicationFile, userApplicationDir);
ApplicationPackage applicationPackage = createApplication(applicationFile,
userApplicationDir,
applicationId,
sessionId,
currentlyActiveSessionId,
internalRedeploy);
applicationPackage.writeMetaData();
return applicationPackage;
}
private void copyApp(File sourceDir, File destinationDir) throws IOException {
if (destinationDir.exists())
throw new RuntimeException("Destination dir " + destinationDir + " already exists");
if (! sourceDir.isDirectory())
throw new IllegalArgumentException(sourceDir.getAbsolutePath() + " is not a directory");
java.nio.file.Path tempDestinationDir = Files.createTempDirectory(destinationDir.getParentFile().toPath(), "app-package");
log.log(Level.FINE, "Copying dir " + sourceDir.getAbsolutePath() + " to " + tempDestinationDir.toFile().getAbsolutePath());
IOUtils.copyDirectory(sourceDir, tempDestinationDir.toFile());
log.log(Level.FINE, "Moving " + tempDestinationDir + " to " + destinationDir.getAbsolutePath());
Files.move(tempDestinationDir, destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE);
}
/**
* Returns a new session instance for the given session id.
*/
LocalSession createSessionFromId(long sessionId) {
File sessionDir = getAndValidateExistingSessionAppDir(sessionId);
ApplicationPackage applicationPackage = FilesApplicationPackage.fromFile(sessionDir);
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
}
/**
* Returns a new local session for the given session id if it does not already exist.
* Will also add the session to the local session cache if necessary
*/
public Optional<LocalSession> createLocalSessionUsingDistributedApplicationPackage(long sessionId) {
if (applicationRepo.hasLocalSession(sessionId)) {
log.log(Level.FINE, "Local session for session id " + sessionId + " already exists");
return Optional.of(createSessionFromId(sessionId));
}
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
FileReference fileReference = sessionZKClient.readApplicationPackageReference();
log.log(Level.FINE, "File reference for session id " + sessionId + ": " + fileReference);
if (fileReference != null) {
File rootDir = new File(Defaults.getDefaults().underVespaHome(componentRegistry.getConfigserverConfig().fileReferencesDir()));
File sessionDir;
FileDirectory fileDirectory = new FileDirectory(rootDir);
try {
sessionDir = fileDirectory.getFile(fileReference);
} catch (IllegalArgumentException e) {
log.log(Level.INFO, "File reference for session id " + sessionId + ": " + fileReference + " not found in " + fileDirectory);
return Optional.empty();
}
ApplicationId applicationId = sessionZKClient.readApplicationId();
log.log(Level.INFO, "Creating local session for session id " + sessionId);
LocalSession localSession = createLocalSession(sessionDir, applicationId, sessionId);
addLocalSession(localSession);
return Optional.of(localSession);
}
return Optional.empty();
}
private Optional<Long> getActiveSessionId(ApplicationId applicationId) {
List<ApplicationId> applicationIds = applicationRepo.activeApplications();
return applicationIds.contains(applicationId)
? Optional.of(applicationRepo.requireActiveSessionOf(applicationId))
: Optional.empty();
}
private long getNextSessionId() {
return new SessionCounter(componentRegistry.getConfigCurator(), tenantName).nextSessionId();
}
public Path getSessionPath(long sessionId) {
return sessionsPath.append(String.valueOf(sessionId));
}
Path getSessionStatePath(long sessionId) {
return getSessionPath(sessionId).append(ConfigCurator.SESSIONSTATE_ZK_SUBPATH);
}
private SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) {
String serverId = componentRegistry.getConfigserverConfig().serverId();
Optional<NodeFlavors> nodeFlavors = componentRegistry.getZone().nodeFlavors();
Path sessionPath = getSessionPath(sessionId);
return new SessionZooKeeperClient(curator, componentRegistry.getConfigCurator(), sessionPath, serverId, nodeFlavors);
}
private File getAndValidateExistingSessionAppDir(long sessionId) {
File appDir = getSessionAppDir(sessionId);
if (!appDir.exists() || !appDir.isDirectory()) {
throw new IllegalArgumentException("Unable to find correct application directory for session " + sessionId);
}
return appDir;
}
private File getSessionAppDir(long sessionId) {
return new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName).getUserApplicationDir(sessionId);
}
private void addSesssionStateWatcher(long sessionId, Curator.FileCache fileCache, RemoteSession remoteSession, Optional<LocalSession> localSession) {
if (sessionStateWatchers.containsKey(sessionId)) {
localSession.ifPresent(session -> sessionStateWatchers.get(sessionId).addLocalSession(session));
} else {
sessionStateWatchers.put(sessionId, new SessionStateWatcher(fileCache, applicationRepo, remoteSession,
localSession, metrics, zkWatcherExecutor, this));
}
}
@Override
public String toString() {
return getLocalSessions().toString();
}
/** Returns the lock for session operations for the given session id. */
public Lock lock(long sessionId) {
return curator.lock(lockPath(sessionId), Duration.ofMinutes(1));
}
private Path lockPath(long sessionId) {
return locksPath.append(String.valueOf(sessionId));
}
private static class FileTransaction extends AbstractTransaction {
public static FileTransaction from(FileOperation operation) {
FileTransaction transaction = new FileTransaction();
transaction.add(operation);
return transaction;
}
@Override
public void prepare() { }
@Override
public void commit() {
for (Operation operation : operations())
((FileOperation)operation).commit();
}
}
/** Factory for file operations */
private static class FileOperations {
/** Creates an operation which recursively deletes the given path */
public static DeleteOperation delete(String pathToDelete) {
return new DeleteOperation(pathToDelete);
}
}
private interface FileOperation extends Transaction.Operation {
void commit();
}
/**
* Recursively deletes this path and everything below.
* Succeeds with no action if the path does not exist.
*/
private static class DeleteOperation implements FileOperation {
private final String pathToDelete;
DeleteOperation(String pathToDelete) {
this.pathToDelete = pathToDelete;
}
@Override
public void commit() {
IOUtils.recursiveDeleteDir(new File(pathToDelete));
}
}
} | class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSession = 0;
private final SessionCache<LocalSession> localSessionCache = new SessionCache<>();
private final SessionCache<RemoteSession> remoteSessionCache = new SessionCache<>();
private final Map<Long, SessionStateWatcher> sessionStateWatchers = new HashMap<>();
private final Duration sessionLifetime;
private final Clock clock;
private final Curator curator;
private final Executor zkWatcherExecutor;
private final TenantFileSystemDirs tenantFileSystemDirs;
private final BooleanFlag distributeApplicationPackage;
private final MetricUpdater metrics;
private final Curator.DirectoryCache directoryCache;
private final TenantApplications applicationRepo;
private final SessionPreparer sessionPreparer;
private final Path sessionsPath;
private final TenantName tenantName;
private final GlobalComponentRegistry componentRegistry;
private final Path locksPath;
public SessionRepository(TenantName tenantName,
GlobalComponentRegistry componentRegistry,
TenantApplications applicationRepo,
FlagSource flagSource,
SessionPreparer sessionPreparer) {
this.tenantName = tenantName;
this.componentRegistry = componentRegistry;
this.sessionsPath = TenantRepository.getSessionsPath(tenantName);
this.clock = componentRegistry.getClock();
this.curator = componentRegistry.getCurator();
this.sessionLifetime = Duration.ofSeconds(componentRegistry.getConfigserverConfig().sessionLifetime());
this.zkWatcherExecutor = command -> componentRegistry.getZkWatcherExecutor().execute(tenantName, command);
this.tenantFileSystemDirs = new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName);
this.applicationRepo = applicationRepo;
this.sessionPreparer = sessionPreparer;
this.distributeApplicationPackage = Flags.CONFIGSERVER_DISTRIBUTE_APPLICATION_PACKAGE.bindTo(flagSource);
this.metrics = componentRegistry.getMetrics().getOrCreateMetricUpdater(Metrics.createDimensions(tenantName));
this.locksPath = TenantRepository.getLocksPath(tenantName);
loadLocalSessions();
initializeRemoteSessions();
this.directoryCache = curator.createDirectoryCache(sessionsPath.getAbsolute(), false, false, componentRegistry.getZkCacheExecutor());
this.directoryCache.addListener(this::childEvent);
this.directoryCache.start();
}
public synchronized void addLocalSession(LocalSession session) {
localSessionCache.addSession(session);
long sessionId = session.getSessionId();
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
RemoteSession remoteSession = createRemoteSession(sessionId);
addSesssionStateWatcher(sessionId, fileCache, remoteSession, Optional.of(session));
}
public LocalSession getLocalSession(long sessionId) {
return localSessionCache.getSession(sessionId);
}
public List<LocalSession> getLocalSessions() {
return localSessionCache.getSessions();
}
private void loadLocalSessions() {
File[] sessions = tenantFileSystemDirs.sessionsPath().listFiles(sessionApplicationsFilter);
if (sessions == null) return;
for (File session : sessions) {
try {
addLocalSession(createSessionFromId(Long.parseLong(session.getName())));
} catch (IllegalArgumentException e) {
log.log(Level.WARNING, "Could not load local session '" +
session.getAbsolutePath() + "':" + e.getMessage() + ", skipping it.");
}
}
}
public ConfigChangeActions prepareLocalSession(LocalSession session,
DeployLogger logger,
PrepareParams params,
Optional<ApplicationSet> currentActiveApplicationSet,
Path tenantPath,
Instant now) {
applicationRepo.createApplication(params.getApplicationId());
logger.log(Level.FINE, "Created application " + params.getApplicationId());
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
Curator.CompletionWaiter waiter = sessionZooKeeperClient.createPrepareWaiter();
ConfigChangeActions actions = sessionPreparer.prepare(applicationRepo.getHostValidator(), logger, params,
currentActiveApplicationSet, tenantPath, now,
getSessionAppDir(sessionId),
session.getApplicationPackage(), sessionZooKeeperClient);
session.setPrepared();
waiter.awaitCompletion(params.getTimeoutBudget().timeLeft());
return actions;
}
public void deleteExpiredSessions(Map<ApplicationId, Long> activeSessions) {
log.log(Level.FINE, "Purging old sessions");
try {
for (LocalSession candidate : localSessionCache.getSessions()) {
Instant createTime = candidate.getCreateTime();
log.log(Level.FINE, "Candidate session for deletion: " + candidate.getSessionId() + ", created: " + createTime);
if (hasExpired(candidate) && !isActiveSession(candidate)) {
deleteLocalSession(candidate);
} else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) {
ApplicationId applicationId = candidate.getApplicationId();
Long activeSession = activeSessions.get(applicationId);
if (activeSession == null || activeSession != candidate.getSessionId()) {
deleteLocalSession(candidate);
log.log(Level.INFO, "Deleted inactive session " + candidate.getSessionId() + " created " +
createTime + " for '" + applicationId + "'");
}
}
}
} catch (Throwable e) {
log.log(Level.WARNING, "Error when purging old sessions ", e);
}
log.log(Level.FINE, "Done purging old sessions");
}
private boolean hasExpired(LocalSession candidate) {
return (candidate.getCreateTime().plus(sessionLifetime).isBefore(clock.instant()));
}
private boolean isActiveSession(LocalSession candidate) {
return candidate.getStatus() == Session.Status.ACTIVATE;
}
/** Add transactions to delete this session to the given nested transaction */
public void deleteLocalSession(LocalSession session, NestedTransaction transaction) {
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
transaction.add(sessionZooKeeperClient.deleteTransaction(), FileTransaction.class);
transaction.add(FileTransaction.from(FileOperations.delete(getSessionAppDir(sessionId).getAbsolutePath())));
}
public void close() {
deleteAllSessions();
tenantFileSystemDirs.delete();
try {
if (directoryCache != null) {
directoryCache.close();
}
} catch (Exception e) {
log.log(Level.WARNING, "Exception when closing path cache", e);
} finally {
checkForRemovedSessions(new ArrayList<>());
}
}
private void deleteAllSessions() {
List<LocalSession> sessions = new ArrayList<>(localSessionCache.getSessions());
for (LocalSession session : sessions) {
deleteLocalSession(session);
}
}
public RemoteSession getRemoteSession(long sessionId) {
return remoteSessionCache.getSession(sessionId);
}
public List<Long> getRemoteSessions() {
return getSessionList(curator.getChildren(sessionsPath));
}
public void addRemoteSession(RemoteSession session) {
remoteSessionCache.addSession(session);
metrics.incAddedSessions();
}
public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) {
int deleted = 0;
for (long sessionId : getRemoteSessions()) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
if (session.getStatus() == Session.Status.ACTIVATE) continue;
if (sessionHasExpired(session.getCreateTime(), expiryTime, clock)) {
log.log(Level.INFO, "Remote session " + sessionId + " for " + tenantName + " has expired, deleting it");
session.delete();
deleted++;
}
}
return deleted;
}
private boolean sessionHasExpired(Instant created, Duration expiryTime, Clock clock) {
return (created.plus(expiryTime).isBefore(clock.instant()));
}
private List<Long> getSessionListFromDirectoryCache(List<ChildData> children) {
return getSessionList(children.stream()
.map(child -> Path.fromString(child.getPath()).getName())
.collect(Collectors.toList()));
}
private List<Long> getSessionList(List<String> children) {
return children.stream().map(Long::parseLong).collect(Collectors.toList());
}
private void initializeRemoteSessions() throws NumberFormatException {
getRemoteSessions().forEach(this::sessionAdded);
}
private synchronized void sessionsChanged() throws NumberFormatException {
List<Long> sessions = getSessionListFromDirectoryCache(directoryCache.getCurrentData());
checkForRemovedSessions(sessions);
checkForAddedSessions(sessions);
}
private void checkForRemovedSessions(List<Long> sessions) {
for (RemoteSession session : remoteSessionCache.getSessions())
if ( ! sessions.contains(session.getSessionId()))
sessionRemoved(session.getSessionId());
}
private void checkForAddedSessions(List<Long> sessions) {
for (Long sessionId : sessions)
if (remoteSessionCache.getSession(sessionId) == null)
sessionAdded(sessionId);
}
/**
* A session for which we don't have a watcher, i.e. hitherto unknown to us.
*
* @param sessionId session id for the new session
*/
public void sessionAdded(long sessionId) {
try (var lock = lock(sessionId)) {
log.log(Level.FINE, () -> "Adding remote session to SessionRepository: " + sessionId);
RemoteSession remoteSession = createRemoteSession(sessionId);
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
fileCache.addListener(this::nodeChanged);
loadSessionIfActive(remoteSession);
addRemoteSession(remoteSession);
Optional<LocalSession> localSession = Optional.empty();
if (distributeApplicationPackage())
localSession = createLocalSessionUsingDistributedApplicationPackage(sessionId);
addSesssionStateWatcher(sessionId, fileCache, remoteSession, localSession);
}
}
boolean distributeApplicationPackage() {
return distributeApplicationPackage.value();
}
private void sessionRemoved(long sessionId) {
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
remoteSessionCache.removeSession(sessionId);
metrics.incRemovedSessions();
}
private void loadSessionIfActive(RemoteSession session) {
for (ApplicationId applicationId : applicationRepo.activeApplications()) {
if (applicationRepo.requireActiveSessionOf(applicationId) == session.getSessionId()) {
log.log(Level.FINE, () -> "Found active application for session " + session.getSessionId() + " , loading it");
applicationRepo.reloadConfig(session.ensureApplicationLoaded());
log.log(Level.INFO, session.logPre() + "Application activated successfully: " + applicationId + " (generation " + session.getSessionId() + ")");
return;
}
}
}
private void nodeChanged() {
zkWatcherExecutor.execute(() -> {
Multiset<Session.Status> sessionMetrics = HashMultiset.create();
for (RemoteSession session : remoteSessionCache.getSessions()) {
sessionMetrics.add(session.getStatus());
}
metrics.setNewSessions(sessionMetrics.count(Session.Status.NEW));
metrics.setPreparedSessions(sessionMetrics.count(Session.Status.PREPARE));
metrics.setActivatedSessions(sessionMetrics.count(Session.Status.ACTIVATE));
metrics.setDeactivatedSessions(sessionMetrics.count(Session.Status.DEACTIVATE));
});
}
@SuppressWarnings("unused")
private void childEvent(CuratorFramework ignored, PathChildrenCacheEvent event) {
zkWatcherExecutor.execute(() -> {
log.log(Level.FINE, () -> "Got child event: " + event);
switch (event.getType()) {
case CHILD_ADDED:
sessionsChanged();
synchronizeOnNew(getSessionListFromDirectoryCache(Collections.singletonList(event.getData())));
break;
case CHILD_REMOVED:
case CONNECTION_RECONNECTED:
sessionsChanged();
break;
}
});
}
private void synchronizeOnNew(List<Long> sessionList) {
for (long sessionId : sessionList) {
RemoteSession session = remoteSessionCache.getSession(sessionId);
if (session == null) continue;
log.log(Level.FINE, () -> session.logPre() + "Confirming upload for session " + sessionId);
session.confirmUpload();
}
}
/**
* Creates a new deployment session from an application package.
*
* @param applicationDirectory a File pointing to an application.
* @param applicationId application id for this new session.
* @param timeoutBudget Timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSession(File applicationDirectory, ApplicationId applicationId,
TimeoutBudget timeoutBudget, Optional<Long> activeSessionId) {
return create(applicationDirectory, applicationId, activeSessionId, false, timeoutBudget);
}
public RemoteSession createRemoteSession(long sessionId) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new RemoteSession(tenantName, sessionId, componentRegistry, sessionZKClient);
}
private void ensureSessionPathDoesNotExist(long sessionId) {
Path sessionPath = getSessionPath(sessionId);
if (componentRegistry.getConfigCurator().exists(sessionPath.getAbsolute())) {
throw new IllegalArgumentException("Path " + sessionPath.getAbsolute() + " already exists in ZooKeeper");
}
}
private ApplicationPackage createApplication(File userDir,
File configApplicationDir,
ApplicationId applicationId,
long sessionId,
Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) {
long deployTimestamp = System.currentTimeMillis();
String user = System.getenv("USER");
if (user == null) {
user = "unknown";
}
DeployData deployData = new DeployData(user, userDir.getAbsolutePath(), applicationId, deployTimestamp,
internalRedeploy, sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSession));
return FilesApplicationPackage.fromFileWithDeployData(configApplicationDir, deployData);
}
private LocalSession createSessionFromApplication(ApplicationPackage applicationPackage,
long sessionId,
TimeoutBudget timeoutBudget,
Clock clock) {
log.log(Level.FINE, TenantRepository.logPre(tenantName) + "Creating session " + sessionId + " in ZooKeeper");
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
sessionZKClient.createNewSession(clock.instant());
Curator.CompletionWaiter waiter = sessionZKClient.getUploadWaiter();
LocalSession session = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
waiter.awaitCompletion(timeoutBudget.timeLeft());
return session;
}
/**
* Creates a new deployment session from an already existing session.
*
* @param existingSession the session to use as base
* @param logger a deploy logger where the deploy log will be written.
* @param internalRedeploy whether this session is for a system internal redeploy — not an application package change
* @param timeoutBudget timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSessionFromExisting(Session existingSession,
DeployLogger logger,
boolean internalRedeploy,
TimeoutBudget timeoutBudget) {
File existingApp = getSessionAppDir(existingSession.getSessionId());
ApplicationId existingApplicationId = existingSession.getApplicationId();
Optional<Long> activeSessionId = getActiveSessionId(existingApplicationId);
logger.log(Level.FINE, "Create new session for application id '" + existingApplicationId + "' from existing active session " + activeSessionId);
LocalSession session = create(existingApp, existingApplicationId, activeSessionId, internalRedeploy, timeoutBudget);
session.setApplicationId(existingApplicationId);
if (distributeApplicationPackage() && existingSession.getApplicationPackageReference() != null) {
session.setApplicationPackageReference(existingSession.getApplicationPackageReference());
}
session.setVespaVersion(existingSession.getVespaVersion());
session.setDockerImageRepository(existingSession.getDockerImageRepository());
session.setAthenzDomain(existingSession.getAthenzDomain());
return session;
}
private LocalSession create(File applicationFile, ApplicationId applicationId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy, TimeoutBudget timeoutBudget) {
long sessionId = getNextSessionId();
try {
ensureSessionPathDoesNotExist(sessionId);
ApplicationPackage app = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, internalRedeploy);
return createSessionFromApplication(app, sessionId, timeoutBudget, clock);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
/**
* This method is used when creating a session based on a remote session and the distributed application package
* It does not wait for session being created on other servers
*/
private LocalSession createLocalSession(File applicationFile, ApplicationId applicationId, long sessionId) {
try {
Optional<Long> currentlyActiveSessionId = getActiveSessionId(applicationId);
ApplicationPackage applicationPackage = createApplicationPackage(applicationFile, applicationId,
sessionId, currentlyActiveSessionId, false);
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZooKeeperClient, applicationRepo);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
private ApplicationPackage createApplicationPackage(File applicationFile, ApplicationId applicationId,
long sessionId, Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) throws IOException {
File userApplicationDir = getSessionAppDir(sessionId);
copyApp(applicationFile, userApplicationDir);
ApplicationPackage applicationPackage = createApplication(applicationFile,
userApplicationDir,
applicationId,
sessionId,
currentlyActiveSessionId,
internalRedeploy);
applicationPackage.writeMetaData();
return applicationPackage;
}
private void copyApp(File sourceDir, File destinationDir) throws IOException {
if (destinationDir.exists())
throw new RuntimeException("Destination dir " + destinationDir + " already exists");
if (! sourceDir.isDirectory())
throw new IllegalArgumentException(sourceDir.getAbsolutePath() + " is not a directory");
java.nio.file.Path tempDestinationDir = Files.createTempDirectory(destinationDir.getParentFile().toPath(), "app-package");
log.log(Level.FINE, "Copying dir " + sourceDir.getAbsolutePath() + " to " + tempDestinationDir.toFile().getAbsolutePath());
IOUtils.copyDirectory(sourceDir, tempDestinationDir.toFile());
log.log(Level.FINE, "Moving " + tempDestinationDir + " to " + destinationDir.getAbsolutePath());
Files.move(tempDestinationDir, destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE);
}
/**
* Returns a new session instance for the given session id.
*/
LocalSession createSessionFromId(long sessionId) {
File sessionDir = getAndValidateExistingSessionAppDir(sessionId);
ApplicationPackage applicationPackage = FilesApplicationPackage.fromFile(sessionDir);
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
return new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
}
/**
* Returns a new local session for the given session id if it does not already exist.
* Will also add the session to the local session cache if necessary
*/
public Optional<LocalSession> createLocalSessionUsingDistributedApplicationPackage(long sessionId) {
if (applicationRepo.hasLocalSession(sessionId)) {
log.log(Level.FINE, "Local session for session id " + sessionId + " already exists");
return Optional.of(createSessionFromId(sessionId));
}
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
FileReference fileReference = sessionZKClient.readApplicationPackageReference();
log.log(Level.FINE, "File reference for session id " + sessionId + ": " + fileReference);
if (fileReference != null) {
File rootDir = new File(Defaults.getDefaults().underVespaHome(componentRegistry.getConfigserverConfig().fileReferencesDir()));
File sessionDir;
FileDirectory fileDirectory = new FileDirectory(rootDir);
try {
sessionDir = fileDirectory.getFile(fileReference);
} catch (IllegalArgumentException e) {
log.log(Level.INFO, "File reference for session id " + sessionId + ": " + fileReference + " not found in " + fileDirectory);
return Optional.empty();
}
ApplicationId applicationId = sessionZKClient.readApplicationId();
log.log(Level.INFO, "Creating local session for session id " + sessionId);
LocalSession localSession = createLocalSession(sessionDir, applicationId, sessionId);
addLocalSession(localSession);
return Optional.of(localSession);
}
return Optional.empty();
}
private Optional<Long> getActiveSessionId(ApplicationId applicationId) {
List<ApplicationId> applicationIds = applicationRepo.activeApplications();
return applicationIds.contains(applicationId)
? Optional.of(applicationRepo.requireActiveSessionOf(applicationId))
: Optional.empty();
}
private long getNextSessionId() {
return new SessionCounter(componentRegistry.getConfigCurator(), tenantName).nextSessionId();
}
public Path getSessionPath(long sessionId) {
return sessionsPath.append(String.valueOf(sessionId));
}
Path getSessionStatePath(long sessionId) {
return getSessionPath(sessionId).append(ConfigCurator.SESSIONSTATE_ZK_SUBPATH);
}
private SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) {
String serverId = componentRegistry.getConfigserverConfig().serverId();
Optional<NodeFlavors> nodeFlavors = componentRegistry.getZone().nodeFlavors();
Path sessionPath = getSessionPath(sessionId);
return new SessionZooKeeperClient(curator, componentRegistry.getConfigCurator(), sessionPath, serverId, nodeFlavors);
}
private File getAndValidateExistingSessionAppDir(long sessionId) {
File appDir = getSessionAppDir(sessionId);
if (!appDir.exists() || !appDir.isDirectory()) {
throw new IllegalArgumentException("Unable to find correct application directory for session " + sessionId);
}
return appDir;
}
private File getSessionAppDir(long sessionId) {
return new TenantFileSystemDirs(componentRegistry.getConfigServerDB(), tenantName).getUserApplicationDir(sessionId);
}
private void addSesssionStateWatcher(long sessionId, Curator.FileCache fileCache, RemoteSession remoteSession, Optional<LocalSession> localSession) {
if (sessionStateWatchers.containsKey(sessionId)) {
localSession.ifPresent(session -> sessionStateWatchers.get(sessionId).addLocalSession(session));
} else {
sessionStateWatchers.put(sessionId, new SessionStateWatcher(fileCache, applicationRepo, remoteSession,
localSession, metrics, zkWatcherExecutor, this));
}
}
@Override
public String toString() {
return getLocalSessions().toString();
}
/** Returns the lock for session operations for the given session id. */
public Lock lock(long sessionId) {
return curator.lock(lockPath(sessionId), Duration.ofMinutes(1));
}
private Path lockPath(long sessionId) {
return locksPath.append(String.valueOf(sessionId));
}
private static class FileTransaction extends AbstractTransaction {
public static FileTransaction from(FileOperation operation) {
FileTransaction transaction = new FileTransaction();
transaction.add(operation);
return transaction;
}
@Override
public void prepare() { }
@Override
public void commit() {
for (Operation operation : operations())
((FileOperation)operation).commit();
}
}
/** Factory for file operations */
private static class FileOperations {
/** Creates an operation which recursively deletes the given path */
public static DeleteOperation delete(String pathToDelete) {
return new DeleteOperation(pathToDelete);
}
}
private interface FileOperation extends Transaction.Operation {
void commit();
}
/**
* Recursively deletes this path and everything below.
* Succeeds with no action if the path does not exist.
*/
private static class DeleteOperation implements FileOperation {
private final String pathToDelete;
DeleteOperation(String pathToDelete) {
this.pathToDelete = pathToDelete;
}
@Override
public void commit() {
IOUtils.recursiveDeleteDir(new File(pathToDelete));
}
}
} |
nit: the middle part of the message could be simplified to " locks older than " | protected void maintain() {
applicationRepository.deleteExpiredLocalSessions();
if (hostedVespa) {
Duration expiryTime = Duration.ofDays(1);
int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
log.log(LogLevel.FINE, "Deleted " + deleted + " expired remote sessions, expiry time " + expiryTime);
}
Duration lockExpiryTime = Duration.ofDays(1);
int deleted = applicationRepository.deleteExpiredLocks(lockExpiryTime);
log.log(LogLevel.INFO, "Deleted " + deleted + " expired locks, expiry time " + lockExpiryTime);
} | log.log(LogLevel.INFO, "Deleted " + deleted + " expired locks, expiry time " + lockExpiryTime); | protected void maintain() {
applicationRepository.deleteExpiredLocalSessions();
if (hostedVespa) {
Duration expiryTime = Duration.ofDays(1);
int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
log.log(LogLevel.FINE, "Deleted " + deleted + " expired remote sessions, expiry time " + expiryTime);
}
Duration lockExpiryTime = Duration.ofDays(1);
int deleted = applicationRepository.deleteExpiredLocks(lockExpiryTime);
log.log(LogLevel.INFO, "Deleted " + deleted + " locks older than " + lockExpiryTime);
} | class SessionsMaintainer extends ConfigServerMaintainer {
private final boolean hostedVespa;
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval) {
super(applicationRepository, curator, Duration.ZERO, interval);
this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
@Override
} | class SessionsMaintainer extends ConfigServerMaintainer {
private final boolean hostedVespa;
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval) {
super(applicationRepository, curator, Duration.ZERO, interval);
this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
@Override
} |
Why not add the embedding `container` element in `createModelAndGetHttp`? | public void access_control_filter_chains_are_set_up() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain' />",
" </filtering>",
" </http>",
"</container>");
FilterChains filterChains = http.getFilterChains();
assertTrue(filterChains.hasChain(AccessControl.ACCESS_CONTROL_CHAIN_ID));
assertTrue(filterChains.hasChain(AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID));
Chain<Filter> excludedChain = filterChains.allChains().getComponent(AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID);
Collection<Filter> innerComponents = excludedChain.getInnerComponents();
assertThat(innerComponents, hasSize(1));
String accessControlExcludedChain = innerComponents.iterator().next().getClassId().stringValue();
assertEquals("com.yahoo.jdisc.http.filter.security.misc.NoopFilter", accessControlExcludedChain);
} | "<container version='1.0'>", | public void access_control_filter_chains_are_set_up() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain' />",
" </filtering>",
" </http>");
FilterChains filterChains = http.getFilterChains();
assertTrue(filterChains.hasChain(AccessControl.ACCESS_CONTROL_CHAIN_ID));
assertTrue(filterChains.hasChain(AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID));
} | class AccessControlTest extends ContainerModelBuilderTestBase {
@Test
@Test
public void properties_are_set_from_xml() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain'/>",
" </filtering>",
" </http>",
"</container>");
AccessControl accessControl = http.getAccessControl().get();
assertEquals("Wrong domain.", "my-tenant-domain", accessControl.domain);
}
@Test
public void read_is_disabled_and_write_is_enabled_by_default() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain'/>",
" </filtering>",
" </http>",
"</container>");
assertFalse("Wrong default value for read.", http.getAccessControl().get().readEnabled);
assertTrue("Wrong default value for write.", http.getAccessControl().get().writeEnabled);
}
@Test
public void read_and_write_can_be_overridden() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain' read='true' write='false'/>",
" </filtering>",
" </http>",
"</container>");
assertTrue("Given read value not honoured.", http.getAccessControl().get().readEnabled);
assertFalse("Given write value not honoured.", http.getAccessControl().get().writeEnabled);
}
@Test
public void access_control_excluded_filter_chain_has_all_bindings_from_excluded_handlers() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <filtering>",
" <access-control/>",
" </filtering>",
" </http>",
"</container>");
Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID);
assertThat(actualBindings, containsInAnyOrder(
"http:
"http:
"http:
"http:
"http:
"http:
"http:
"http:
"http:
}
@Test
public void access_control_excluded_filter_chain_has_user_provided_excluded_bindings() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <handler id='custom.Handler'>",
" <binding>http:
" </handler>",
" <filtering>",
" <access-control>",
" <exclude>",
" <binding>http:
" <binding>http:
" </exclude>",
" </access-control>",
" </filtering>",
" </http>",
"</container>");
Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID);
assertThat(actualBindings, hasItems("http:
}
@Test
public void access_control_filter_chain_contains_catchall_bindings() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <filtering>",
" <access-control/>",
" </filtering>",
" </http>",
"</container>");
Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_CHAIN_ID);
assertThat(actualBindings, containsInAnyOrder("http:
}
@Test
public void access_control_is_implicitly_added_for_hosted_apps() {
Http http = createModelAndGetHttp("<container version='1.0'/>");
Optional<AccessControl> maybeAccessControl = http.getAccessControl();
assertThat(maybeAccessControl.isPresent(), is(true));
AccessControl accessControl = maybeAccessControl.get();
assertThat(accessControl.writeEnabled, is(false));
assertThat(accessControl.readEnabled, is(false));
assertThat(accessControl.domain, equalTo("my-tenant-domain"));
}
@Test
public void access_control_is_implicitly_added_for_hosted_apps_with_existing_http_element() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <server port='" + getDefaults().vespaWebServicePort() + "' id='main' />",
" <filtering>",
" <filter id='outer' />",
" <request-chain id='myChain'>",
" <filter id='inner' />",
" </request-chain>",
" </filtering>",
" </http>",
"</container>" );
assertThat(http.getAccessControl().isPresent(), is(true));
assertThat(http.getFilterChains().hasChain(AccessControl.ACCESS_CONTROL_CHAIN_ID), is(true));
assertThat(http.getFilterChains().hasChain(ComponentId.fromString("myChain")), is(true));
}
private Http createModelAndGetHttp(String... servicesXml) {
AthenzDomain tenantDomain = AthenzDomain.from("my-tenant-domain");
DeployState state = new DeployState.Builder().properties(
new TestProperties()
.setAthenzDomain(tenantDomain)
.setHostedVespa(true))
.build();
createModel(root, state, null, DomBuilderTest.parse(servicesXml));
return ((ApplicationContainer) root.getProducer("container/container.0")).getHttp();
}
private static Set<String> getFilterBindings(Http http, ComponentId filerChain) {
return http.getBindings().stream()
.filter(binding -> binding.filterId().toId().equals(filerChain))
.map(binding -> binding.binding().patternString())
.collect(Collectors.toSet());
}
} | class AccessControlTest extends ContainerModelBuilderTestBase {
@Test
@Test
public void properties_are_set_from_xml() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain'/>",
" </filtering>",
" </http>");
AccessControl accessControl = http.getAccessControl().get();
assertEquals("Wrong domain.", "my-tenant-domain", accessControl.domain);
}
@Test
public void read_is_disabled_and_write_is_enabled_by_default() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain'/>",
" </filtering>",
" </http>");
assertFalse("Wrong default value for read.", http.getAccessControl().get().readEnabled);
assertTrue("Wrong default value for write.", http.getAccessControl().get().writeEnabled);
}
@Test
public void read_and_write_can_be_overridden() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain' read='true' write='false'/>",
" </filtering>",
" </http>");
assertTrue("Given read value not honoured.", http.getAccessControl().get().readEnabled);
assertFalse("Given write value not honoured.", http.getAccessControl().get().writeEnabled);
}
@Test
public void access_control_excluded_filter_chain_has_all_bindings_from_excluded_handlers() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control/>",
" </filtering>",
" </http>");
Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID);
assertThat(actualBindings, containsInAnyOrder(
"http:
"http:
"http:
"http:
"http:
"http:
"http:
"http:
"http:
}
@Test
public void access_control_excluded_chain_does_not_contain_any_bindings_from_access_control_chain() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control/>",
" </filtering>",
" </http>");
Set<String> bindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_CHAIN_ID);
Set<String> excludedBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID);
for (String binding : bindings) {
assertThat(excludedBindings, not(hasItem(binding)));
}
}
@Test
public void access_control_excluded_filter_chain_has_user_provided_excluded_bindings() {
Http http = createModelAndGetHttp(
" <http>",
" <handler id='custom.Handler'>",
" <binding>http:
" </handler>",
" <filtering>",
" <access-control>",
" <exclude>",
" <binding>http:
" <binding>http:
" </exclude>",
" </access-control>",
" </filtering>",
" </http>");
Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID);
assertThat(actualBindings, hasItems("http:
}
@Test
public void access_control_filter_chain_contains_catchall_bindings() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control/>",
" </filtering>",
" </http>");
Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_CHAIN_ID);
assertThat(actualBindings, containsInAnyOrder("http:
}
@Test
public void access_control_is_implicitly_added_for_hosted_apps() {
Http http = createModelAndGetHttp("<container version='1.0'/>");
Optional<AccessControl> maybeAccessControl = http.getAccessControl();
assertThat(maybeAccessControl.isPresent(), is(true));
AccessControl accessControl = maybeAccessControl.get();
assertThat(accessControl.writeEnabled, is(false));
assertThat(accessControl.readEnabled, is(false));
assertThat(accessControl.domain, equalTo("my-tenant-domain"));
}
@Test
public void access_control_is_implicitly_added_for_hosted_apps_with_existing_http_element() {
Http http = createModelAndGetHttp(
" <http>",
" <server port='" + getDefaults().vespaWebServicePort() + "' id='main' />",
" <filtering>",
" <filter id='outer' />",
" <request-chain id='myChain'>",
" <filter id='inner' />",
" </request-chain>",
" </filtering>",
" </http>");
assertThat(http.getAccessControl().isPresent(), is(true));
assertThat(http.getFilterChains().hasChain(AccessControl.ACCESS_CONTROL_CHAIN_ID), is(true));
assertThat(http.getFilterChains().hasChain(ComponentId.fromString("myChain")), is(true));
}
private Http createModelAndGetHttp(String... httpElement) {
List<String> servicesXml = new ArrayList<>();
servicesXml.add("<container version='1.0'>");
servicesXml.addAll(List.of(httpElement));
servicesXml.add("</container>");
AthenzDomain tenantDomain = AthenzDomain.from("my-tenant-domain");
DeployState state = new DeployState.Builder().properties(
new TestProperties()
.setAthenzDomain(tenantDomain)
.setHostedVespa(true))
.build();
createModel(root, state, null, DomBuilderTest.parse(servicesXml.toArray(String[]::new)));
return ((ApplicationContainer) root.getProducer("container/container.0")).getHttp();
}
private static Set<String> getFilterBindings(Http http, ComponentId filerChain) {
return http.getBindings().stream()
.filter(binding -> binding.chainId().toId().equals(filerChain))
.map(binding -> binding.binding().patternString())
.collect(Collectors.toSet());
}
} |
thanks, will fix | protected void maintain() {
applicationRepository.deleteExpiredLocalSessions();
if (hostedVespa) {
Duration expiryTime = Duration.ofDays(1);
int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
log.log(LogLevel.FINE, "Deleted " + deleted + " expired remote sessions, expiry time " + expiryTime);
}
Duration lockExpiryTime = Duration.ofDays(1);
int deleted = applicationRepository.deleteExpiredLocks(lockExpiryTime);
log.log(LogLevel.INFO, "Deleted " + deleted + " expired locks, expiry time " + lockExpiryTime);
} | log.log(LogLevel.INFO, "Deleted " + deleted + " expired locks, expiry time " + lockExpiryTime); | protected void maintain() {
applicationRepository.deleteExpiredLocalSessions();
if (hostedVespa) {
Duration expiryTime = Duration.ofDays(1);
int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
log.log(LogLevel.FINE, "Deleted " + deleted + " expired remote sessions, expiry time " + expiryTime);
}
Duration lockExpiryTime = Duration.ofDays(1);
int deleted = applicationRepository.deleteExpiredLocks(lockExpiryTime);
log.log(LogLevel.INFO, "Deleted " + deleted + " locks older than " + lockExpiryTime);
} | class SessionsMaintainer extends ConfigServerMaintainer {
private final boolean hostedVespa;
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval) {
super(applicationRepository, curator, Duration.ZERO, interval);
this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
@Override
} | class SessionsMaintainer extends ConfigServerMaintainer {
private final boolean hostedVespa;
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval) {
super(applicationRepository, curator, Duration.ZERO, interval);
this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
@Override
} |
What about test/staging? If this indeed only applies to prod, we can perhaps use the path `/application/v4/tenant/{tenant}/application/{application}/environment/prod`? | private HttpResponse handleDELETE(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeProdAllDeployments(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
return ErrorResponse.notFoundError("Nothing at " + path);
} | if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeProdAllDeployments(path.get("tenant"), path.get("application")); | private HttpResponse handleDELETE(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeAllProdDeployments(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
return ErrorResponse.notFoundError("Nothing at " + path);
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestConfigSerializer testConfigSerializer;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
}
@Override
public Duration getTimeout() {
return Duration.ofMinutes(20);
}
@Override
public HttpResponse handle(HttpRequest request) {
try {
Path path = new Path(request.getUri(), OPTIONAL_PREFIX);
switch (request.getMethod()) {
case GET: return handleGET(path, request);
case PUT: return handlePUT(path, request);
case POST: return handlePOST(path, request);
case PATCH: return handlePATCH(path, request);
case DELETE: return handleDELETE(path, request);
case OPTIONS: return handleOPTIONS();
default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
}
}
catch (ForbiddenException e) {
return ErrorResponse.forbidden(Exceptions.toMessageString(e));
}
catch (NotAuthorizedException e) {
return ErrorResponse.unauthorized(Exceptions.toMessageString(e));
}
catch (NotExistsException e) {
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
}
catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
catch (ConfigServerException e) {
switch (e.getErrorCode()) {
case NOT_FOUND:
return new ErrorResponse(NOT_FOUND, e.getErrorCode().name(), Exceptions.toMessageString(e));
case ACTIVATION_CONFLICT:
return new ErrorResponse(CONFLICT, e.getErrorCode().name(), Exceptions.toMessageString(e));
case INTERNAL_SERVER_ERROR:
return new ErrorResponse(INTERNAL_SERVER_ERROR, e.getErrorCode().name(), Exceptions.toMessageString(e));
default:
return new ErrorResponse(BAD_REQUEST, e.getErrorCode().name(), Exceptions.toMessageString(e));
}
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/tenant")) return tenants(request);
if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePUT(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePATCH(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleOPTIONS() {
EmptyResponse response = new EmptyResponse();
response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS");
return response;
}
private HttpResponse recursiveRoot(HttpRequest request) {
Slime slime = new Slime();
Cursor tenantArray = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
toSlime(tenantArray.addObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse root(HttpRequest request) {
return recurseOverTenants(request)
? recursiveRoot(request)
: new ResourceResponse(request, "tenant");
}
private HttpResponse tenants(HttpRequest request) {
Slime slime = new Slime();
Cursor response = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject());
return new SlimeJsonResponse(slime);
}
private HttpResponse tenant(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenant(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenant(Tenant tenant, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
if (controller.tenants().get(tenantName).isEmpty())
return ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist");
Slime slime = new Slime();
Cursor applicationArray = slime.setArray();
for (com.yahoo.vespa.hosted.controller.Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true)) {
Cursor applicationObject = applicationArray.addObject();
applicationObject.setString("tenant", application.id().tenant().value());
applicationObject.setString("application", application.id().application().value());
applicationObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value(),
request.getUri()).toString());
Cursor instanceArray = applicationObject.setArray("instances");
for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet()
: application.instances().keySet()) {
Cursor instanceObject = instanceArray.addObject();
instanceObject.setString("instance", instance.value());
instanceObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/instance/" + instance.value(),
request.getUri()).toString());
}
}
}
return new SlimeJsonResponse(slime);
}
private HttpResponse devApplicationPackage(ApplicationId id, JobType type) {
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Only manually deployed zones have dev packages");
ZoneId zone = type.zone(controller.system());
byte[] applicationPackage = controller.applications().applicationStore().getDev(id, zone);
return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage);
}
private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse compileVersion(String tenantName, String applicationName) {
Slime slime = new Slime();
slime.setObject().setString("compileVersion",
compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString());
return new SlimeJsonResponse(slime);
}
private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
Principal user = request.getJDiscRequest().getUserPrincipal();
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withDeveloperKey(developerKey, user);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Principal user = ((CloudTenant) controller.tenants().require(TenantName.from(tenantName))).developerKeys().get(developerKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withoutDeveloperKey(developerKey);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) {
keys.forEach((key, principal) -> {
Cursor keyObject = keysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", principal.getName());
});
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withoutDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes.");
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
Inspector majorVersionField = requestObject.field("majorVersion");
if (majorVersionField.valid()) {
Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong();
application = application.withMajorVersion(majorVersion);
messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion));
}
Inspector pemDeployKeyField = requestObject.field("pemDeployKey");
if (pemDeployKeyField.valid()) {
String pemDeployKey = pemDeployKeyField.asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
application = application.withDeployKey(deployKey);
messageBuilder.add("Added deploy key " + pemDeployKey);
}
controller.applications().store(application);
});
return new MessageResponse(messageBuilder.toString());
}
private com.yahoo.vespa.hosted.controller.Application getApplication(String tenantName, String applicationName) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
return controller.applications().getApplication(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private Instance getInstance(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
return controller.applications().getInstance(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, id);
Slime slime = new Slime();
Cursor nodesArray = slime.setObject().setArray("nodes");
for (Node node : nodes) {
Cursor nodeObject = nodesArray.addObject();
nodeObject.setString("hostname", node.hostname().value());
nodeObject.setString("state", valueOf(node.state()));
node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.flavor());
toSlime(node.resources(), nodeObject);
nodeObject.setBool("fastDisk", node.resources().diskSpeed() == NodeResources.DiskSpeed.fast);
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
return new SlimeJsonResponse(slime);
}
private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id);
Slime slime = new Slime();
Cursor clustersObject = slime.setObject().setObject("clusters");
for (Cluster cluster : application.clusters().values()) {
Cursor clusterObject = clustersObject.setObject(cluster.id().value());
toSlime(cluster.min(), clusterObject.setObject("min"));
toSlime(cluster.max(), clusterObject.setObject("max"));
toSlime(cluster.current(), clusterObject.setObject("current"));
cluster.target().ifPresent(target -> toSlime(target, clusterObject.setObject("target")));
cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested")));
}
return new SlimeJsonResponse(slime);
}
private static String valueOf(Node.State state) {
switch (state) {
case failed: return "failed";
case parked: return "parked";
case dirty: return "dirty";
case ready: return "ready";
case active: return "active";
case inactive: return "inactive";
case reserved: return "reserved";
case provisioned: return "provisioned";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ServiceState state) {
switch (state) {
case expectedUp: return "expectedUp";
case allowedDown: return "allowedDown";
case unorchestrated: return "unorchestrated";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ClusterType type) {
switch (type) {
case admin: return "admin";
case content: return "content";
case container: return "container";
case combined: return "combined";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
private static String valueOf(NodeResources.DiskSpeed diskSpeed) {
switch (diskSpeed) {
case fast : return "fast";
case slow : return "slow";
case any : return "any";
default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'");
}
}
private static String valueOf(NodeResources.StorageType storageType) {
switch (storageType) {
case remote : return "remote";
case local : return "local";
case any : return "any";
default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'");
}
}
private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters);
return new HttpResponse(200) {
@Override
public void render(OutputStream outputStream) throws IOException {
logStream.transferTo(outputStream);
}
};
}
private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
boolean requireTests = ! requestObject.field("skipTests").asBool();
boolean reTrigger = requestObject.field("reTrigger").asBool();
String triggered = reTrigger
? controller.applications().deploymentTrigger()
.reTrigger(id, type).type().jobName()
: controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests)
.stream().map(job -> job.type().jobName()).collect(joining(", "));
return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered"
: "Triggered " + triggered + " for " + id);
}
private HttpResponse pause(ApplicationId id, JobType type) {
Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause);
controller.applications().deploymentTrigger().pauseJob(id, type, until);
return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause);
}
private HttpResponse resume(ApplicationId id, JobType type) {
controller.applications().deploymentTrigger().resumeJob(id, type);
return new MessageResponse(type.jobName() + " for " + id + " resumed");
}
private void toSlime(Cursor object, com.yahoo.vespa.hosted.controller.Application application, HttpRequest request) {
object.setString("tenant", application.id().tenant().value());
object.setString("application", application.id().application().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/job/",
request.getUri()).toString());
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
application.instances().values().stream().findFirst().ifPresent(instance -> {
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
});
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request);
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
if (deploymentSpec.instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec.requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
globalEndpointsToSlime(object, instance);
List<Deployment> deployments = deploymentSpec.instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor deploymentsArray = object.setArray("deployments");
for (Deployment deployment : deployments) {
Cursor deploymentObject = deploymentsArray.addObject();
if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty())
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/instance/" + instance.name().value() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
}
private void globalEndpointsToSlime(Cursor object, Instance instance) {
var globalEndpointUrls = new LinkedHashSet<String>();
controller.routing().endpointsOf(instance.id())
.requiresRotation()
.not().legacy()
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalEndpointUrls::add);
var globalRotationsArray = object.setArray("globalRotations");
globalEndpointUrls.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
}
private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) {
com.yahoo.vespa.hosted.controller.Application application = status.application();
object.setString("tenant", instance.id().tenant().value());
object.setString("application", instance.id().application().value());
object.setString("instance", instance.id().instance().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + instance.id().tenant().value() +
"/application/" + instance.id().application().value() +
"/instance/" + instance.id().instance().value() + "/job/",
request.getUri()).toString());
application.latestVersion().ifPresent(version -> {
sourceRevisionToSlime(version.source(), object.setObject("source"));
version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
version.commit().ifPresent(commit -> object.setString("commit", commit));
});
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if (application.deploymentSpec().instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec().requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
globalEndpointsToSlime(object, instance);
List<Deployment> deployments =
application.deploymentSpec().instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor instancesArray = object.setArray("instances");
for (Deployment deployment : deployments) {
Cursor deploymentObject = instancesArray.addObject();
if (deployment.zone().environment() == Environment.prod) {
if (instance.rotations().size() == 1) {
toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment),
deploymentObject);
}
if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) {
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
}
}
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("instance", instance.id().instance().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
status.jobSteps().keySet().stream()
.filter(job -> job.application().instance().equals(instance.name()))
.filter(job -> job.type().isProduction() && job.type().isDeployment())
.map(job -> job.type().zone(controller.system()))
.filter(zone -> ! instance.deployments().containsKey(zone))
.forEach(zone -> {
Cursor deploymentObject = instancesArray.addObject();
deploymentObject.setString("environment", zone.environment().value());
deploymentObject.setString("region", zone.region().value());
});
application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key)));
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().getInstance(id)
.orElseThrow(() -> new NotExistsException(id + " not found"));
DeploymentId deploymentId = new DeploymentId(instance.id(),
ZoneId.from(environment, region));
Deployment deployment = instance.deployments().get(deploymentId.zoneId());
if (deployment == null)
throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId());
Slime slime = new Slime();
toSlime(slime.setObject(), deploymentId, deployment, request);
return new SlimeJsonResponse(slime);
}
private void toSlime(Cursor object, Change change) {
change.platform().ifPresent(version -> object.setString("version", version.toString()));
change.application()
.filter(version -> !version.isUnknown())
.ifPresent(version -> toSlime(version, object.setObject("revision")));
}
private void toSlime(Endpoint endpoint, String cluster, Cursor object) {
object.setString("cluster", cluster);
object.setBool("tls", endpoint.tls());
object.setString("url", endpoint.url().toString());
object.setString("scope", endpointScopeString(endpoint.scope()));
object.setString("routingMethod", routingMethodString(endpoint.routingMethod()));
}
private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) {
response.setString("tenant", deploymentId.applicationId().tenant().value());
response.setString("application", deploymentId.applicationId().application().value());
response.setString("instance", deploymentId.applicationId().instance().value());
response.setString("environment", deploymentId.zoneId().environment().value());
response.setString("region", deploymentId.zoneId().region().value());
var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId()));
var endpointArray = response.setArray("endpoints");
for (var endpoint : controller.routing().endpointsOf(deploymentId)
.scope(Endpoint.Scope.zone)
.not().legacy()) {
toSlime(endpoint, endpoint.name(), endpointArray.addObject());
}
var globalEndpoints = controller.routing().endpointsOf(application, deploymentId.applicationId().instance())
.not().legacy()
.targets(deploymentId.zoneId());
for (var endpoint : globalEndpoints) {
toSlime(endpoint, endpoint.cluster().value(), endpointArray.addObject());
}
response.setString("nodes", withPath("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/?&recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString());
response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString());
response.setString("version", deployment.version().toFullString());
response.setString("revision", deployment.applicationVersion().id());
response.setLong("deployTimeEpochMs", deployment.at().toEpochMilli());
controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId())
.ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", deployment.at().plus(deploymentTimeToLive).toEpochMilli()));
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
var instance = application.instances().get(deploymentId.applicationId().instance());
if (instance != null) {
if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod)
toSlime(instance.rotations(), instance.rotationStatus(), deployment, response);
JobType.from(controller.system(), deployment.zone())
.map(type -> new JobId(instance.id(), type))
.map(status.jobSteps()::get)
.ifPresent(stepStatus -> {
JobControllerApiHandlerHelper.applicationVersionToSlime(
response.setObject("applicationVersion"), deployment.applicationVersion());
if (!status.jobsToRun().containsKey(stepStatus.job().get()))
response.setString("status", "complete");
else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true))
response.setString("status", "pending");
else response.setString("status", "running");
});
}
Cursor activity = response.setObject("activity");
deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried",
instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten",
instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
DeploymentMetrics metrics = deployment.metrics();
Cursor metricsObject = response.setObject("metrics");
metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond());
metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond());
metricsObject.setDouble("documentCount", metrics.documentCount());
metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis());
metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli()));
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if ( ! applicationVersion.isUnknown()) {
object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong());
object.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if (revision.isEmpty()) return;
object.setString("gitRepository", revision.get().repository());
object.setString("gitBranch", revision.get().branch());
object.setString("gitCommit", revision.get().commit());
}
private void toSlime(RotationState state, Cursor object) {
Cursor bcpStatus = object.setObject("bcpStatus");
bcpStatus.setString("rotationStatus", rotationStateString(state));
}
private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) {
var array = object.setArray("endpointStatus");
for (var rotation : rotations) {
var statusObject = array.addObject();
var targets = status.of(rotation.rotationId());
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("rotationId", rotation.rotationId().asString());
statusObject.setString("clusterId", rotation.clusterId().value());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli());
}
}
private URI monitoringSystemUri(DeploymentId deploymentId) {
return controller.zoneRegistry().getMonitoringSystemUri(deploymentId);
}
/**
* Returns a non-broken, released version at least as old as the oldest platform the given application is on.
*
* If no known version is applicable, the newest version at least as old as the oldest platform is selected,
* among all versions released for this system. If no such versions exists, throws an IllegalStateException.
*/
private Version compileVersion(TenantAndApplicationId id) {
Version oldestPlatform = controller.applications().oldestInstalledPlatform(id);
VersionStatus versionStatus = controller.versionStatus();
return versionStatus.versions().stream()
.filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low))
.filter(VespaVersion::isReleased)
.map(VespaVersion::versionNumber)
.filter(version -> ! version.isAfter(oldestPlatform))
.max(Comparator.naturalOrder())
.orElseGet(() -> controller.mavenRepository().metadata().versions().stream()
.filter(version -> ! version.isAfter(oldestPlatform))
.filter(version -> ! versionStatus.versions().stream()
.map(VespaVersion::versionNumber)
.collect(Collectors.toSet()).contains(version))
.max(Comparator.naturalOrder())
.orElseThrow(() -> new IllegalStateException("No available releases of " +
controller.mavenRepository().artifactId())));
}
private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
ZoneId zone = ZoneId.from(environment, region);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
var deploymentId = new DeploymentId(instance.id(), zone);
setGlobalRotationStatus(deploymentId, inService, request);
setGlobalEndpointStatus(deploymentId, inService, request);
return new MessageResponse(String.format("Successfully set %s in %s %s service",
instance.id().toShortString(), zone, inService ? "in" : "out of"));
}
/** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */
private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
var status = inService ? GlobalRouting.Status.in : GlobalRouting.Status.out;
controller.routing().policies().setGlobalRoutingStatus(deployment, status, agent);
}
/** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */
private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var requestData = toSlime(request.getData()).get();
var reason = mandatory("reason", requestData).asString();
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
long timestamp = controller.clock().instant().getEpochSecond();
var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp);
controller.routing().setGlobalRotationStatus(deployment, endpointStatus);
}
private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Slime slime = new Slime();
Cursor array = slime.setObject().setArray("globalrotationoverride");
controller.routing().globalRotationStatus(deploymentId)
.forEach((endpoint, status) -> {
array.addString(endpoint.upstreamIdOf(deploymentId));
Cursor statusObject = array.addObject();
statusObject.setString("status", status.getStatus().name());
statusObject.setString("reason", status.getReason() == null ? "" : status.getReason());
statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent());
statusObject.setLong("timestamp", status.getEpoch());
});
return new SlimeJsonResponse(slime);
}
private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().requireInstance(applicationId);
ZoneId zone = ZoneId.from(environment, region);
RotationId rotation = findRotationId(instance, endpointId);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
Slime slime = new Slime();
Cursor response = slime.setObject();
toSlime(instance.rotationStatus().of(rotation, deployment), response);
return new SlimeJsonResponse(slime);
}
private HttpResponse metering(String tenant, String application, HttpRequest request) {
Slime slime = new Slime();
Cursor root = slime.setObject();
MeteringData meteringData = controller.serviceRegistry()
.meteringService()
.getMeteringData(TenantName.from(tenant), ApplicationName.from(application));
ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringData.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringData.getLastMonth();
Cursor lastmonth = root.setObject("lastmonth");
lastmonth.setDouble("cpu", lastMonth.getCpuCores());
lastmonth.setDouble("mem", lastMonth.getMemoryGb());
lastmonth.setDouble("disk", lastMonth.getDiskGb());
Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory();
Cursor details = root.setObject("details");
Cursor detailsCpu = details.setObject("cpu");
Cursor detailsMem = details.setObject("mem");
Cursor detailsDisk = details.setObject("disk");
history.entrySet().stream()
.forEach(entry -> {
String instanceName = entry.getKey().instance().value();
Cursor detailsCpuApp = detailsCpu.setObject(instanceName);
Cursor detailsMemApp = detailsMem.setObject(instanceName);
Cursor detailsDiskApp = detailsDisk.setObject(instanceName);
Cursor detailsCpuData = detailsCpuApp.setArray("data");
Cursor detailsMemData = detailsMemApp.setArray("data");
Cursor detailsDiskData = detailsDiskApp.setArray("data");
entry.getValue().stream()
.forEach(resourceSnapshot -> {
Cursor cpu = detailsCpuData.addObject();
cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
cpu.setDouble("value", resourceSnapshot.getCpuCores());
Cursor mem = detailsMemData.addObject();
mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
mem.setDouble("value", resourceSnapshot.getMemoryGb());
Cursor disk = detailsDiskData.addObject();
disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
disk.setDouble("value", resourceSnapshot.getDiskGb());
});
});
return new SlimeJsonResponse(slime);
}
private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! instance.change().isEmpty()) {
instance.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", instance.change().isPinned());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
boolean suspended = controller.applications().isSuspended(deploymentId);
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setBool("suspended", suspended);
return new SlimeJsonResponse(slime);
}
private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region);
ServiceApiResponse response = new ServiceApiResponse(ZoneId.from(environment, region),
new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(),
controller.zoneRegistry().getConfigServerApiUris(ZoneId.from(environment, region)),
request.getUri());
response.setResponse(applicationView);
return response;
}
private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), ZoneId.from(environment, region));
if ("container-clustercontroller".equals((serviceName)) && restPath.contains("/status/")) {
String result = controller.serviceRegistry().configServer().getClusterControllerStatus(deploymentId, restPath);
return new HtmlResponse(result);
}
Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath);
ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(),
deploymentId.applicationId(),
controller.zoneRegistry().getConfigServerApiUris(deploymentId.zoneId()),
request.getUri());
response.setResponse(result, serviceName, restPath);
return response;
}
private HttpResponse updateTenant(String tenantName, HttpRequest request) {
getTenantOrThrow(tenantName);
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().update(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createTenant(String tenantName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().create(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest());
com.yahoo.vespa.hosted.controller.Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
if (controller.applications().getApplication(applicationId).isEmpty())
createApplication(tenantName, applicationName, request);
controller.applications().createInstance(applicationId.instance(instanceName));
Slime slime = new Slime();
toSlime(applicationId.instance(instanceName), slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
/** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */
private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) {
request = controller.auditLogger().log(request);
String versionString = readToString(request.getData());
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Version version = Version.fromString(versionString);
if (version.equals(Version.emptyVersion))
version = controller.systemVersion();
if ( ! systemHasVersion(version))
throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " +
"Version is not active in this system. " +
"Active versions: " + controller.versionStatus().versions()
.stream()
.map(VespaVersion::versionNumber)
.map(Version::toString)
.collect(joining(", ")));
Change change = Change.of(version);
if (pin)
change = change.withPin();
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Trigger deployment to the last known application package for the given application. */
private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) {
controller.auditLogger().log(request);
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */
private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = application.get().require(id.instance()).change();
if (change.isEmpty()) {
response.append("No deployment in progress for ").append(id).append(" at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Schedule restart of deployment, or specific host in a deployment */
private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Optional<Hostname> hostname = Optional.ofNullable(request.getProperty("hostname")).map(Hostname::new);
controller.applications().restart(deploymentId, hostname);
return new MessageResponse("Requested restart of " + deploymentId);
}
private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) {
if ( ! type.environment().isManuallyDeployed() && ! isOperator(request))
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("applicationZip"))
throw new IllegalArgumentException("Missing required form part 'applicationZip'");
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(id.tenant(),
Optional.of(id.instance()),
Optional.of(type.zone(controller.system())),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions"))
.map(json -> SlimeUtils.jsonToSlime(json).get())
.flatMap(options -> optional("vespaVersion", options))
.map(Version::fromString);
controller.jobController().deploy(id, type, version, applicationPackage);
RunId runId = controller.jobController().last(id, type).get().id();
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("message", "Deployment started in " + runId +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<com.yahoo.vespa.hosted.controller.Application> application = controller.applications().getApplication(TenantAndApplicationId.from(applicationId));
Inspector sourceRevision = deployOptions.field("sourceRevision");
Inspector buildNumber = deployOptions.field("buildNumber");
if (sourceRevision.valid() != buildNumber.valid())
throw new IllegalArgumentException("Source revision and build number must both be provided, or not");
Optional<ApplicationVersion> applicationVersion = Optional.empty();
if (sourceRevision.valid()) {
if (applicationPackage.isPresent())
throw new IllegalArgumentException("Application version and application package can't both be provided.");
applicationVersion = Optional.of(ApplicationVersion.from(toSourceRevision(sourceRevision),
buildNumber.asLong()));
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
boolean deployDirectly = deployOptions.field("deployDirectly").asBool();
Optional<Version> vespaVersion = optional("vespaVersion", deployOptions).map(Version::new);
if (deployDirectly && applicationPackage.isEmpty() && applicationVersion.isEmpty() && vespaVersion.isEmpty()) {
Optional<Deployment> deployment = controller.applications().getInstance(applicationId)
.map(Instance::deployments)
.flatMap(deployments -> Optional.ofNullable(deployments.get(zone)));
if(deployment.isEmpty())
throw new IllegalArgumentException("Can't redeploy application, no deployment currently exist");
ApplicationVersion version = deployment.get().applicationVersion();
if(version.isUnknown())
throw new IllegalArgumentException("Can't redeploy application, application version is unknown");
applicationVersion = Optional.of(version);
vespaVersion = Optional.of(deployment.get().version());
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
Optional.of(applicationId.instance()),
Optional.of(zone),
aPackage,
Optional.of(requireUserPrincipal(request))));
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass);
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if (tenant.isEmpty())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
controller.tenants().delete(tenant.get().name(),
accessControlRequests.credentials(tenant.get().name(),
toSlime(request.getData()).get(),
request.getJDiscRequest()));
return tenant(tenant.get(), request);
}
private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
return new MessageResponse("Deleted application " + id);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty()) {
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
}
return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
controller.applications().deactivate(id.applicationId(), id.zoneId());
return new MessageResponse("Deactivated " + id);
}
/** Returns test config for indicated job, with production deployments of the default instance. */
private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
HashSet<DeploymentId> deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toCollection(HashSet::new));
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.routing().zoneEndpointsOf(deployments),
controller.applications().contentClustersByZone(deployments)));
}
private static SourceRevision toSourceRevision(Inspector object) {
if (!object.field("repository").valid() ||
!object.field("branch").valid() ||
!object.field("commit").valid()) {
throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\".");
}
return new SourceRevision(object.field("repository").asString(),
object.field("branch").asString(),
object.field("commit").asString());
}
private Tenant getTenantOrThrow(String tenantName) {
return controller.tenants().get(tenantName)
.orElseThrow(() -> new NotExistsException(new TenantId(tenantName)));
}
private void toSlime(Cursor object, Tenant tenant, HttpRequest request) {
object.setString("tenant", tenant.name().value());
object.setString("type", tenantType(tenant));
List<com.yahoo.vespa.hosted.controller.Application> applications = controller.applications().asList(tenant.name());
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
object.setString("athensDomain", athenzTenant.domain().getName());
object.setString("property", athenzTenant.property().id());
athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString()));
athenzTenant.contact().ifPresent(c -> {
object.setString("propertyUrl", c.propertyUrl().toString());
object.setString("contactsUrl", c.url().toString());
object.setString("issueCreationUrl", c.issueTrackerUrl().toString());
Cursor contactsArray = object.setArray("contacts");
c.persons().forEach(persons -> {
Cursor personArray = contactsArray.addArray();
persons.forEach(personArray::addString);
});
});
break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys");
cloudTenant.developerKeys().forEach((key, user) -> {
Cursor keyObject = pemDeveloperKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", user.getName());
});
break;
}
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
Cursor applicationArray = object.setArray("applications");
for (com.yahoo.vespa.hosted.controller.Application application : applications) {
DeploymentStatus status = controller.jobController().deploymentStatus(application);
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, status, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
}
private void toSlime(ClusterResources resources, Cursor object) {
object.setLong("nodes", resources.nodes());
object.setLong("groups", resources.groups());
toSlime(resources.nodeResources(), object.setObject("nodeResources"));
if ( ! controller.zoneRegistry().system().isPublic())
object.setDouble("cost", Math.round(resources.nodes() * resources.nodeResources().cost() * 100.0 / 3.0) / 100.0);
}
private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", valueOf(resources.diskSpeed()));
object.setString("storageType", valueOf(resources.storageType()));
}
private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) {
object.setString("tenant", tenant.name().value());
Cursor metaData = object.setObject("metaData");
metaData.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
metaData.setString("athensDomain", athenzTenant.domain().getName());
metaData.setString("property", athenzTenant.property().id());
break;
case cloud: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString());
}
/** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */
private URI withPath(String newPath, URI uri) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, null, null);
}
catch (URISyntaxException e) {
throw new RuntimeException("Will not happen", e);
}
}
private long asLong(String valueOrNull, long defaultWhenNull) {
if (valueOrNull == null) return defaultWhenNull;
try {
return Long.parseLong(valueOrNull);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'");
}
}
private void toSlime(Run run, Cursor object) {
object.setLong("id", run.id().number());
object.setString("version", run.versions().targetPlatform().toFullString());
if ( ! run.versions().targetApplication().isUnknown())
toSlime(run.versions().targetApplication(), object.setObject("revision"));
object.setString("reason", "unknown reason");
object.setLong("at", run.end().orElse(run.start()).toEpochMilli());
}
private Slime toSlime(InputStream jsonStream) {
try {
byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000);
return SlimeUtils.jsonToSlime(jsonBytes);
} catch (IOException e) {
throw new RuntimeException();
}
}
private static Principal requireUserPrincipal(HttpRequest request) {
Principal principal = request.getJDiscRequest().getUserPrincipal();
if (principal == null) throw new InternalServerErrorException("Expected a user principal");
return principal;
}
private Inspector mandatory(String key, Inspector object) {
if ( ! object.field(key).valid())
throw new IllegalArgumentException("'" + key + "' is missing");
return object.field(key);
}
private Optional<String> optional(String key, Inspector object) {
return SlimeUtils.optionalString(object.field(key));
}
private static String path(Object... elements) {
return Joiner.on("/").join(elements);
}
private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value(),
request.getUri()).toString());
}
private void toSlime(ApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value() +
"/instance/" + id.instance().value(),
request.getUri()).toString());
}
private Slime toSlime(ActivateResult result) {
Slime slime = new Slime();
Cursor object = slime.setObject();
object.setString("revisionId", result.revisionId().id());
object.setLong("applicationZipSize", result.applicationZipSizeBytes());
Cursor logArray = object.setArray("prepareMessages");
if (result.prepareResponse().log != null) {
for (Log logMessage : result.prepareResponse().log) {
Cursor logObject = logArray.addObject();
logObject.setLong("time", logMessage.time);
logObject.setString("level", logMessage.level);
logObject.setString("message", logMessage.message);
}
}
Cursor changeObject = object.setObject("configChangeActions");
Cursor restartActionsArray = changeObject.setArray("restart");
for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) {
Cursor restartActionObject = restartActionsArray.addObject();
restartActionObject.setString("clusterName", restartAction.clusterName);
restartActionObject.setString("clusterType", restartAction.clusterType);
restartActionObject.setString("serviceType", restartAction.serviceType);
serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services"));
stringsToSlime(restartAction.messages, restartActionObject.setArray("messages"));
}
Cursor refeedActionsArray = changeObject.setArray("refeed");
for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) {
Cursor refeedActionObject = refeedActionsArray.addObject();
refeedActionObject.setString("name", refeedAction.name);
refeedActionObject.setBool("allowed", refeedAction.allowed);
refeedActionObject.setString("documentType", refeedAction.documentType);
refeedActionObject.setString("clusterName", refeedAction.clusterName);
serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services"));
stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages"));
}
return slime;
}
private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) {
for (ServiceInfo serviceInfo : serviceInfoList) {
Cursor serviceInfoObject = array.addObject();
serviceInfoObject.setString("serviceName", serviceInfo.serviceName);
serviceInfoObject.setString("serviceType", serviceInfo.serviceType);
serviceInfoObject.setString("configId", serviceInfo.configId);
serviceInfoObject.setString("hostName", serviceInfo.hostName);
}
}
private void stringsToSlime(List<String> strings, Cursor array) {
for (String string : strings)
array.addString(string);
}
private String readToString(InputStream stream) {
Scanner scanner = new Scanner(stream).useDelimiter("\\A");
if ( ! scanner.hasNext()) return null;
return scanner.next();
}
private boolean systemHasVersion(Version version) {
return controller.versionStatus().versions().stream().anyMatch(v -> v.versionNumber().equals(version));
}
private static boolean recurseOverTenants(HttpRequest request) {
return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive"));
}
private static boolean recurseOverApplications(HttpRequest request) {
return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive"));
}
private static boolean recurseOverDeployments(HttpRequest request) {
return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive"));
}
private static boolean showOnlyProductionInstances(HttpRequest request) {
return "true".equals(request.getProperty("production"));
}
private static String tenantType(Tenant tenant) {
switch (tenant.type()) {
case athenz: return "ATHENS";
case cloud: return "CLOUD";
default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName());
}
}
private static ApplicationId appIdFromPath(Path path) {
return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance"));
}
private static JobType jobTypeFromPath(Path path) {
return JobType.fromJobName(path.get("jobtype"));
}
private static RunId runIdFromPath(Path path) {
long number = Long.parseLong(path.get("number"));
return new RunId(appIdFromPath(path), jobTypeFromPath(path), number);
}
private HttpResponse submit(String tenant, String application, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
Optional<String> repository = optional("repository", submitOptions);
Optional<String> branch = optional("branch", submitOptions);
Optional<String> commit = optional("commit", submitOptions);
Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent()
? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get()))
: Optional.empty();
Optional<String> sourceUrl = optional("sourceUrl", submitOptions);
Optional<String> authorEmail = optional("authorEmail", submitOptions);
sourceUrl.map(URI::create).ifPresent(url -> {
if (url.getHost() == null || url.getScheme() == null)
throw new IllegalArgumentException("Source URL must include scheme and host");
});
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true);
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
Optional.empty(),
Optional.empty(),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
sourceUrl,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
private HttpResponse removeProdAllDeployments(String tenant, String application) {
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application,
Optional.empty(), Optional.empty(), Optional.empty(), 1,
ApplicationPackage.createEmptyForDeploymentRemoval(), new byte[0]);
}
private static Map<String, byte[]> parseDataParts(HttpRequest request) {
String contentHash = request.getHeader("x-Content-Hash");
if (contentHash == null)
return new MultipartParser().parse(request);
DigestInputStream digester = Signatures.sha256Digester(request.getData());
var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri());
if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash)))
throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash");
return dataParts;
}
private static RotationId findRotationId(Instance instance, Optional<String> endpointId) {
if (instance.rotations().isEmpty()) {
throw new NotExistsException("global rotation does not exist for " + instance);
}
if (endpointId.isPresent()) {
return instance.rotations().stream()
.filter(r -> r.endpointId().id().equals(endpointId.get()))
.map(AssignedRotation::rotationId)
.findFirst()
.orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() +
" does not exist for " + instance));
} else if (instance.rotations().size() > 1) {
throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given");
}
return instance.rotations().get(0).rotationId();
}
private static String rotationStateString(RotationState state) {
switch (state) {
case in: return "IN";
case out: return "OUT";
}
return "UNKNOWN";
}
private static String endpointScopeString(Endpoint.Scope scope) {
switch (scope) {
case global: return "global";
case zone: return "zone";
}
throw new IllegalArgumentException("Unknown endpoint scope " + scope);
}
private static String routingMethodString(RoutingMethod method) {
switch (method) {
case exclusive: return "exclusive";
case shared: return "shared";
case sharedLayer4: return "sharedLayer4";
}
throw new IllegalArgumentException("Unknown routing method " + method);
}
private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) {
return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName))
.filter(cls::isInstance)
.map(cls::cast)
.orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request"));
}
/** Returns whether given request is by an operator */
private static boolean isOperator(HttpRequest request) {
var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class);
return securityContext.roles().stream()
.map(Role::definition)
.anyMatch(definition -> definition == RoleDefinition.hostedOperator);
}
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestConfigSerializer testConfigSerializer;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
}
@Override
public Duration getTimeout() {
return Duration.ofMinutes(20);
}
@Override
public HttpResponse handle(HttpRequest request) {
try {
Path path = new Path(request.getUri(), OPTIONAL_PREFIX);
switch (request.getMethod()) {
case GET: return handleGET(path, request);
case PUT: return handlePUT(path, request);
case POST: return handlePOST(path, request);
case PATCH: return handlePATCH(path, request);
case DELETE: return handleDELETE(path, request);
case OPTIONS: return handleOPTIONS();
default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
}
}
catch (ForbiddenException e) {
return ErrorResponse.forbidden(Exceptions.toMessageString(e));
}
catch (NotAuthorizedException e) {
return ErrorResponse.unauthorized(Exceptions.toMessageString(e));
}
catch (NotExistsException e) {
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
}
catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
catch (ConfigServerException e) {
switch (e.getErrorCode()) {
case NOT_FOUND:
return new ErrorResponse(NOT_FOUND, e.getErrorCode().name(), Exceptions.toMessageString(e));
case ACTIVATION_CONFLICT:
return new ErrorResponse(CONFLICT, e.getErrorCode().name(), Exceptions.toMessageString(e));
case INTERNAL_SERVER_ERROR:
return new ErrorResponse(INTERNAL_SERVER_ERROR, e.getErrorCode().name(), Exceptions.toMessageString(e));
default:
return new ErrorResponse(BAD_REQUEST, e.getErrorCode().name(), Exceptions.toMessageString(e));
}
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/tenant")) return tenants(request);
if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePUT(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePATCH(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleOPTIONS() {
EmptyResponse response = new EmptyResponse();
response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS");
return response;
}
private HttpResponse recursiveRoot(HttpRequest request) {
Slime slime = new Slime();
Cursor tenantArray = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
toSlime(tenantArray.addObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse root(HttpRequest request) {
return recurseOverTenants(request)
? recursiveRoot(request)
: new ResourceResponse(request, "tenant");
}
private HttpResponse tenants(HttpRequest request) {
Slime slime = new Slime();
Cursor response = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject());
return new SlimeJsonResponse(slime);
}
private HttpResponse tenant(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenant(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenant(Tenant tenant, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
if (controller.tenants().get(tenantName).isEmpty())
return ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist");
Slime slime = new Slime();
Cursor applicationArray = slime.setArray();
for (com.yahoo.vespa.hosted.controller.Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true)) {
Cursor applicationObject = applicationArray.addObject();
applicationObject.setString("tenant", application.id().tenant().value());
applicationObject.setString("application", application.id().application().value());
applicationObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value(),
request.getUri()).toString());
Cursor instanceArray = applicationObject.setArray("instances");
for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet()
: application.instances().keySet()) {
Cursor instanceObject = instanceArray.addObject();
instanceObject.setString("instance", instance.value());
instanceObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/instance/" + instance.value(),
request.getUri()).toString());
}
}
}
return new SlimeJsonResponse(slime);
}
private HttpResponse devApplicationPackage(ApplicationId id, JobType type) {
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Only manually deployed zones have dev packages");
ZoneId zone = type.zone(controller.system());
byte[] applicationPackage = controller.applications().applicationStore().getDev(id, zone);
return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage);
}
private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse compileVersion(String tenantName, String applicationName) {
Slime slime = new Slime();
slime.setObject().setString("compileVersion",
compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString());
return new SlimeJsonResponse(slime);
}
private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
Principal user = request.getJDiscRequest().getUserPrincipal();
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withDeveloperKey(developerKey, user);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Principal user = ((CloudTenant) controller.tenants().require(TenantName.from(tenantName))).developerKeys().get(developerKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withoutDeveloperKey(developerKey);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) {
keys.forEach((key, principal) -> {
Cursor keyObject = keysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", principal.getName());
});
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withoutDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes.");
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
Inspector majorVersionField = requestObject.field("majorVersion");
if (majorVersionField.valid()) {
Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong();
application = application.withMajorVersion(majorVersion);
messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion));
}
Inspector pemDeployKeyField = requestObject.field("pemDeployKey");
if (pemDeployKeyField.valid()) {
String pemDeployKey = pemDeployKeyField.asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
application = application.withDeployKey(deployKey);
messageBuilder.add("Added deploy key " + pemDeployKey);
}
controller.applications().store(application);
});
return new MessageResponse(messageBuilder.toString());
}
private com.yahoo.vespa.hosted.controller.Application getApplication(String tenantName, String applicationName) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
return controller.applications().getApplication(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private Instance getInstance(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
return controller.applications().getInstance(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, id);
Slime slime = new Slime();
Cursor nodesArray = slime.setObject().setArray("nodes");
for (Node node : nodes) {
Cursor nodeObject = nodesArray.addObject();
nodeObject.setString("hostname", node.hostname().value());
nodeObject.setString("state", valueOf(node.state()));
node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.flavor());
toSlime(node.resources(), nodeObject);
nodeObject.setBool("fastDisk", node.resources().diskSpeed() == NodeResources.DiskSpeed.fast);
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
return new SlimeJsonResponse(slime);
}
private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id);
Slime slime = new Slime();
Cursor clustersObject = slime.setObject().setObject("clusters");
for (Cluster cluster : application.clusters().values()) {
Cursor clusterObject = clustersObject.setObject(cluster.id().value());
toSlime(cluster.min(), clusterObject.setObject("min"));
toSlime(cluster.max(), clusterObject.setObject("max"));
toSlime(cluster.current(), clusterObject.setObject("current"));
cluster.target().ifPresent(target -> toSlime(target, clusterObject.setObject("target")));
cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested")));
}
return new SlimeJsonResponse(slime);
}
private static String valueOf(Node.State state) {
switch (state) {
case failed: return "failed";
case parked: return "parked";
case dirty: return "dirty";
case ready: return "ready";
case active: return "active";
case inactive: return "inactive";
case reserved: return "reserved";
case provisioned: return "provisioned";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ServiceState state) {
switch (state) {
case expectedUp: return "expectedUp";
case allowedDown: return "allowedDown";
case unorchestrated: return "unorchestrated";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ClusterType type) {
switch (type) {
case admin: return "admin";
case content: return "content";
case container: return "container";
case combined: return "combined";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
private static String valueOf(NodeResources.DiskSpeed diskSpeed) {
switch (diskSpeed) {
case fast : return "fast";
case slow : return "slow";
case any : return "any";
default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'");
}
}
private static String valueOf(NodeResources.StorageType storageType) {
switch (storageType) {
case remote : return "remote";
case local : return "local";
case any : return "any";
default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'");
}
}
private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters);
return new HttpResponse(200) {
@Override
public void render(OutputStream outputStream) throws IOException {
logStream.transferTo(outputStream);
}
};
}
private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
boolean requireTests = ! requestObject.field("skipTests").asBool();
boolean reTrigger = requestObject.field("reTrigger").asBool();
String triggered = reTrigger
? controller.applications().deploymentTrigger()
.reTrigger(id, type).type().jobName()
: controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests)
.stream().map(job -> job.type().jobName()).collect(joining(", "));
return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered"
: "Triggered " + triggered + " for " + id);
}
private HttpResponse pause(ApplicationId id, JobType type) {
Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause);
controller.applications().deploymentTrigger().pauseJob(id, type, until);
return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause);
}
private HttpResponse resume(ApplicationId id, JobType type) {
controller.applications().deploymentTrigger().resumeJob(id, type);
return new MessageResponse(type.jobName() + " for " + id + " resumed");
}
private void toSlime(Cursor object, com.yahoo.vespa.hosted.controller.Application application, HttpRequest request) {
object.setString("tenant", application.id().tenant().value());
object.setString("application", application.id().application().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/job/",
request.getUri()).toString());
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
application.instances().values().stream().findFirst().ifPresent(instance -> {
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
});
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request);
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
if (deploymentSpec.instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec.requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
globalEndpointsToSlime(object, instance);
List<Deployment> deployments = deploymentSpec.instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor deploymentsArray = object.setArray("deployments");
for (Deployment deployment : deployments) {
Cursor deploymentObject = deploymentsArray.addObject();
if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty())
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/instance/" + instance.name().value() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
}
private void globalEndpointsToSlime(Cursor object, Instance instance) {
var globalEndpointUrls = new LinkedHashSet<String>();
controller.routing().endpointsOf(instance.id())
.requiresRotation()
.not().legacy()
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalEndpointUrls::add);
var globalRotationsArray = object.setArray("globalRotations");
globalEndpointUrls.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
}
private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) {
com.yahoo.vespa.hosted.controller.Application application = status.application();
object.setString("tenant", instance.id().tenant().value());
object.setString("application", instance.id().application().value());
object.setString("instance", instance.id().instance().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + instance.id().tenant().value() +
"/application/" + instance.id().application().value() +
"/instance/" + instance.id().instance().value() + "/job/",
request.getUri()).toString());
application.latestVersion().ifPresent(version -> {
sourceRevisionToSlime(version.source(), object.setObject("source"));
version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
version.commit().ifPresent(commit -> object.setString("commit", commit));
});
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if (application.deploymentSpec().instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec().requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
globalEndpointsToSlime(object, instance);
List<Deployment> deployments =
application.deploymentSpec().instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor instancesArray = object.setArray("instances");
for (Deployment deployment : deployments) {
Cursor deploymentObject = instancesArray.addObject();
if (deployment.zone().environment() == Environment.prod) {
if (instance.rotations().size() == 1) {
toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment),
deploymentObject);
}
if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) {
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
}
}
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("instance", instance.id().instance().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
status.jobSteps().keySet().stream()
.filter(job -> job.application().instance().equals(instance.name()))
.filter(job -> job.type().isProduction() && job.type().isDeployment())
.map(job -> job.type().zone(controller.system()))
.filter(zone -> ! instance.deployments().containsKey(zone))
.forEach(zone -> {
Cursor deploymentObject = instancesArray.addObject();
deploymentObject.setString("environment", zone.environment().value());
deploymentObject.setString("region", zone.region().value());
});
application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key)));
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().getInstance(id)
.orElseThrow(() -> new NotExistsException(id + " not found"));
DeploymentId deploymentId = new DeploymentId(instance.id(),
ZoneId.from(environment, region));
Deployment deployment = instance.deployments().get(deploymentId.zoneId());
if (deployment == null)
throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId());
Slime slime = new Slime();
toSlime(slime.setObject(), deploymentId, deployment, request);
return new SlimeJsonResponse(slime);
}
private void toSlime(Cursor object, Change change) {
change.platform().ifPresent(version -> object.setString("version", version.toString()));
change.application()
.filter(version -> !version.isUnknown())
.ifPresent(version -> toSlime(version, object.setObject("revision")));
}
private void toSlime(Endpoint endpoint, String cluster, Cursor object) {
object.setString("cluster", cluster);
object.setBool("tls", endpoint.tls());
object.setString("url", endpoint.url().toString());
object.setString("scope", endpointScopeString(endpoint.scope()));
object.setString("routingMethod", routingMethodString(endpoint.routingMethod()));
}
private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) {
response.setString("tenant", deploymentId.applicationId().tenant().value());
response.setString("application", deploymentId.applicationId().application().value());
response.setString("instance", deploymentId.applicationId().instance().value());
response.setString("environment", deploymentId.zoneId().environment().value());
response.setString("region", deploymentId.zoneId().region().value());
var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId()));
var endpointArray = response.setArray("endpoints");
for (var endpoint : controller.routing().endpointsOf(deploymentId)
.scope(Endpoint.Scope.zone)
.not().legacy()) {
toSlime(endpoint, endpoint.name(), endpointArray.addObject());
}
var globalEndpoints = controller.routing().endpointsOf(application, deploymentId.applicationId().instance())
.not().legacy()
.targets(deploymentId.zoneId());
for (var endpoint : globalEndpoints) {
toSlime(endpoint, endpoint.cluster().value(), endpointArray.addObject());
}
response.setString("nodes", withPath("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/?&recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString());
response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString());
response.setString("version", deployment.version().toFullString());
response.setString("revision", deployment.applicationVersion().id());
response.setLong("deployTimeEpochMs", deployment.at().toEpochMilli());
controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId())
.ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", deployment.at().plus(deploymentTimeToLive).toEpochMilli()));
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
var instance = application.instances().get(deploymentId.applicationId().instance());
if (instance != null) {
if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod)
toSlime(instance.rotations(), instance.rotationStatus(), deployment, response);
JobType.from(controller.system(), deployment.zone())
.map(type -> new JobId(instance.id(), type))
.map(status.jobSteps()::get)
.ifPresent(stepStatus -> {
JobControllerApiHandlerHelper.applicationVersionToSlime(
response.setObject("applicationVersion"), deployment.applicationVersion());
if (!status.jobsToRun().containsKey(stepStatus.job().get()))
response.setString("status", "complete");
else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true))
response.setString("status", "pending");
else response.setString("status", "running");
});
}
Cursor activity = response.setObject("activity");
deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried",
instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten",
instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
DeploymentMetrics metrics = deployment.metrics();
Cursor metricsObject = response.setObject("metrics");
metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond());
metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond());
metricsObject.setDouble("documentCount", metrics.documentCount());
metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis());
metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli()));
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if ( ! applicationVersion.isUnknown()) {
object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong());
object.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if (revision.isEmpty()) return;
object.setString("gitRepository", revision.get().repository());
object.setString("gitBranch", revision.get().branch());
object.setString("gitCommit", revision.get().commit());
}
private void toSlime(RotationState state, Cursor object) {
Cursor bcpStatus = object.setObject("bcpStatus");
bcpStatus.setString("rotationStatus", rotationStateString(state));
}
private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) {
var array = object.setArray("endpointStatus");
for (var rotation : rotations) {
var statusObject = array.addObject();
var targets = status.of(rotation.rotationId());
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("rotationId", rotation.rotationId().asString());
statusObject.setString("clusterId", rotation.clusterId().value());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli());
}
}
private URI monitoringSystemUri(DeploymentId deploymentId) {
return controller.zoneRegistry().getMonitoringSystemUri(deploymentId);
}
/**
* Returns a non-broken, released version at least as old as the oldest platform the given application is on.
*
* If no known version is applicable, the newest version at least as old as the oldest platform is selected,
* among all versions released for this system. If no such versions exists, throws an IllegalStateException.
*/
private Version compileVersion(TenantAndApplicationId id) {
Version oldestPlatform = controller.applications().oldestInstalledPlatform(id);
VersionStatus versionStatus = controller.versionStatus();
return versionStatus.versions().stream()
.filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low))
.filter(VespaVersion::isReleased)
.map(VespaVersion::versionNumber)
.filter(version -> ! version.isAfter(oldestPlatform))
.max(Comparator.naturalOrder())
.orElseGet(() -> controller.mavenRepository().metadata().versions().stream()
.filter(version -> ! version.isAfter(oldestPlatform))
.filter(version -> ! versionStatus.versions().stream()
.map(VespaVersion::versionNumber)
.collect(Collectors.toSet()).contains(version))
.max(Comparator.naturalOrder())
.orElseThrow(() -> new IllegalStateException("No available releases of " +
controller.mavenRepository().artifactId())));
}
private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
ZoneId zone = ZoneId.from(environment, region);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
var deploymentId = new DeploymentId(instance.id(), zone);
setGlobalRotationStatus(deploymentId, inService, request);
setGlobalEndpointStatus(deploymentId, inService, request);
return new MessageResponse(String.format("Successfully set %s in %s %s service",
instance.id().toShortString(), zone, inService ? "in" : "out of"));
}
/** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */
private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
var status = inService ? GlobalRouting.Status.in : GlobalRouting.Status.out;
controller.routing().policies().setGlobalRoutingStatus(deployment, status, agent);
}
/** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */
private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var requestData = toSlime(request.getData()).get();
var reason = mandatory("reason", requestData).asString();
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
long timestamp = controller.clock().instant().getEpochSecond();
var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp);
controller.routing().setGlobalRotationStatus(deployment, endpointStatus);
}
private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Slime slime = new Slime();
Cursor array = slime.setObject().setArray("globalrotationoverride");
controller.routing().globalRotationStatus(deploymentId)
.forEach((endpoint, status) -> {
array.addString(endpoint.upstreamIdOf(deploymentId));
Cursor statusObject = array.addObject();
statusObject.setString("status", status.getStatus().name());
statusObject.setString("reason", status.getReason() == null ? "" : status.getReason());
statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent());
statusObject.setLong("timestamp", status.getEpoch());
});
return new SlimeJsonResponse(slime);
}
private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().requireInstance(applicationId);
ZoneId zone = ZoneId.from(environment, region);
RotationId rotation = findRotationId(instance, endpointId);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
Slime slime = new Slime();
Cursor response = slime.setObject();
toSlime(instance.rotationStatus().of(rotation, deployment), response);
return new SlimeJsonResponse(slime);
}
private HttpResponse metering(String tenant, String application, HttpRequest request) {
Slime slime = new Slime();
Cursor root = slime.setObject();
MeteringData meteringData = controller.serviceRegistry()
.meteringService()
.getMeteringData(TenantName.from(tenant), ApplicationName.from(application));
ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringData.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringData.getLastMonth();
Cursor lastmonth = root.setObject("lastmonth");
lastmonth.setDouble("cpu", lastMonth.getCpuCores());
lastmonth.setDouble("mem", lastMonth.getMemoryGb());
lastmonth.setDouble("disk", lastMonth.getDiskGb());
Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory();
Cursor details = root.setObject("details");
Cursor detailsCpu = details.setObject("cpu");
Cursor detailsMem = details.setObject("mem");
Cursor detailsDisk = details.setObject("disk");
history.entrySet().stream()
.forEach(entry -> {
String instanceName = entry.getKey().instance().value();
Cursor detailsCpuApp = detailsCpu.setObject(instanceName);
Cursor detailsMemApp = detailsMem.setObject(instanceName);
Cursor detailsDiskApp = detailsDisk.setObject(instanceName);
Cursor detailsCpuData = detailsCpuApp.setArray("data");
Cursor detailsMemData = detailsMemApp.setArray("data");
Cursor detailsDiskData = detailsDiskApp.setArray("data");
entry.getValue().stream()
.forEach(resourceSnapshot -> {
Cursor cpu = detailsCpuData.addObject();
cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
cpu.setDouble("value", resourceSnapshot.getCpuCores());
Cursor mem = detailsMemData.addObject();
mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
mem.setDouble("value", resourceSnapshot.getMemoryGb());
Cursor disk = detailsDiskData.addObject();
disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
disk.setDouble("value", resourceSnapshot.getDiskGb());
});
});
return new SlimeJsonResponse(slime);
}
private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! instance.change().isEmpty()) {
instance.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", instance.change().isPinned());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
boolean suspended = controller.applications().isSuspended(deploymentId);
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setBool("suspended", suspended);
return new SlimeJsonResponse(slime);
}
private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region);
ServiceApiResponse response = new ServiceApiResponse(ZoneId.from(environment, region),
new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(),
controller.zoneRegistry().getConfigServerApiUris(ZoneId.from(environment, region)),
request.getUri());
response.setResponse(applicationView);
return response;
}
private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), ZoneId.from(environment, region));
if ("container-clustercontroller".equals((serviceName)) && restPath.contains("/status/")) {
String result = controller.serviceRegistry().configServer().getClusterControllerStatus(deploymentId, restPath);
return new HtmlResponse(result);
}
Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath);
ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(),
deploymentId.applicationId(),
controller.zoneRegistry().getConfigServerApiUris(deploymentId.zoneId()),
request.getUri());
response.setResponse(result, serviceName, restPath);
return response;
}
private HttpResponse updateTenant(String tenantName, HttpRequest request) {
getTenantOrThrow(tenantName);
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().update(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createTenant(String tenantName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().create(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest());
com.yahoo.vespa.hosted.controller.Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
if (controller.applications().getApplication(applicationId).isEmpty())
createApplication(tenantName, applicationName, request);
controller.applications().createInstance(applicationId.instance(instanceName));
Slime slime = new Slime();
toSlime(applicationId.instance(instanceName), slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
/** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */
private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) {
request = controller.auditLogger().log(request);
String versionString = readToString(request.getData());
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Version version = Version.fromString(versionString);
if (version.equals(Version.emptyVersion))
version = controller.systemVersion();
if ( ! systemHasVersion(version))
throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " +
"Version is not active in this system. " +
"Active versions: " + controller.versionStatus().versions()
.stream()
.map(VespaVersion::versionNumber)
.map(Version::toString)
.collect(joining(", ")));
Change change = Change.of(version);
if (pin)
change = change.withPin();
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Trigger deployment to the last known application package for the given application. */
private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) {
controller.auditLogger().log(request);
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */
private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = application.get().require(id.instance()).change();
if (change.isEmpty()) {
response.append("No deployment in progress for ").append(id).append(" at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Schedule restart of deployment, or specific host in a deployment */
private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Optional<Hostname> hostname = Optional.ofNullable(request.getProperty("hostname")).map(Hostname::new);
controller.applications().restart(deploymentId, hostname);
return new MessageResponse("Requested restart of " + deploymentId);
}
private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) {
if ( ! type.environment().isManuallyDeployed() && ! isOperator(request))
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("applicationZip"))
throw new IllegalArgumentException("Missing required form part 'applicationZip'");
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(id.tenant(),
Optional.of(id.instance()),
Optional.of(type.zone(controller.system())),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions"))
.map(json -> SlimeUtils.jsonToSlime(json).get())
.flatMap(options -> optional("vespaVersion", options))
.map(Version::fromString);
controller.jobController().deploy(id, type, version, applicationPackage);
RunId runId = controller.jobController().last(id, type).get().id();
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("message", "Deployment started in " + runId +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<com.yahoo.vespa.hosted.controller.Application> application = controller.applications().getApplication(TenantAndApplicationId.from(applicationId));
Inspector sourceRevision = deployOptions.field("sourceRevision");
Inspector buildNumber = deployOptions.field("buildNumber");
if (sourceRevision.valid() != buildNumber.valid())
throw new IllegalArgumentException("Source revision and build number must both be provided, or not");
Optional<ApplicationVersion> applicationVersion = Optional.empty();
if (sourceRevision.valid()) {
if (applicationPackage.isPresent())
throw new IllegalArgumentException("Application version and application package can't both be provided.");
applicationVersion = Optional.of(ApplicationVersion.from(toSourceRevision(sourceRevision),
buildNumber.asLong()));
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
boolean deployDirectly = deployOptions.field("deployDirectly").asBool();
Optional<Version> vespaVersion = optional("vespaVersion", deployOptions).map(Version::new);
if (deployDirectly && applicationPackage.isEmpty() && applicationVersion.isEmpty() && vespaVersion.isEmpty()) {
Optional<Deployment> deployment = controller.applications().getInstance(applicationId)
.map(Instance::deployments)
.flatMap(deployments -> Optional.ofNullable(deployments.get(zone)));
if(deployment.isEmpty())
throw new IllegalArgumentException("Can't redeploy application, no deployment currently exist");
ApplicationVersion version = deployment.get().applicationVersion();
if(version.isUnknown())
throw new IllegalArgumentException("Can't redeploy application, application version is unknown");
applicationVersion = Optional.of(version);
vespaVersion = Optional.of(deployment.get().version());
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
Optional.of(applicationId.instance()),
Optional.of(zone),
aPackage,
Optional.of(requireUserPrincipal(request))));
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass);
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if (tenant.isEmpty())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
controller.tenants().delete(tenant.get().name(),
accessControlRequests.credentials(tenant.get().name(),
toSlime(request.getData()).get(),
request.getJDiscRequest()));
return tenant(tenant.get(), request);
}
private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
return new MessageResponse("Deleted application " + id);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty()) {
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
}
return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
controller.applications().deactivate(id.applicationId(), id.zoneId());
return new MessageResponse("Deactivated " + id);
}
/** Returns test config for indicated job, with production deployments of the default instance. */
private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
HashSet<DeploymentId> deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toCollection(HashSet::new));
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.routing().zoneEndpointsOf(deployments),
controller.applications().contentClustersByZone(deployments)));
}
private static SourceRevision toSourceRevision(Inspector object) {
if (!object.field("repository").valid() ||
!object.field("branch").valid() ||
!object.field("commit").valid()) {
throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\".");
}
return new SourceRevision(object.field("repository").asString(),
object.field("branch").asString(),
object.field("commit").asString());
}
private Tenant getTenantOrThrow(String tenantName) {
return controller.tenants().get(tenantName)
.orElseThrow(() -> new NotExistsException(new TenantId(tenantName)));
}
private void toSlime(Cursor object, Tenant tenant, HttpRequest request) {
object.setString("tenant", tenant.name().value());
object.setString("type", tenantType(tenant));
List<com.yahoo.vespa.hosted.controller.Application> applications = controller.applications().asList(tenant.name());
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
object.setString("athensDomain", athenzTenant.domain().getName());
object.setString("property", athenzTenant.property().id());
athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString()));
athenzTenant.contact().ifPresent(c -> {
object.setString("propertyUrl", c.propertyUrl().toString());
object.setString("contactsUrl", c.url().toString());
object.setString("issueCreationUrl", c.issueTrackerUrl().toString());
Cursor contactsArray = object.setArray("contacts");
c.persons().forEach(persons -> {
Cursor personArray = contactsArray.addArray();
persons.forEach(personArray::addString);
});
});
break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys");
cloudTenant.developerKeys().forEach((key, user) -> {
Cursor keyObject = pemDeveloperKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", user.getName());
});
break;
}
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
Cursor applicationArray = object.setArray("applications");
for (com.yahoo.vespa.hosted.controller.Application application : applications) {
DeploymentStatus status = controller.jobController().deploymentStatus(application);
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, status, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
}
private void toSlime(ClusterResources resources, Cursor object) {
object.setLong("nodes", resources.nodes());
object.setLong("groups", resources.groups());
toSlime(resources.nodeResources(), object.setObject("nodeResources"));
if ( ! controller.zoneRegistry().system().isPublic())
object.setDouble("cost", Math.round(resources.nodes() * resources.nodeResources().cost() * 100.0 / 3.0) / 100.0);
}
private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", valueOf(resources.diskSpeed()));
object.setString("storageType", valueOf(resources.storageType()));
}
private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) {
object.setString("tenant", tenant.name().value());
Cursor metaData = object.setObject("metaData");
metaData.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
metaData.setString("athensDomain", athenzTenant.domain().getName());
metaData.setString("property", athenzTenant.property().id());
break;
case cloud: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString());
}
/** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */
private URI withPath(String newPath, URI uri) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, null, null);
}
catch (URISyntaxException e) {
throw new RuntimeException("Will not happen", e);
}
}
private long asLong(String valueOrNull, long defaultWhenNull) {
if (valueOrNull == null) return defaultWhenNull;
try {
return Long.parseLong(valueOrNull);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'");
}
}
private void toSlime(Run run, Cursor object) {
object.setLong("id", run.id().number());
object.setString("version", run.versions().targetPlatform().toFullString());
if ( ! run.versions().targetApplication().isUnknown())
toSlime(run.versions().targetApplication(), object.setObject("revision"));
object.setString("reason", "unknown reason");
object.setLong("at", run.end().orElse(run.start()).toEpochMilli());
}
private Slime toSlime(InputStream jsonStream) {
try {
byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000);
return SlimeUtils.jsonToSlime(jsonBytes);
} catch (IOException e) {
throw new RuntimeException();
}
}
private static Principal requireUserPrincipal(HttpRequest request) {
Principal principal = request.getJDiscRequest().getUserPrincipal();
if (principal == null) throw new InternalServerErrorException("Expected a user principal");
return principal;
}
private Inspector mandatory(String key, Inspector object) {
if ( ! object.field(key).valid())
throw new IllegalArgumentException("'" + key + "' is missing");
return object.field(key);
}
private Optional<String> optional(String key, Inspector object) {
return SlimeUtils.optionalString(object.field(key));
}
private static String path(Object... elements) {
return Joiner.on("/").join(elements);
}
private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value(),
request.getUri()).toString());
}
private void toSlime(ApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value() +
"/instance/" + id.instance().value(),
request.getUri()).toString());
}
private Slime toSlime(ActivateResult result) {
Slime slime = new Slime();
Cursor object = slime.setObject();
object.setString("revisionId", result.revisionId().id());
object.setLong("applicationZipSize", result.applicationZipSizeBytes());
Cursor logArray = object.setArray("prepareMessages");
if (result.prepareResponse().log != null) {
for (Log logMessage : result.prepareResponse().log) {
Cursor logObject = logArray.addObject();
logObject.setLong("time", logMessage.time);
logObject.setString("level", logMessage.level);
logObject.setString("message", logMessage.message);
}
}
Cursor changeObject = object.setObject("configChangeActions");
Cursor restartActionsArray = changeObject.setArray("restart");
for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) {
Cursor restartActionObject = restartActionsArray.addObject();
restartActionObject.setString("clusterName", restartAction.clusterName);
restartActionObject.setString("clusterType", restartAction.clusterType);
restartActionObject.setString("serviceType", restartAction.serviceType);
serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services"));
stringsToSlime(restartAction.messages, restartActionObject.setArray("messages"));
}
Cursor refeedActionsArray = changeObject.setArray("refeed");
for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) {
Cursor refeedActionObject = refeedActionsArray.addObject();
refeedActionObject.setString("name", refeedAction.name);
refeedActionObject.setBool("allowed", refeedAction.allowed);
refeedActionObject.setString("documentType", refeedAction.documentType);
refeedActionObject.setString("clusterName", refeedAction.clusterName);
serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services"));
stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages"));
}
return slime;
}
private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) {
for (ServiceInfo serviceInfo : serviceInfoList) {
Cursor serviceInfoObject = array.addObject();
serviceInfoObject.setString("serviceName", serviceInfo.serviceName);
serviceInfoObject.setString("serviceType", serviceInfo.serviceType);
serviceInfoObject.setString("configId", serviceInfo.configId);
serviceInfoObject.setString("hostName", serviceInfo.hostName);
}
}
private void stringsToSlime(List<String> strings, Cursor array) {
for (String string : strings)
array.addString(string);
}
private String readToString(InputStream stream) {
Scanner scanner = new Scanner(stream).useDelimiter("\\A");
if ( ! scanner.hasNext()) return null;
return scanner.next();
}
private boolean systemHasVersion(Version version) {
return controller.versionStatus().versions().stream().anyMatch(v -> v.versionNumber().equals(version));
}
private static boolean recurseOverTenants(HttpRequest request) {
return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive"));
}
private static boolean recurseOverApplications(HttpRequest request) {
return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive"));
}
private static boolean recurseOverDeployments(HttpRequest request) {
return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive"));
}
private static boolean showOnlyProductionInstances(HttpRequest request) {
return "true".equals(request.getProperty("production"));
}
private static String tenantType(Tenant tenant) {
switch (tenant.type()) {
case athenz: return "ATHENS";
case cloud: return "CLOUD";
default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName());
}
}
private static ApplicationId appIdFromPath(Path path) {
return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance"));
}
private static JobType jobTypeFromPath(Path path) {
return JobType.fromJobName(path.get("jobtype"));
}
private static RunId runIdFromPath(Path path) {
long number = Long.parseLong(path.get("number"));
return new RunId(appIdFromPath(path), jobTypeFromPath(path), number);
}
private HttpResponse submit(String tenant, String application, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
Optional<String> repository = optional("repository", submitOptions);
Optional<String> branch = optional("branch", submitOptions);
Optional<String> commit = optional("commit", submitOptions);
Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent()
? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get()))
: Optional.empty();
Optional<String> sourceUrl = optional("sourceUrl", submitOptions);
Optional<String> authorEmail = optional("authorEmail", submitOptions);
sourceUrl.map(URI::create).ifPresent(url -> {
if (url.getHost() == null || url.getScheme() == null)
throw new IllegalArgumentException("Source URL must include scheme and host");
});
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true);
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
Optional.empty(),
Optional.empty(),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
sourceUrl,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
private HttpResponse removeAllProdDeployments(String tenant, String application) {
JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application,
Optional.empty(), Optional.empty(), Optional.empty(), 1,
ApplicationPackage.deploymentRemoval(), new byte[0]);
return new MessageResponse("All deployments removed");
}
private static Map<String, byte[]> parseDataParts(HttpRequest request) {
String contentHash = request.getHeader("x-Content-Hash");
if (contentHash == null)
return new MultipartParser().parse(request);
DigestInputStream digester = Signatures.sha256Digester(request.getData());
var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri());
if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash)))
throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash");
return dataParts;
}
private static RotationId findRotationId(Instance instance, Optional<String> endpointId) {
if (instance.rotations().isEmpty()) {
throw new NotExistsException("global rotation does not exist for " + instance);
}
if (endpointId.isPresent()) {
return instance.rotations().stream()
.filter(r -> r.endpointId().id().equals(endpointId.get()))
.map(AssignedRotation::rotationId)
.findFirst()
.orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() +
" does not exist for " + instance));
} else if (instance.rotations().size() > 1) {
throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given");
}
return instance.rotations().get(0).rotationId();
}
private static String rotationStateString(RotationState state) {
switch (state) {
case in: return "IN";
case out: return "OUT";
}
return "UNKNOWN";
}
private static String endpointScopeString(Endpoint.Scope scope) {
switch (scope) {
case global: return "global";
case zone: return "zone";
}
throw new IllegalArgumentException("Unknown endpoint scope " + scope);
}
private static String routingMethodString(RoutingMethod method) {
switch (method) {
case exclusive: return "exclusive";
case shared: return "shared";
case sharedLayer4: return "sharedLayer4";
}
throw new IllegalArgumentException("Unknown routing method " + method);
}
private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) {
return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName))
.filter(cls::isInstance)
.map(cls::cast)
.orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request"));
}
/** Returns whether given request is by an operator */
private static boolean isOperator(HttpRequest request) {
var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class);
return securityContext.roles().stream()
.map(Role::definition)
.anyMatch(definition -> definition == RoleDefinition.hostedOperator);
}
} |
Would be better if this said what happened (i.e. "all deployments removed"), but not important. | public void testRemovingAllDeployments() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 432L);
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
tester.controller().jobController().deploy(app.instanceId(), JobType.devUsEast1, Optional.empty(), applicationPackage);
assertEquals(Set.of(ZoneId.from("prod.us-west-1"), ZoneId.from("prod.us-east-3"), ZoneId.from("prod.eu-west-1"), ZoneId.from("dev.us-east-1")),
app.instance().deployments().keySet());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/deployment", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Application package version: 1.0.2-unknown\"}");
assertEquals(Set.of(ZoneId.from("dev.us-east-1")), app.instance().deployments().keySet());
} | "{\"message\":\"Application package version: 1.0.2-unknown\"}"); | public void testRemovingAllDeployments() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 432L);
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
tester.controller().jobController().deploy(app.instanceId(), JobType.devUsEast1, Optional.empty(), applicationPackage);
assertEquals(Set.of(ZoneId.from("prod.us-west-1"), ZoneId.from("prod.us-east-3"), ZoneId.from("prod.eu-west-1"), ZoneId.from("dev.us-east-1")),
app.instance().deployments().keySet());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/deployment", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"All deployments removed\"}");
assertEquals(Set.of(ZoneId.from("dev.us-east-1")), app.instance().deployments().keySet());
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private ContainerTester tester;
private DeploymentTester deploymentTester;
@Before
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().computeVersionStatus();
}
@Test
public void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
new File("root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("application-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("application-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.properties(Map.of("recursive", "true",
"production", "true")),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID)
.properties(Map.of("recursive", "true",
"production", "true")),
new File("application-without-instances.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
var app1 = deploymentTester.newDeploymentContext(id);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/production-us-east-3/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Direct deployments are only allowed to manually deployed environments.\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/production-us-east-3/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Deployment started in run 1 of production-us-east-3 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.productionUsEast3);
tester.controller().applications().deactivate(app1.instanceId(), ZoneId.from("prod", "us-east-3"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.devUsEast1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/dev-us-east-1/package", GET)
.userIdentity(USER_ID),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1.instance1.dev.us-east-1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/deploy/dev-us-east-1", POST)
.userIdentity(USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/environment/dev/region/us-east-1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.myuser in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.myuser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
id.application());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsCentral1);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 666)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1 with version 1.0.666-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
entity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
id2.application());
deploymentTester.applications().deploymentTrigger().triggerChange(id2, Change.of(Version.fromString("7.0")));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage, 1000)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/job/production-us-west-1", POST)
.data("{\"skipTests\":true}")
.userIdentity(USER_ID),
"{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1\"}");
app2.runJob(JobType.productionUsWest1);
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/job/production-us-west-1", POST)
.data("{\"reTrigger\":true}")
.userIdentity(USER_ID),
"{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/environment/prod/region/us-west-1", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Deactivated tenant2.application2.instance1 in prod.us-west-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.userIdentity(USER_ID),
new File("application2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("application2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", PATCH)
.userIdentity(USER_ID)
.data("{\"majorVersion\":7}"),
"{\"message\":\"Set major version to 7\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/key", POST)
.userIdentity(USER_ID)
.data("{\"key\":\"" + pemPublicKey + "\"}"),
"{\"keys\":[\"-----BEGIN PUBLIC KEY-----\\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\\nz/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\\n-----END PUBLIC KEY-----\\n\"]}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", PATCH)
.userIdentity(USER_ID)
.data("{\"pemDeployKey\":\"" + pemPublicKey + "\"}"),
"{\"message\":\"Added deploy key " + quotedPemPublicKey + "\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.userIdentity(USER_ID),
new File("application2-with-patches.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", PATCH)
.userIdentity(USER_ID)
.data("{\"majorVersion\":null}"),
"{\"message\":\"Set major version to empty\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/compile-version", GET)
.userIdentity(USER_ID),
"{\"compileVersion\":\"6.1.0\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/key", DELETE)
.userIdentity(USER_ID)
.data("{\"key\":\"" + pemPublicKey + "\"}"),
"{\"keys\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.userIdentity(USER_ID),
new File("application2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant2.application2.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant2.application2\"}");
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
deploymentTester.controllerTester().computeVersionStatus();
setDeploymentMaintainedInfo();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("deployment"),
new File("recursive-root.json"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("tenant"),
new File("recursive-until-tenant-root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("tenant1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/clusters", GET)
.userIdentity(USER_ID),
new File("application-clusters.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-central-1/instance/default/logs?from=1233&to=3214", GET)
.userIdentity(USER_ID),
"INFO - All good");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Changed deployment from 'application change to 1.0.1-commit1' to 'no change' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(USER_ID)
.data("{\"cancel\":\"all\"}"),
"{\"message\":\"No deployment in progress for tenant1.application1.instance1 at this time\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", POST)
.userIdentity(USER_ID)
.data("6.1.0"),
"{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
assertTrue("Action is logged to audit log",
tester.controller().auditLogger().readLog().entries().stream()
.anyMatch(entry -> entry.resource().equals("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin?")));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Changed deployment from 'pin to 6.1' to 'upgrade to 6.1' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":false}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", POST)
.userIdentity(USER_ID)
.data("6.1"),
"{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/platform", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Changed deployment from 'pin to 6.1' to 'pin to current platform' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Changed deployment from 'pin to current platform' to 'no change' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1/pause", POST)
.userIdentity(USER_ID),
"{\"message\":\"production-us-west-1 for tenant1.application1.instance1 paused for " + DeploymentTrigger.maxPause + "\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1/pause", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"production-us-west-1 for tenant1.application1.instance1 resumed\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1", POST)
.userIdentity(USER_ID),
"{\"message\":\"Triggered production-us-west-1 for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
.userIdentity(USER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
addUserToHostedOperatorRole(HostedAthenzIdentities.from(SCREWDRIVER_ID));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-central-1/instance/instance1/restart", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in staging.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-central-1/instance/instance1/restart", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in test.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-central-1/instance/instance1/restart", POST)
.userIdentity(USER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in dev.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
.properties(Map.of("hostname", "node-1-tenant-host-prod.us-central-1"))
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
ApplicationPackage packageWithServiceForWrongDomain = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN_2.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"message\":\"Application package version: 1.0.2-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
.properties(Map.of("build", "1"))
.userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
.data(streamer),
"{\"message\":\"Application package version: 1.0.3-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.environment(Environment.prod)
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec, 123)),
"{\"message\":\"Application package version: 1.0.4-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
.userIdentity(USER_ID),
new File("jobs.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/deployment", GET)
.userIdentity(USER_ID),
new File("deployment-overview.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
.userIdentity(USER_ID),
new File("system-test-job.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
.userIdentity(USER_ID),
new File("system-test-details.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/", Request.Method.OPTIONS)
.userIdentity(USER_ID),
"");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
}
private void addIssues(DeploymentTester tester, TenantAndApplicationId id) {
tester.applications().lockApplicationOrThrow(id, application ->
tester.controller().applications().store(application.withDeploymentIssueId(IssueId.from("123"))
.withOwnershipIssueId(IssueId.from("321"))
.withOwner(User.from("owner-username"))));
}
@Test
public void testRotationOverride() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
var westZone = ZoneId.from("prod", "us-west-1");
var eastZone = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region(westZone.region())
.region(eastZone.region())
.build();
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
app.submit(applicationPackage).deploy();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/environment/prod/region/us-west-1/instance/default/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"tenant2.application2 not found\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/global-rotation/override", PUT)
.userIdentity(USER_ID)
.data("{\"reason\":\"unit-test\"}"),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
404);
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
new File("global-rotation.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", GET)
.userIdentity(USER_ID),
new File("global-rotation-get.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", PUT)
.userIdentity(USER_ID)
.data("{\"reason\":\"unit-test\"}"),
new File("global-rotation-put.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), GlobalRouting.Status.out, GlobalRouting.Agent.tenant);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", DELETE)
.userIdentity(USER_ID)
.data("{\"reason\":\"unit-test\"}"),
new File("global-rotation-delete.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), GlobalRouting.Status.in, GlobalRouting.Agent.tenant);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", PUT)
.userIdentity(HOSTED_VESPA_OPERATOR)
.data("{\"reason\":\"unit-test\"}"),
new File("global-rotation-put.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), GlobalRouting.Status.out, GlobalRouting.Agent.operator);
}
@Test
public void multiple_endpoints() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-west-1"));
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-east-3"));
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "eu-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.properties(Map.of("endpointId", "default"))
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"IN\"}}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.properties(Map.of("endpointId", "eu"))
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/eu-west-1/global-rotation", GET)
.properties(Map.of("endpointId", "eu"))
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"IN\"}}",
200);
}
@Test
public void testDeployDirectly() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST).userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(SCREWDRIVER_ID));
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(entity)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
MultiPartStreamer noAppEntity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Deployment of system applications during a system upgrade is not allowed\"}",
400);
deploymentTester.controllerTester().upgradeSystem(deploymentTester.controller().versionStatus().controllerVersion().get().versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/proxy-host/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-no-deployment.json"), 400);
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = tester.serviceRegistry().meteringService();
ResourceAllocation currentSnapshot = new ResourceAllocation(1, 2, 3);
ResourceAllocation thisMonth = new ResourceAllocation(12, 24, 1000);
ResourceAllocation lastMonth = new ResourceAllocation(24, 48, 2000);
ApplicationId applicationId = ApplicationId.from("doesnotexist", "doesnotexist", "default");
Map<ApplicationId, List<ResourceSnapshot>> snapshotHistory = Map.of(applicationId, List.of(
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(123), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringData(new MeteringData(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
@Test
public void testErrorResponses() throws Exception {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/hosted-vespa", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", "Invalid application package", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
.properties(Map.of("build", "42"))
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
.properties(Map.of("build", "foobar"))
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", "Out of capacity", ConfigServerException.ErrorCode.OUT_OF_CAPACITY, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-out-of-capacity.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to activate application", "Activation conflict", ConfigServerException.ErrorCode.ACTIVATION_CONFLICT, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-activation-conflict.json"), 409);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to deploy application", "Internal server error", ConfigServerException.ErrorCode.INTERNAL_SERVER_ERROR, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-internal-server-error.json"), 500);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 1234L);
var application = deploymentTester.newDeploymentContext("tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId("123");
addScrewdriverUserToDeployRole(screwdriverId, ATHENZ_TENANT_DOMAIN, application.instanceId().application());
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
400);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
public void personal_deployment_with_athenz_service_requires_user_is_admin() {
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.build();
createTenantAndApplication();
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
.admin(HostedAthenzIdentities.from(userId));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
@Test
public void developers_can_deploy_when_privileged() {
UserId tenantAdmin = new UserId("tenant-admin");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
UserId developer = new UserId("developer");
AthenzDomain sandboxDomain = new AthenzDomain("sandbox");
createAthenzDomainWithAdmin(sandboxDomain, developer);
AthenzTenantSpec tenantSpec = new AthenzTenantSpec(TenantName.from("sandbox"),
sandboxDomain,
new Property("vespa"),
Optional.empty());
AthenzCredentials credentials = new AthenzCredentials(
new AthenzPrincipal(new AthenzUser(developer.id())), sandboxDomain, OKTA_IT, OKTA_AT);
tester.controller().tenants().create(tenantSpec, credentials);
tester.controller().applications().createApplication(TenantAndApplicationId.from("sandbox", "myapp"), credentials);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.build();
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(developer),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"User user.developer is not allowed to launch service domain1.service. Please reach out to the domain admin.\"}",
400);
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(ATHENZ_TENANT_DOMAIN);
domainMock.withPolicy("user." + developer.id(), "launch", "service.service");
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(developer),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for sandbox.myapp. This may take about 15 minutes the first time.\",\"run\":1}",
200);
UserId developer2 = new UserId("developer2");
tester.athenzClientFactory().getSetup().getOrCreateDomain(sandboxDomain).tenantAdmin(new AthenzUser(developer2.id()));
tester.athenzClientFactory().getSetup().getOrCreateDomain(ATHENZ_TENANT_DOMAIN).tenantAdmin(new AthenzUser(developer2.id()));
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(developer2),
"{\"message\":\"Deployment started in run 2 of dev-us-east-1 for sandbox.myapp. This may take about 15 minutes the first time.\",\"run\":2}",
200);
}
@Test
public void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
var zone = ZoneId.from(Environment.prod, RegionName.from("us-west-1"));
deploymentTester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone),
List.of(RoutingMethod.exclusive, RoutingMethod.shared));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain"), AthenzService.from("service"))
.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.environment(Environment.prod)
.instances("instance1")
.region(zone.region().value())
.build();
app.submit(applicationPackage).deploy();
app.addInactiveRoutingPolicy(zone);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private MultiPartStreamer createApplicationDeployData(ApplicationPackage applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(Optional.of(applicationPackage), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(applicationPackage, Optional.empty(), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage,
Optional<ApplicationVersion> applicationVersion, boolean deployDirectly) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", deployOptions(deployDirectly, applicationVersion));
applicationPackage.ifPresent(ap -> streamer.addBytes("applicationZip", ap.zippedContent()));
return streamer;
}
static MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage, long projectId) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repository1\",\"branch\":\"master\",\"commit\":\"commit1\","
+ "\"projectId\":" + projectId + ",\"authorEmail\":\"a@b\"}")
.addBytes(EnvironmentResource.APPLICATION_ZIP, applicationPackage.zippedContent())
.addBytes(EnvironmentResource.APPLICATION_TEST_ZIP, "content".getBytes());
}
private String deployOptions(boolean deployDirectly, Optional<ApplicationVersion> applicationVersion) {
return "{\"vespaVersion\":null," +
"\"ignoreValidationErrors\":false," +
"\"deployDirectly\":" + deployDirectly +
applicationVersion.map(version ->
"," +
"\"buildNumber\":" + version.buildNumber().getAsLong() + "," +
"\"sourceRevision\":{" +
"\"repository\":\"" + version.source().get().repository() + "\"," +
"\"branch\":\"" + version.source().get().branch() + "\"," +
"\"commit\":\"" + version.source().get().commit() + "\"" +
"}"
).orElse("") +
"}";
}
/** Make a request with (athens) user domain1.mytenant */
private RequestBuilder request(String path, Request.Method method) {
return new RequestBuilder(path, method);
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void createAthenzDomainWithAdmin(AthenzDomain domain, UserId userId) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(domain);
domainMock.markAsVespaTenant();
domainMock.admin(AthenzUser.fromUserId(userId.id()));
}
/**
* Mock athenz service identity configuration. Simulates that configserver is allowed to launch a service
*/
private void allowLaunchOfService(com.yahoo.vespa.athenz.api.AthenzService service) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(service.getDomain());
domainMock.withPolicy(tester.controller().zoneRegistry().accessControlDomain().value()+".provider.*","launch", "service." + service.getName());
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void addScrewdriverUserToDeployRole(ScrewdriverId screwdriverId,
AthenzDomain domain,
ApplicationName application) {
tester.authorize(domain, HostedAthenzIdentities.from(screwdriverId), ApplicationAction.deploy, application);
}
private ApplicationId createTenantAndApplication() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
/**
* Cluster info, utilization and application and deployment metrics are maintained async by maintainers.
*
* This sets these values as if the maintainers has been ran.
*/
private void setDeploymentMaintainedInfo() {
for (Application application : deploymentTester.applications().asList()) {
deploymentTester.applications().lockApplicationOrThrow(application.id(), lockedApplication -> {
lockedApplication = lockedApplication.with(new ApplicationMetrics(0.5, 0.7));
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.deployments().values()) {
DeploymentMetrics metrics = new DeploymentMetrics(1, 2, 3, 4, 5,
Optional.of(Instant.ofEpochMilli(123123)), Map.of());
lockedApplication = lockedApplication.with(instance.name(),
lockedInstance -> lockedInstance.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
deploymentTester.applications().store(lockedApplication);
}
});
}
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
tester.serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1)).run();
}
private void updateContactInformation() {
Contact contact = new Contact(URI.create("www.contacts.tld/1234"),
URI.create("www.properties.tld/1234"),
URI.create("www.issues.tld/1234"),
List.of(List.of("alice"), List.of("bob")), "queue", Optional.empty());
tester.controller().tenants().lockIfPresent(TenantName.from("tenant2"),
LockedTenant.Athenz.class,
lockedTenant -> tester.controller().tenants().store(lockedTenant.with(contact)));
}
private void registerContact(long propertyId) {
PropertyId p = new PropertyId(String.valueOf(propertyId));
tester.serviceRegistry().contactRetrieverMock().addContact(p, new Contact(URI.create("www.issues.tld/" + p.id()),
URI.create("www.contacts.tld/" + p.id()),
URI.create("www.properties.tld/" + p.id()),
List.of(Collections.singletonList("alice"),
Collections.singletonList("bob")),
"queue", Optional.empty()));
}
private void assertGlobalRouting(DeploymentId deployment, GlobalRouting.Status status, GlobalRouting.Agent agent) {
var changedAt = tester.controller().clock().instant();
var westPolicies = tester.controller().routing().policies().get(deployment);
assertEquals(1, westPolicies.size());
var westPolicy = westPolicies.values().iterator().next();
assertEquals(status, westPolicy.status().globalRouting().status());
assertEquals(agent, westPolicy.status().globalRouting().agent());
assertEquals(changedAt.truncatedTo(ChronoUnit.MILLIS), westPolicy.status().globalRouting().changedAt());
}
private static class RequestBuilder implements Supplier<Request> {
private final String path;
private final Request.Method method;
private byte[] data = new byte[0];
private AthenzIdentity identity;
private OktaIdentityToken oktaIdentityToken;
private OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private final Map<String, List<String>> headers = new HashMap<>();
private final Map<String, String> properties = new HashMap<>();
private RequestBuilder(String path, Request.Method method) {
this.path = path;
this.method = method;
}
private RequestBuilder data(byte[] data) { this.data = data; return this; }
private RequestBuilder data(String data) { return data(data.getBytes(UTF_8)); }
private RequestBuilder data(MultiPartStreamer streamer) {
return Exceptions.uncheck(() -> data(streamer.data().readAllBytes()).contentType(streamer.contentType()));
}
private RequestBuilder userIdentity(UserId userId) { this.identity = HostedAthenzIdentities.from(userId); return this; }
private RequestBuilder screwdriverIdentity(ScrewdriverId screwdriverId) { this.identity = HostedAthenzIdentities.from(screwdriverId); return this; }
private RequestBuilder oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) {return properties(Map.of("recursive", recursive)); }
private RequestBuilder properties(Map<String, String> properties) { this.properties.putAll(properties); return this; }
private RequestBuilder header(String name, String value) {
this.headers.putIfAbsent(name, new ArrayList<>());
this.headers.get(name).add(value);
return this;
}
@Override
public Request get() {
Request request = new Request("http:
properties.entrySet().stream()
.map(entry -> encode(entry.getKey(), UTF_8) + "=" + encode(entry.getValue(), UTF_8))
.collect(joining("&", "?", "")),
data, method);
request.getHeaders().addAll(headers);
request.getHeaders().put("Content-Type", contentType);
if (identity != null) {
addIdentityToRequest(request, identity);
}
if (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private ContainerTester tester;
private DeploymentTester deploymentTester;
@Before
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().computeVersionStatus();
}
@Test
public void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
new File("root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("application-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("application-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.properties(Map.of("recursive", "true",
"production", "true")),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID)
.properties(Map.of("recursive", "true",
"production", "true")),
new File("application-without-instances.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
var app1 = deploymentTester.newDeploymentContext(id);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/production-us-east-3/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Direct deployments are only allowed to manually deployed environments.\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/production-us-east-3/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Deployment started in run 1 of production-us-east-3 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.productionUsEast3);
tester.controller().applications().deactivate(app1.instanceId(), ZoneId.from("prod", "us-east-3"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.devUsEast1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/dev-us-east-1/package", GET)
.userIdentity(USER_ID),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1.instance1.dev.us-east-1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/deploy/dev-us-east-1", POST)
.userIdentity(USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/environment/dev/region/us-east-1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.myuser in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.myuser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
id.application());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsCentral1);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 666)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1 with version 1.0.666-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
entity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
id2.application());
deploymentTester.applications().deploymentTrigger().triggerChange(id2, Change.of(Version.fromString("7.0")));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage, 1000)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/job/production-us-west-1", POST)
.data("{\"skipTests\":true}")
.userIdentity(USER_ID),
"{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1\"}");
app2.runJob(JobType.productionUsWest1);
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/job/production-us-west-1", POST)
.data("{\"reTrigger\":true}")
.userIdentity(USER_ID),
"{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/environment/prod/region/us-west-1", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Deactivated tenant2.application2.instance1 in prod.us-west-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.userIdentity(USER_ID),
new File("application2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("application2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", PATCH)
.userIdentity(USER_ID)
.data("{\"majorVersion\":7}"),
"{\"message\":\"Set major version to 7\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/key", POST)
.userIdentity(USER_ID)
.data("{\"key\":\"" + pemPublicKey + "\"}"),
"{\"keys\":[\"-----BEGIN PUBLIC KEY-----\\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\\nz/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\\n-----END PUBLIC KEY-----\\n\"]}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", PATCH)
.userIdentity(USER_ID)
.data("{\"pemDeployKey\":\"" + pemPublicKey + "\"}"),
"{\"message\":\"Added deploy key " + quotedPemPublicKey + "\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.userIdentity(USER_ID),
new File("application2-with-patches.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", PATCH)
.userIdentity(USER_ID)
.data("{\"majorVersion\":null}"),
"{\"message\":\"Set major version to empty\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/compile-version", GET)
.userIdentity(USER_ID),
"{\"compileVersion\":\"6.1.0\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/key", DELETE)
.userIdentity(USER_ID)
.data("{\"key\":\"" + pemPublicKey + "\"}"),
"{\"keys\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.userIdentity(USER_ID),
new File("application2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant2.application2.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant2.application2\"}");
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
deploymentTester.controllerTester().computeVersionStatus();
setDeploymentMaintainedInfo();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("deployment"),
new File("recursive-root.json"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("tenant"),
new File("recursive-until-tenant-root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("tenant1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/clusters", GET)
.userIdentity(USER_ID),
new File("application-clusters.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-central-1/instance/default/logs?from=1233&to=3214", GET)
.userIdentity(USER_ID),
"INFO - All good");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Changed deployment from 'application change to 1.0.1-commit1' to 'no change' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(USER_ID)
.data("{\"cancel\":\"all\"}"),
"{\"message\":\"No deployment in progress for tenant1.application1.instance1 at this time\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", POST)
.userIdentity(USER_ID)
.data("6.1.0"),
"{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
assertTrue("Action is logged to audit log",
tester.controller().auditLogger().readLog().entries().stream()
.anyMatch(entry -> entry.resource().equals("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin?")));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Changed deployment from 'pin to 6.1' to 'upgrade to 6.1' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":false}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", POST)
.userIdentity(USER_ID)
.data("6.1"),
"{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/platform", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Changed deployment from 'pin to 6.1' to 'pin to current platform' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Changed deployment from 'pin to current platform' to 'no change' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1/pause", POST)
.userIdentity(USER_ID),
"{\"message\":\"production-us-west-1 for tenant1.application1.instance1 paused for " + DeploymentTrigger.maxPause + "\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1/pause", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"production-us-west-1 for tenant1.application1.instance1 resumed\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1", POST)
.userIdentity(USER_ID),
"{\"message\":\"Triggered production-us-west-1 for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
.userIdentity(USER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
addUserToHostedOperatorRole(HostedAthenzIdentities.from(SCREWDRIVER_ID));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-central-1/instance/instance1/restart", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in staging.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-central-1/instance/instance1/restart", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in test.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-central-1/instance/instance1/restart", POST)
.userIdentity(USER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in dev.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
.properties(Map.of("hostname", "node-1-tenant-host-prod.us-central-1"))
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
ApplicationPackage packageWithServiceForWrongDomain = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN_2.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"message\":\"Application package version: 1.0.2-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
.properties(Map.of("build", "1"))
.userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
.data(streamer),
"{\"message\":\"Application package version: 1.0.3-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.environment(Environment.prod)
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec, 123)),
"{\"message\":\"Application package version: 1.0.4-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
.userIdentity(USER_ID),
new File("jobs.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/deployment", GET)
.userIdentity(USER_ID),
new File("deployment-overview.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
.userIdentity(USER_ID),
new File("system-test-job.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
.userIdentity(USER_ID),
new File("system-test-details.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/", Request.Method.OPTIONS)
.userIdentity(USER_ID),
"");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
}
private void addIssues(DeploymentTester tester, TenantAndApplicationId id) {
tester.applications().lockApplicationOrThrow(id, application ->
tester.controller().applications().store(application.withDeploymentIssueId(IssueId.from("123"))
.withOwnershipIssueId(IssueId.from("321"))
.withOwner(User.from("owner-username"))));
}
@Test
public void testRotationOverride() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
var westZone = ZoneId.from("prod", "us-west-1");
var eastZone = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region(westZone.region())
.region(eastZone.region())
.build();
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
app.submit(applicationPackage).deploy();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/environment/prod/region/us-west-1/instance/default/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"tenant2.application2 not found\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/global-rotation/override", PUT)
.userIdentity(USER_ID)
.data("{\"reason\":\"unit-test\"}"),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
404);
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
new File("global-rotation.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", GET)
.userIdentity(USER_ID),
new File("global-rotation-get.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", PUT)
.userIdentity(USER_ID)
.data("{\"reason\":\"unit-test\"}"),
new File("global-rotation-put.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), GlobalRouting.Status.out, GlobalRouting.Agent.tenant);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", DELETE)
.userIdentity(USER_ID)
.data("{\"reason\":\"unit-test\"}"),
new File("global-rotation-delete.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), GlobalRouting.Status.in, GlobalRouting.Agent.tenant);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", PUT)
.userIdentity(HOSTED_VESPA_OPERATOR)
.data("{\"reason\":\"unit-test\"}"),
new File("global-rotation-put.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), GlobalRouting.Status.out, GlobalRouting.Agent.operator);
}
@Test
public void multiple_endpoints() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-west-1"));
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-east-3"));
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "eu-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.properties(Map.of("endpointId", "default"))
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"IN\"}}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.properties(Map.of("endpointId", "eu"))
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/eu-west-1/global-rotation", GET)
.properties(Map.of("endpointId", "eu"))
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"IN\"}}",
200);
}
@Test
public void testDeployDirectly() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST).userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(SCREWDRIVER_ID));
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(entity)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
MultiPartStreamer noAppEntity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Deployment of system applications during a system upgrade is not allowed\"}",
400);
deploymentTester.controllerTester().upgradeSystem(deploymentTester.controller().versionStatus().controllerVersion().get().versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/proxy-host/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-no-deployment.json"), 400);
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = tester.serviceRegistry().meteringService();
ResourceAllocation currentSnapshot = new ResourceAllocation(1, 2, 3);
ResourceAllocation thisMonth = new ResourceAllocation(12, 24, 1000);
ResourceAllocation lastMonth = new ResourceAllocation(24, 48, 2000);
ApplicationId applicationId = ApplicationId.from("doesnotexist", "doesnotexist", "default");
Map<ApplicationId, List<ResourceSnapshot>> snapshotHistory = Map.of(applicationId, List.of(
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(123), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringData(new MeteringData(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
@Test
public void testErrorResponses() throws Exception {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/hosted-vespa", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", "Invalid application package", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
.properties(Map.of("build", "42"))
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
.properties(Map.of("build", "foobar"))
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", "Out of capacity", ConfigServerException.ErrorCode.OUT_OF_CAPACITY, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-out-of-capacity.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to activate application", "Activation conflict", ConfigServerException.ErrorCode.ACTIVATION_CONFLICT, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-activation-conflict.json"), 409);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to deploy application", "Internal server error", ConfigServerException.ErrorCode.INTERNAL_SERVER_ERROR, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-internal-server-error.json"), 500);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 1234L);
var application = deploymentTester.newDeploymentContext("tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId("123");
addScrewdriverUserToDeployRole(screwdriverId, ATHENZ_TENANT_DOMAIN, application.instanceId().application());
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
400);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
public void personal_deployment_with_athenz_service_requires_user_is_admin() {
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.build();
createTenantAndApplication();
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
.admin(HostedAthenzIdentities.from(userId));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
@Test
public void developers_can_deploy_when_privileged() {
UserId tenantAdmin = new UserId("tenant-admin");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
UserId developer = new UserId("developer");
AthenzDomain sandboxDomain = new AthenzDomain("sandbox");
createAthenzDomainWithAdmin(sandboxDomain, developer);
AthenzTenantSpec tenantSpec = new AthenzTenantSpec(TenantName.from("sandbox"),
sandboxDomain,
new Property("vespa"),
Optional.empty());
AthenzCredentials credentials = new AthenzCredentials(
new AthenzPrincipal(new AthenzUser(developer.id())), sandboxDomain, OKTA_IT, OKTA_AT);
tester.controller().tenants().create(tenantSpec, credentials);
tester.controller().applications().createApplication(TenantAndApplicationId.from("sandbox", "myapp"), credentials);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.build();
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(developer),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"User user.developer is not allowed to launch service domain1.service. Please reach out to the domain admin.\"}",
400);
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(ATHENZ_TENANT_DOMAIN);
domainMock.withPolicy("user." + developer.id(), "launch", "service.service");
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(developer),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for sandbox.myapp. This may take about 15 minutes the first time.\",\"run\":1}",
200);
UserId developer2 = new UserId("developer2");
tester.athenzClientFactory().getSetup().getOrCreateDomain(sandboxDomain).tenantAdmin(new AthenzUser(developer2.id()));
tester.athenzClientFactory().getSetup().getOrCreateDomain(ATHENZ_TENANT_DOMAIN).tenantAdmin(new AthenzUser(developer2.id()));
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(developer2),
"{\"message\":\"Deployment started in run 2 of dev-us-east-1 for sandbox.myapp. This may take about 15 minutes the first time.\",\"run\":2}",
200);
}
@Test
public void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
var zone = ZoneId.from(Environment.prod, RegionName.from("us-west-1"));
deploymentTester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone),
List.of(RoutingMethod.exclusive, RoutingMethod.shared));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain"), AthenzService.from("service"))
.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.environment(Environment.prod)
.instances("instance1")
.region(zone.region().value())
.build();
app.submit(applicationPackage).deploy();
app.addInactiveRoutingPolicy(zone);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private MultiPartStreamer createApplicationDeployData(ApplicationPackage applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(Optional.of(applicationPackage), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(applicationPackage, Optional.empty(), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage,
Optional<ApplicationVersion> applicationVersion, boolean deployDirectly) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", deployOptions(deployDirectly, applicationVersion));
applicationPackage.ifPresent(ap -> streamer.addBytes("applicationZip", ap.zippedContent()));
return streamer;
}
static MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage, long projectId) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repository1\",\"branch\":\"master\",\"commit\":\"commit1\","
+ "\"projectId\":" + projectId + ",\"authorEmail\":\"a@b\"}")
.addBytes(EnvironmentResource.APPLICATION_ZIP, applicationPackage.zippedContent())
.addBytes(EnvironmentResource.APPLICATION_TEST_ZIP, "content".getBytes());
}
private String deployOptions(boolean deployDirectly, Optional<ApplicationVersion> applicationVersion) {
return "{\"vespaVersion\":null," +
"\"ignoreValidationErrors\":false," +
"\"deployDirectly\":" + deployDirectly +
applicationVersion.map(version ->
"," +
"\"buildNumber\":" + version.buildNumber().getAsLong() + "," +
"\"sourceRevision\":{" +
"\"repository\":\"" + version.source().get().repository() + "\"," +
"\"branch\":\"" + version.source().get().branch() + "\"," +
"\"commit\":\"" + version.source().get().commit() + "\"" +
"}"
).orElse("") +
"}";
}
/** Make a request with (athens) user domain1.mytenant */
private RequestBuilder request(String path, Request.Method method) {
return new RequestBuilder(path, method);
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void createAthenzDomainWithAdmin(AthenzDomain domain, UserId userId) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(domain);
domainMock.markAsVespaTenant();
domainMock.admin(AthenzUser.fromUserId(userId.id()));
}
/**
* Mock athenz service identity configuration. Simulates that configserver is allowed to launch a service
*/
private void allowLaunchOfService(com.yahoo.vespa.athenz.api.AthenzService service) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(service.getDomain());
domainMock.withPolicy(tester.controller().zoneRegistry().accessControlDomain().value()+".provider.*","launch", "service." + service.getName());
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void addScrewdriverUserToDeployRole(ScrewdriverId screwdriverId,
AthenzDomain domain,
ApplicationName application) {
tester.authorize(domain, HostedAthenzIdentities.from(screwdriverId), ApplicationAction.deploy, application);
}
private ApplicationId createTenantAndApplication() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
/**
* Cluster info, utilization and application and deployment metrics are maintained async by maintainers.
*
* This sets these values as if the maintainers has been ran.
*/
private void setDeploymentMaintainedInfo() {
for (Application application : deploymentTester.applications().asList()) {
deploymentTester.applications().lockApplicationOrThrow(application.id(), lockedApplication -> {
lockedApplication = lockedApplication.with(new ApplicationMetrics(0.5, 0.7));
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.deployments().values()) {
DeploymentMetrics metrics = new DeploymentMetrics(1, 2, 3, 4, 5,
Optional.of(Instant.ofEpochMilli(123123)), Map.of());
lockedApplication = lockedApplication.with(instance.name(),
lockedInstance -> lockedInstance.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
deploymentTester.applications().store(lockedApplication);
}
});
}
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
tester.serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1)).run();
}
private void updateContactInformation() {
Contact contact = new Contact(URI.create("www.contacts.tld/1234"),
URI.create("www.properties.tld/1234"),
URI.create("www.issues.tld/1234"),
List.of(List.of("alice"), List.of("bob")), "queue", Optional.empty());
tester.controller().tenants().lockIfPresent(TenantName.from("tenant2"),
LockedTenant.Athenz.class,
lockedTenant -> tester.controller().tenants().store(lockedTenant.with(contact)));
}
private void registerContact(long propertyId) {
PropertyId p = new PropertyId(String.valueOf(propertyId));
tester.serviceRegistry().contactRetrieverMock().addContact(p, new Contact(URI.create("www.issues.tld/" + p.id()),
URI.create("www.contacts.tld/" + p.id()),
URI.create("www.properties.tld/" + p.id()),
List.of(Collections.singletonList("alice"),
Collections.singletonList("bob")),
"queue", Optional.empty()));
}
private void assertGlobalRouting(DeploymentId deployment, GlobalRouting.Status status, GlobalRouting.Agent agent) {
var changedAt = tester.controller().clock().instant();
var westPolicies = tester.controller().routing().policies().get(deployment);
assertEquals(1, westPolicies.size());
var westPolicy = westPolicies.values().iterator().next();
assertEquals(status, westPolicy.status().globalRouting().status());
assertEquals(agent, westPolicy.status().globalRouting().agent());
assertEquals(changedAt.truncatedTo(ChronoUnit.MILLIS), westPolicy.status().globalRouting().changedAt());
}
private static class RequestBuilder implements Supplier<Request> {
private final String path;
private final Request.Method method;
private byte[] data = new byte[0];
private AthenzIdentity identity;
private OktaIdentityToken oktaIdentityToken;
private OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private final Map<String, List<String>> headers = new HashMap<>();
private final Map<String, String> properties = new HashMap<>();
private RequestBuilder(String path, Request.Method method) {
this.path = path;
this.method = method;
}
private RequestBuilder data(byte[] data) { this.data = data; return this; }
private RequestBuilder data(String data) { return data(data.getBytes(UTF_8)); }
private RequestBuilder data(MultiPartStreamer streamer) {
return Exceptions.uncheck(() -> data(streamer.data().readAllBytes()).contentType(streamer.contentType()));
}
private RequestBuilder userIdentity(UserId userId) { this.identity = HostedAthenzIdentities.from(userId); return this; }
private RequestBuilder screwdriverIdentity(ScrewdriverId screwdriverId) { this.identity = HostedAthenzIdentities.from(screwdriverId); return this; }
private RequestBuilder oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) {return properties(Map.of("recursive", recursive)); }
private RequestBuilder properties(Map<String, String> properties) { this.properties.putAll(properties); return this; }
private RequestBuilder header(String name, String value) {
this.headers.putIfAbsent(name, new ArrayList<>());
this.headers.get(name).add(value);
return this;
}
@Override
public Request get() {
Request request = new Request("http:
properties.entrySet().stream()
.map(entry -> encode(entry.getKey(), UTF_8) + "=" + encode(entry.getValue(), UTF_8))
.collect(joining("&", "?", "")),
data, method);
request.getHeaders().addAll(headers);
request.getHeaders().put("Content-Type", contentType);
if (identity != null) {
addIdentityToRequest(request, identity);
}
if (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} |
My understanding is that this will submit the empty application, which will notify the JobController which will asynchronously at some point see that prod deployments have been removed and start making DELETE calls against config servers. It will also figure out that the system/staging tests it might have been running are no longer needed and abort them + delete deployment (similar to what happens when you submit a new package while tests are running). | private HttpResponse handleDELETE(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeProdAllDeployments(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
return ErrorResponse.notFoundError("Nothing at " + path);
} | if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeProdAllDeployments(path.get("tenant"), path.get("application")); | private HttpResponse handleDELETE(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeAllProdDeployments(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
return ErrorResponse.notFoundError("Nothing at " + path);
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestConfigSerializer testConfigSerializer;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
}
@Override
public Duration getTimeout() {
return Duration.ofMinutes(20);
}
@Override
public HttpResponse handle(HttpRequest request) {
try {
Path path = new Path(request.getUri(), OPTIONAL_PREFIX);
switch (request.getMethod()) {
case GET: return handleGET(path, request);
case PUT: return handlePUT(path, request);
case POST: return handlePOST(path, request);
case PATCH: return handlePATCH(path, request);
case DELETE: return handleDELETE(path, request);
case OPTIONS: return handleOPTIONS();
default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
}
}
catch (ForbiddenException e) {
return ErrorResponse.forbidden(Exceptions.toMessageString(e));
}
catch (NotAuthorizedException e) {
return ErrorResponse.unauthorized(Exceptions.toMessageString(e));
}
catch (NotExistsException e) {
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
}
catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
catch (ConfigServerException e) {
switch (e.getErrorCode()) {
case NOT_FOUND:
return new ErrorResponse(NOT_FOUND, e.getErrorCode().name(), Exceptions.toMessageString(e));
case ACTIVATION_CONFLICT:
return new ErrorResponse(CONFLICT, e.getErrorCode().name(), Exceptions.toMessageString(e));
case INTERNAL_SERVER_ERROR:
return new ErrorResponse(INTERNAL_SERVER_ERROR, e.getErrorCode().name(), Exceptions.toMessageString(e));
default:
return new ErrorResponse(BAD_REQUEST, e.getErrorCode().name(), Exceptions.toMessageString(e));
}
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/tenant")) return tenants(request);
if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePUT(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePATCH(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleOPTIONS() {
EmptyResponse response = new EmptyResponse();
response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS");
return response;
}
private HttpResponse recursiveRoot(HttpRequest request) {
Slime slime = new Slime();
Cursor tenantArray = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
toSlime(tenantArray.addObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse root(HttpRequest request) {
return recurseOverTenants(request)
? recursiveRoot(request)
: new ResourceResponse(request, "tenant");
}
private HttpResponse tenants(HttpRequest request) {
Slime slime = new Slime();
Cursor response = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject());
return new SlimeJsonResponse(slime);
}
private HttpResponse tenant(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenant(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenant(Tenant tenant, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
if (controller.tenants().get(tenantName).isEmpty())
return ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist");
Slime slime = new Slime();
Cursor applicationArray = slime.setArray();
for (com.yahoo.vespa.hosted.controller.Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true)) {
Cursor applicationObject = applicationArray.addObject();
applicationObject.setString("tenant", application.id().tenant().value());
applicationObject.setString("application", application.id().application().value());
applicationObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value(),
request.getUri()).toString());
Cursor instanceArray = applicationObject.setArray("instances");
for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet()
: application.instances().keySet()) {
Cursor instanceObject = instanceArray.addObject();
instanceObject.setString("instance", instance.value());
instanceObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/instance/" + instance.value(),
request.getUri()).toString());
}
}
}
return new SlimeJsonResponse(slime);
}
private HttpResponse devApplicationPackage(ApplicationId id, JobType type) {
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Only manually deployed zones have dev packages");
ZoneId zone = type.zone(controller.system());
byte[] applicationPackage = controller.applications().applicationStore().getDev(id, zone);
return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage);
}
private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse compileVersion(String tenantName, String applicationName) {
Slime slime = new Slime();
slime.setObject().setString("compileVersion",
compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString());
return new SlimeJsonResponse(slime);
}
private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
Principal user = request.getJDiscRequest().getUserPrincipal();
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withDeveloperKey(developerKey, user);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Principal user = ((CloudTenant) controller.tenants().require(TenantName.from(tenantName))).developerKeys().get(developerKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withoutDeveloperKey(developerKey);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) {
keys.forEach((key, principal) -> {
Cursor keyObject = keysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", principal.getName());
});
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withoutDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes.");
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
Inspector majorVersionField = requestObject.field("majorVersion");
if (majorVersionField.valid()) {
Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong();
application = application.withMajorVersion(majorVersion);
messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion));
}
Inspector pemDeployKeyField = requestObject.field("pemDeployKey");
if (pemDeployKeyField.valid()) {
String pemDeployKey = pemDeployKeyField.asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
application = application.withDeployKey(deployKey);
messageBuilder.add("Added deploy key " + pemDeployKey);
}
controller.applications().store(application);
});
return new MessageResponse(messageBuilder.toString());
}
private com.yahoo.vespa.hosted.controller.Application getApplication(String tenantName, String applicationName) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
return controller.applications().getApplication(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private Instance getInstance(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
return controller.applications().getInstance(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, id);
Slime slime = new Slime();
Cursor nodesArray = slime.setObject().setArray("nodes");
for (Node node : nodes) {
Cursor nodeObject = nodesArray.addObject();
nodeObject.setString("hostname", node.hostname().value());
nodeObject.setString("state", valueOf(node.state()));
node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.flavor());
toSlime(node.resources(), nodeObject);
nodeObject.setBool("fastDisk", node.resources().diskSpeed() == NodeResources.DiskSpeed.fast);
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
return new SlimeJsonResponse(slime);
}
private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id);
Slime slime = new Slime();
Cursor clustersObject = slime.setObject().setObject("clusters");
for (Cluster cluster : application.clusters().values()) {
Cursor clusterObject = clustersObject.setObject(cluster.id().value());
toSlime(cluster.min(), clusterObject.setObject("min"));
toSlime(cluster.max(), clusterObject.setObject("max"));
toSlime(cluster.current(), clusterObject.setObject("current"));
cluster.target().ifPresent(target -> toSlime(target, clusterObject.setObject("target")));
cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested")));
}
return new SlimeJsonResponse(slime);
}
private static String valueOf(Node.State state) {
switch (state) {
case failed: return "failed";
case parked: return "parked";
case dirty: return "dirty";
case ready: return "ready";
case active: return "active";
case inactive: return "inactive";
case reserved: return "reserved";
case provisioned: return "provisioned";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ServiceState state) {
switch (state) {
case expectedUp: return "expectedUp";
case allowedDown: return "allowedDown";
case unorchestrated: return "unorchestrated";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ClusterType type) {
switch (type) {
case admin: return "admin";
case content: return "content";
case container: return "container";
case combined: return "combined";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
private static String valueOf(NodeResources.DiskSpeed diskSpeed) {
switch (diskSpeed) {
case fast : return "fast";
case slow : return "slow";
case any : return "any";
default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'");
}
}
private static String valueOf(NodeResources.StorageType storageType) {
switch (storageType) {
case remote : return "remote";
case local : return "local";
case any : return "any";
default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'");
}
}
private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters);
return new HttpResponse(200) {
@Override
public void render(OutputStream outputStream) throws IOException {
logStream.transferTo(outputStream);
}
};
}
private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
boolean requireTests = ! requestObject.field("skipTests").asBool();
boolean reTrigger = requestObject.field("reTrigger").asBool();
String triggered = reTrigger
? controller.applications().deploymentTrigger()
.reTrigger(id, type).type().jobName()
: controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests)
.stream().map(job -> job.type().jobName()).collect(joining(", "));
return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered"
: "Triggered " + triggered + " for " + id);
}
private HttpResponse pause(ApplicationId id, JobType type) {
Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause);
controller.applications().deploymentTrigger().pauseJob(id, type, until);
return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause);
}
private HttpResponse resume(ApplicationId id, JobType type) {
controller.applications().deploymentTrigger().resumeJob(id, type);
return new MessageResponse(type.jobName() + " for " + id + " resumed");
}
private void toSlime(Cursor object, com.yahoo.vespa.hosted.controller.Application application, HttpRequest request) {
object.setString("tenant", application.id().tenant().value());
object.setString("application", application.id().application().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/job/",
request.getUri()).toString());
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
application.instances().values().stream().findFirst().ifPresent(instance -> {
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
});
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request);
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
if (deploymentSpec.instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec.requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
globalEndpointsToSlime(object, instance);
List<Deployment> deployments = deploymentSpec.instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor deploymentsArray = object.setArray("deployments");
for (Deployment deployment : deployments) {
Cursor deploymentObject = deploymentsArray.addObject();
if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty())
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/instance/" + instance.name().value() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
}
private void globalEndpointsToSlime(Cursor object, Instance instance) {
var globalEndpointUrls = new LinkedHashSet<String>();
controller.routing().endpointsOf(instance.id())
.requiresRotation()
.not().legacy()
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalEndpointUrls::add);
var globalRotationsArray = object.setArray("globalRotations");
globalEndpointUrls.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
}
private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) {
com.yahoo.vespa.hosted.controller.Application application = status.application();
object.setString("tenant", instance.id().tenant().value());
object.setString("application", instance.id().application().value());
object.setString("instance", instance.id().instance().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + instance.id().tenant().value() +
"/application/" + instance.id().application().value() +
"/instance/" + instance.id().instance().value() + "/job/",
request.getUri()).toString());
application.latestVersion().ifPresent(version -> {
sourceRevisionToSlime(version.source(), object.setObject("source"));
version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
version.commit().ifPresent(commit -> object.setString("commit", commit));
});
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if (application.deploymentSpec().instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec().requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
globalEndpointsToSlime(object, instance);
List<Deployment> deployments =
application.deploymentSpec().instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor instancesArray = object.setArray("instances");
for (Deployment deployment : deployments) {
Cursor deploymentObject = instancesArray.addObject();
if (deployment.zone().environment() == Environment.prod) {
if (instance.rotations().size() == 1) {
toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment),
deploymentObject);
}
if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) {
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
}
}
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("instance", instance.id().instance().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
status.jobSteps().keySet().stream()
.filter(job -> job.application().instance().equals(instance.name()))
.filter(job -> job.type().isProduction() && job.type().isDeployment())
.map(job -> job.type().zone(controller.system()))
.filter(zone -> ! instance.deployments().containsKey(zone))
.forEach(zone -> {
Cursor deploymentObject = instancesArray.addObject();
deploymentObject.setString("environment", zone.environment().value());
deploymentObject.setString("region", zone.region().value());
});
application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key)));
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().getInstance(id)
.orElseThrow(() -> new NotExistsException(id + " not found"));
DeploymentId deploymentId = new DeploymentId(instance.id(),
ZoneId.from(environment, region));
Deployment deployment = instance.deployments().get(deploymentId.zoneId());
if (deployment == null)
throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId());
Slime slime = new Slime();
toSlime(slime.setObject(), deploymentId, deployment, request);
return new SlimeJsonResponse(slime);
}
private void toSlime(Cursor object, Change change) {
change.platform().ifPresent(version -> object.setString("version", version.toString()));
change.application()
.filter(version -> !version.isUnknown())
.ifPresent(version -> toSlime(version, object.setObject("revision")));
}
private void toSlime(Endpoint endpoint, String cluster, Cursor object) {
object.setString("cluster", cluster);
object.setBool("tls", endpoint.tls());
object.setString("url", endpoint.url().toString());
object.setString("scope", endpointScopeString(endpoint.scope()));
object.setString("routingMethod", routingMethodString(endpoint.routingMethod()));
}
private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) {
response.setString("tenant", deploymentId.applicationId().tenant().value());
response.setString("application", deploymentId.applicationId().application().value());
response.setString("instance", deploymentId.applicationId().instance().value());
response.setString("environment", deploymentId.zoneId().environment().value());
response.setString("region", deploymentId.zoneId().region().value());
var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId()));
var endpointArray = response.setArray("endpoints");
for (var endpoint : controller.routing().endpointsOf(deploymentId)
.scope(Endpoint.Scope.zone)
.not().legacy()) {
toSlime(endpoint, endpoint.name(), endpointArray.addObject());
}
var globalEndpoints = controller.routing().endpointsOf(application, deploymentId.applicationId().instance())
.not().legacy()
.targets(deploymentId.zoneId());
for (var endpoint : globalEndpoints) {
toSlime(endpoint, endpoint.cluster().value(), endpointArray.addObject());
}
response.setString("nodes", withPath("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/?&recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString());
response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString());
response.setString("version", deployment.version().toFullString());
response.setString("revision", deployment.applicationVersion().id());
response.setLong("deployTimeEpochMs", deployment.at().toEpochMilli());
controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId())
.ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", deployment.at().plus(deploymentTimeToLive).toEpochMilli()));
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
var instance = application.instances().get(deploymentId.applicationId().instance());
if (instance != null) {
if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod)
toSlime(instance.rotations(), instance.rotationStatus(), deployment, response);
JobType.from(controller.system(), deployment.zone())
.map(type -> new JobId(instance.id(), type))
.map(status.jobSteps()::get)
.ifPresent(stepStatus -> {
JobControllerApiHandlerHelper.applicationVersionToSlime(
response.setObject("applicationVersion"), deployment.applicationVersion());
if (!status.jobsToRun().containsKey(stepStatus.job().get()))
response.setString("status", "complete");
else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true))
response.setString("status", "pending");
else response.setString("status", "running");
});
}
Cursor activity = response.setObject("activity");
deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried",
instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten",
instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
DeploymentMetrics metrics = deployment.metrics();
Cursor metricsObject = response.setObject("metrics");
metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond());
metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond());
metricsObject.setDouble("documentCount", metrics.documentCount());
metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis());
metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli()));
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if ( ! applicationVersion.isUnknown()) {
object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong());
object.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if (revision.isEmpty()) return;
object.setString("gitRepository", revision.get().repository());
object.setString("gitBranch", revision.get().branch());
object.setString("gitCommit", revision.get().commit());
}
private void toSlime(RotationState state, Cursor object) {
Cursor bcpStatus = object.setObject("bcpStatus");
bcpStatus.setString("rotationStatus", rotationStateString(state));
}
private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) {
var array = object.setArray("endpointStatus");
for (var rotation : rotations) {
var statusObject = array.addObject();
var targets = status.of(rotation.rotationId());
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("rotationId", rotation.rotationId().asString());
statusObject.setString("clusterId", rotation.clusterId().value());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli());
}
}
private URI monitoringSystemUri(DeploymentId deploymentId) {
return controller.zoneRegistry().getMonitoringSystemUri(deploymentId);
}
/**
* Returns a non-broken, released version at least as old as the oldest platform the given application is on.
*
* If no known version is applicable, the newest version at least as old as the oldest platform is selected,
* among all versions released for this system. If no such versions exists, throws an IllegalStateException.
*/
private Version compileVersion(TenantAndApplicationId id) {
Version oldestPlatform = controller.applications().oldestInstalledPlatform(id);
VersionStatus versionStatus = controller.versionStatus();
return versionStatus.versions().stream()
.filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low))
.filter(VespaVersion::isReleased)
.map(VespaVersion::versionNumber)
.filter(version -> ! version.isAfter(oldestPlatform))
.max(Comparator.naturalOrder())
.orElseGet(() -> controller.mavenRepository().metadata().versions().stream()
.filter(version -> ! version.isAfter(oldestPlatform))
.filter(version -> ! versionStatus.versions().stream()
.map(VespaVersion::versionNumber)
.collect(Collectors.toSet()).contains(version))
.max(Comparator.naturalOrder())
.orElseThrow(() -> new IllegalStateException("No available releases of " +
controller.mavenRepository().artifactId())));
}
private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
ZoneId zone = ZoneId.from(environment, region);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
var deploymentId = new DeploymentId(instance.id(), zone);
setGlobalRotationStatus(deploymentId, inService, request);
setGlobalEndpointStatus(deploymentId, inService, request);
return new MessageResponse(String.format("Successfully set %s in %s %s service",
instance.id().toShortString(), zone, inService ? "in" : "out of"));
}
/** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */
private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
var status = inService ? GlobalRouting.Status.in : GlobalRouting.Status.out;
controller.routing().policies().setGlobalRoutingStatus(deployment, status, agent);
}
/** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */
private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var requestData = toSlime(request.getData()).get();
var reason = mandatory("reason", requestData).asString();
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
long timestamp = controller.clock().instant().getEpochSecond();
var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp);
controller.routing().setGlobalRotationStatus(deployment, endpointStatus);
}
private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Slime slime = new Slime();
Cursor array = slime.setObject().setArray("globalrotationoverride");
controller.routing().globalRotationStatus(deploymentId)
.forEach((endpoint, status) -> {
array.addString(endpoint.upstreamIdOf(deploymentId));
Cursor statusObject = array.addObject();
statusObject.setString("status", status.getStatus().name());
statusObject.setString("reason", status.getReason() == null ? "" : status.getReason());
statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent());
statusObject.setLong("timestamp", status.getEpoch());
});
return new SlimeJsonResponse(slime);
}
private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().requireInstance(applicationId);
ZoneId zone = ZoneId.from(environment, region);
RotationId rotation = findRotationId(instance, endpointId);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
Slime slime = new Slime();
Cursor response = slime.setObject();
toSlime(instance.rotationStatus().of(rotation, deployment), response);
return new SlimeJsonResponse(slime);
}
private HttpResponse metering(String tenant, String application, HttpRequest request) {
Slime slime = new Slime();
Cursor root = slime.setObject();
MeteringData meteringData = controller.serviceRegistry()
.meteringService()
.getMeteringData(TenantName.from(tenant), ApplicationName.from(application));
ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringData.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringData.getLastMonth();
Cursor lastmonth = root.setObject("lastmonth");
lastmonth.setDouble("cpu", lastMonth.getCpuCores());
lastmonth.setDouble("mem", lastMonth.getMemoryGb());
lastmonth.setDouble("disk", lastMonth.getDiskGb());
Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory();
Cursor details = root.setObject("details");
Cursor detailsCpu = details.setObject("cpu");
Cursor detailsMem = details.setObject("mem");
Cursor detailsDisk = details.setObject("disk");
history.entrySet().stream()
.forEach(entry -> {
String instanceName = entry.getKey().instance().value();
Cursor detailsCpuApp = detailsCpu.setObject(instanceName);
Cursor detailsMemApp = detailsMem.setObject(instanceName);
Cursor detailsDiskApp = detailsDisk.setObject(instanceName);
Cursor detailsCpuData = detailsCpuApp.setArray("data");
Cursor detailsMemData = detailsMemApp.setArray("data");
Cursor detailsDiskData = detailsDiskApp.setArray("data");
entry.getValue().stream()
.forEach(resourceSnapshot -> {
Cursor cpu = detailsCpuData.addObject();
cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
cpu.setDouble("value", resourceSnapshot.getCpuCores());
Cursor mem = detailsMemData.addObject();
mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
mem.setDouble("value", resourceSnapshot.getMemoryGb());
Cursor disk = detailsDiskData.addObject();
disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
disk.setDouble("value", resourceSnapshot.getDiskGb());
});
});
return new SlimeJsonResponse(slime);
}
private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! instance.change().isEmpty()) {
instance.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", instance.change().isPinned());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
boolean suspended = controller.applications().isSuspended(deploymentId);
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setBool("suspended", suspended);
return new SlimeJsonResponse(slime);
}
private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region);
ServiceApiResponse response = new ServiceApiResponse(ZoneId.from(environment, region),
new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(),
controller.zoneRegistry().getConfigServerApiUris(ZoneId.from(environment, region)),
request.getUri());
response.setResponse(applicationView);
return response;
}
private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), ZoneId.from(environment, region));
if ("container-clustercontroller".equals((serviceName)) && restPath.contains("/status/")) {
String result = controller.serviceRegistry().configServer().getClusterControllerStatus(deploymentId, restPath);
return new HtmlResponse(result);
}
Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath);
ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(),
deploymentId.applicationId(),
controller.zoneRegistry().getConfigServerApiUris(deploymentId.zoneId()),
request.getUri());
response.setResponse(result, serviceName, restPath);
return response;
}
private HttpResponse updateTenant(String tenantName, HttpRequest request) {
getTenantOrThrow(tenantName);
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().update(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createTenant(String tenantName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().create(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest());
com.yahoo.vespa.hosted.controller.Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
if (controller.applications().getApplication(applicationId).isEmpty())
createApplication(tenantName, applicationName, request);
controller.applications().createInstance(applicationId.instance(instanceName));
Slime slime = new Slime();
toSlime(applicationId.instance(instanceName), slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
/** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */
private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) {
request = controller.auditLogger().log(request);
String versionString = readToString(request.getData());
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Version version = Version.fromString(versionString);
if (version.equals(Version.emptyVersion))
version = controller.systemVersion();
if ( ! systemHasVersion(version))
throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " +
"Version is not active in this system. " +
"Active versions: " + controller.versionStatus().versions()
.stream()
.map(VespaVersion::versionNumber)
.map(Version::toString)
.collect(joining(", ")));
Change change = Change.of(version);
if (pin)
change = change.withPin();
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Trigger deployment to the last known application package for the given application. */
private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) {
controller.auditLogger().log(request);
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */
private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = application.get().require(id.instance()).change();
if (change.isEmpty()) {
response.append("No deployment in progress for ").append(id).append(" at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Schedule restart of deployment, or specific host in a deployment */
private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Optional<Hostname> hostname = Optional.ofNullable(request.getProperty("hostname")).map(Hostname::new);
controller.applications().restart(deploymentId, hostname);
return new MessageResponse("Requested restart of " + deploymentId);
}
private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) {
if ( ! type.environment().isManuallyDeployed() && ! isOperator(request))
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("applicationZip"))
throw new IllegalArgumentException("Missing required form part 'applicationZip'");
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(id.tenant(),
Optional.of(id.instance()),
Optional.of(type.zone(controller.system())),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions"))
.map(json -> SlimeUtils.jsonToSlime(json).get())
.flatMap(options -> optional("vespaVersion", options))
.map(Version::fromString);
controller.jobController().deploy(id, type, version, applicationPackage);
RunId runId = controller.jobController().last(id, type).get().id();
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("message", "Deployment started in " + runId +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<com.yahoo.vespa.hosted.controller.Application> application = controller.applications().getApplication(TenantAndApplicationId.from(applicationId));
Inspector sourceRevision = deployOptions.field("sourceRevision");
Inspector buildNumber = deployOptions.field("buildNumber");
if (sourceRevision.valid() != buildNumber.valid())
throw new IllegalArgumentException("Source revision and build number must both be provided, or not");
Optional<ApplicationVersion> applicationVersion = Optional.empty();
if (sourceRevision.valid()) {
if (applicationPackage.isPresent())
throw new IllegalArgumentException("Application version and application package can't both be provided.");
applicationVersion = Optional.of(ApplicationVersion.from(toSourceRevision(sourceRevision),
buildNumber.asLong()));
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
boolean deployDirectly = deployOptions.field("deployDirectly").asBool();
Optional<Version> vespaVersion = optional("vespaVersion", deployOptions).map(Version::new);
if (deployDirectly && applicationPackage.isEmpty() && applicationVersion.isEmpty() && vespaVersion.isEmpty()) {
Optional<Deployment> deployment = controller.applications().getInstance(applicationId)
.map(Instance::deployments)
.flatMap(deployments -> Optional.ofNullable(deployments.get(zone)));
if(deployment.isEmpty())
throw new IllegalArgumentException("Can't redeploy application, no deployment currently exist");
ApplicationVersion version = deployment.get().applicationVersion();
if(version.isUnknown())
throw new IllegalArgumentException("Can't redeploy application, application version is unknown");
applicationVersion = Optional.of(version);
vespaVersion = Optional.of(deployment.get().version());
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
Optional.of(applicationId.instance()),
Optional.of(zone),
aPackage,
Optional.of(requireUserPrincipal(request))));
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass);
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if (tenant.isEmpty())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
controller.tenants().delete(tenant.get().name(),
accessControlRequests.credentials(tenant.get().name(),
toSlime(request.getData()).get(),
request.getJDiscRequest()));
return tenant(tenant.get(), request);
}
private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
return new MessageResponse("Deleted application " + id);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty()) {
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
}
return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
controller.applications().deactivate(id.applicationId(), id.zoneId());
return new MessageResponse("Deactivated " + id);
}
/** Returns test config for indicated job, with production deployments of the default instance. */
private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
HashSet<DeploymentId> deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toCollection(HashSet::new));
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.routing().zoneEndpointsOf(deployments),
controller.applications().contentClustersByZone(deployments)));
}
private static SourceRevision toSourceRevision(Inspector object) {
if (!object.field("repository").valid() ||
!object.field("branch").valid() ||
!object.field("commit").valid()) {
throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\".");
}
return new SourceRevision(object.field("repository").asString(),
object.field("branch").asString(),
object.field("commit").asString());
}
private Tenant getTenantOrThrow(String tenantName) {
return controller.tenants().get(tenantName)
.orElseThrow(() -> new NotExistsException(new TenantId(tenantName)));
}
private void toSlime(Cursor object, Tenant tenant, HttpRequest request) {
object.setString("tenant", tenant.name().value());
object.setString("type", tenantType(tenant));
List<com.yahoo.vespa.hosted.controller.Application> applications = controller.applications().asList(tenant.name());
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
object.setString("athensDomain", athenzTenant.domain().getName());
object.setString("property", athenzTenant.property().id());
athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString()));
athenzTenant.contact().ifPresent(c -> {
object.setString("propertyUrl", c.propertyUrl().toString());
object.setString("contactsUrl", c.url().toString());
object.setString("issueCreationUrl", c.issueTrackerUrl().toString());
Cursor contactsArray = object.setArray("contacts");
c.persons().forEach(persons -> {
Cursor personArray = contactsArray.addArray();
persons.forEach(personArray::addString);
});
});
break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys");
cloudTenant.developerKeys().forEach((key, user) -> {
Cursor keyObject = pemDeveloperKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", user.getName());
});
break;
}
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
Cursor applicationArray = object.setArray("applications");
for (com.yahoo.vespa.hosted.controller.Application application : applications) {
DeploymentStatus status = controller.jobController().deploymentStatus(application);
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, status, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
}
private void toSlime(ClusterResources resources, Cursor object) {
object.setLong("nodes", resources.nodes());
object.setLong("groups", resources.groups());
toSlime(resources.nodeResources(), object.setObject("nodeResources"));
if ( ! controller.zoneRegistry().system().isPublic())
object.setDouble("cost", Math.round(resources.nodes() * resources.nodeResources().cost() * 100.0 / 3.0) / 100.0);
}
private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", valueOf(resources.diskSpeed()));
object.setString("storageType", valueOf(resources.storageType()));
}
private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) {
object.setString("tenant", tenant.name().value());
Cursor metaData = object.setObject("metaData");
metaData.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
metaData.setString("athensDomain", athenzTenant.domain().getName());
metaData.setString("property", athenzTenant.property().id());
break;
case cloud: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString());
}
/** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */
private URI withPath(String newPath, URI uri) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, null, null);
}
catch (URISyntaxException e) {
throw new RuntimeException("Will not happen", e);
}
}
private long asLong(String valueOrNull, long defaultWhenNull) {
if (valueOrNull == null) return defaultWhenNull;
try {
return Long.parseLong(valueOrNull);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'");
}
}
private void toSlime(Run run, Cursor object) {
object.setLong("id", run.id().number());
object.setString("version", run.versions().targetPlatform().toFullString());
if ( ! run.versions().targetApplication().isUnknown())
toSlime(run.versions().targetApplication(), object.setObject("revision"));
object.setString("reason", "unknown reason");
object.setLong("at", run.end().orElse(run.start()).toEpochMilli());
}
private Slime toSlime(InputStream jsonStream) {
try {
byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000);
return SlimeUtils.jsonToSlime(jsonBytes);
} catch (IOException e) {
throw new RuntimeException();
}
}
private static Principal requireUserPrincipal(HttpRequest request) {
Principal principal = request.getJDiscRequest().getUserPrincipal();
if (principal == null) throw new InternalServerErrorException("Expected a user principal");
return principal;
}
private Inspector mandatory(String key, Inspector object) {
if ( ! object.field(key).valid())
throw new IllegalArgumentException("'" + key + "' is missing");
return object.field(key);
}
private Optional<String> optional(String key, Inspector object) {
return SlimeUtils.optionalString(object.field(key));
}
private static String path(Object... elements) {
return Joiner.on("/").join(elements);
}
private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value(),
request.getUri()).toString());
}
private void toSlime(ApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value() +
"/instance/" + id.instance().value(),
request.getUri()).toString());
}
private Slime toSlime(ActivateResult result) {
Slime slime = new Slime();
Cursor object = slime.setObject();
object.setString("revisionId", result.revisionId().id());
object.setLong("applicationZipSize", result.applicationZipSizeBytes());
Cursor logArray = object.setArray("prepareMessages");
if (result.prepareResponse().log != null) {
for (Log logMessage : result.prepareResponse().log) {
Cursor logObject = logArray.addObject();
logObject.setLong("time", logMessage.time);
logObject.setString("level", logMessage.level);
logObject.setString("message", logMessage.message);
}
}
Cursor changeObject = object.setObject("configChangeActions");
Cursor restartActionsArray = changeObject.setArray("restart");
for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) {
Cursor restartActionObject = restartActionsArray.addObject();
restartActionObject.setString("clusterName", restartAction.clusterName);
restartActionObject.setString("clusterType", restartAction.clusterType);
restartActionObject.setString("serviceType", restartAction.serviceType);
serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services"));
stringsToSlime(restartAction.messages, restartActionObject.setArray("messages"));
}
Cursor refeedActionsArray = changeObject.setArray("refeed");
for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) {
Cursor refeedActionObject = refeedActionsArray.addObject();
refeedActionObject.setString("name", refeedAction.name);
refeedActionObject.setBool("allowed", refeedAction.allowed);
refeedActionObject.setString("documentType", refeedAction.documentType);
refeedActionObject.setString("clusterName", refeedAction.clusterName);
serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services"));
stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages"));
}
return slime;
}
private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) {
for (ServiceInfo serviceInfo : serviceInfoList) {
Cursor serviceInfoObject = array.addObject();
serviceInfoObject.setString("serviceName", serviceInfo.serviceName);
serviceInfoObject.setString("serviceType", serviceInfo.serviceType);
serviceInfoObject.setString("configId", serviceInfo.configId);
serviceInfoObject.setString("hostName", serviceInfo.hostName);
}
}
private void stringsToSlime(List<String> strings, Cursor array) {
for (String string : strings)
array.addString(string);
}
private String readToString(InputStream stream) {
Scanner scanner = new Scanner(stream).useDelimiter("\\A");
if ( ! scanner.hasNext()) return null;
return scanner.next();
}
private boolean systemHasVersion(Version version) {
return controller.versionStatus().versions().stream().anyMatch(v -> v.versionNumber().equals(version));
}
private static boolean recurseOverTenants(HttpRequest request) {
return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive"));
}
private static boolean recurseOverApplications(HttpRequest request) {
return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive"));
}
private static boolean recurseOverDeployments(HttpRequest request) {
return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive"));
}
private static boolean showOnlyProductionInstances(HttpRequest request) {
return "true".equals(request.getProperty("production"));
}
private static String tenantType(Tenant tenant) {
switch (tenant.type()) {
case athenz: return "ATHENS";
case cloud: return "CLOUD";
default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName());
}
}
private static ApplicationId appIdFromPath(Path path) {
return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance"));
}
private static JobType jobTypeFromPath(Path path) {
return JobType.fromJobName(path.get("jobtype"));
}
private static RunId runIdFromPath(Path path) {
long number = Long.parseLong(path.get("number"));
return new RunId(appIdFromPath(path), jobTypeFromPath(path), number);
}
private HttpResponse submit(String tenant, String application, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
Optional<String> repository = optional("repository", submitOptions);
Optional<String> branch = optional("branch", submitOptions);
Optional<String> commit = optional("commit", submitOptions);
Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent()
? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get()))
: Optional.empty();
Optional<String> sourceUrl = optional("sourceUrl", submitOptions);
Optional<String> authorEmail = optional("authorEmail", submitOptions);
sourceUrl.map(URI::create).ifPresent(url -> {
if (url.getHost() == null || url.getScheme() == null)
throw new IllegalArgumentException("Source URL must include scheme and host");
});
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true);
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
Optional.empty(),
Optional.empty(),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
sourceUrl,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
private HttpResponse removeProdAllDeployments(String tenant, String application) {
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application,
Optional.empty(), Optional.empty(), Optional.empty(), 1,
ApplicationPackage.createEmptyForDeploymentRemoval(), new byte[0]);
}
private static Map<String, byte[]> parseDataParts(HttpRequest request) {
String contentHash = request.getHeader("x-Content-Hash");
if (contentHash == null)
return new MultipartParser().parse(request);
DigestInputStream digester = Signatures.sha256Digester(request.getData());
var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri());
if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash)))
throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash");
return dataParts;
}
private static RotationId findRotationId(Instance instance, Optional<String> endpointId) {
if (instance.rotations().isEmpty()) {
throw new NotExistsException("global rotation does not exist for " + instance);
}
if (endpointId.isPresent()) {
return instance.rotations().stream()
.filter(r -> r.endpointId().id().equals(endpointId.get()))
.map(AssignedRotation::rotationId)
.findFirst()
.orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() +
" does not exist for " + instance));
} else if (instance.rotations().size() > 1) {
throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given");
}
return instance.rotations().get(0).rotationId();
}
private static String rotationStateString(RotationState state) {
switch (state) {
case in: return "IN";
case out: return "OUT";
}
return "UNKNOWN";
}
private static String endpointScopeString(Endpoint.Scope scope) {
switch (scope) {
case global: return "global";
case zone: return "zone";
}
throw new IllegalArgumentException("Unknown endpoint scope " + scope);
}
private static String routingMethodString(RoutingMethod method) {
switch (method) {
case exclusive: return "exclusive";
case shared: return "shared";
case sharedLayer4: return "sharedLayer4";
}
throw new IllegalArgumentException("Unknown routing method " + method);
}
private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) {
return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName))
.filter(cls::isInstance)
.map(cls::cast)
.orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request"));
}
/** Returns whether given request is by an operator */
private static boolean isOperator(HttpRequest request) {
var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class);
return securityContext.roles().stream()
.map(Role::definition)
.anyMatch(definition -> definition == RoleDefinition.hostedOperator);
}
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestConfigSerializer testConfigSerializer;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
}
@Override
public Duration getTimeout() {
return Duration.ofMinutes(20);
}
@Override
public HttpResponse handle(HttpRequest request) {
try {
Path path = new Path(request.getUri(), OPTIONAL_PREFIX);
switch (request.getMethod()) {
case GET: return handleGET(path, request);
case PUT: return handlePUT(path, request);
case POST: return handlePOST(path, request);
case PATCH: return handlePATCH(path, request);
case DELETE: return handleDELETE(path, request);
case OPTIONS: return handleOPTIONS();
default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
}
}
catch (ForbiddenException e) {
return ErrorResponse.forbidden(Exceptions.toMessageString(e));
}
catch (NotAuthorizedException e) {
return ErrorResponse.unauthorized(Exceptions.toMessageString(e));
}
catch (NotExistsException e) {
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
}
catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
catch (ConfigServerException e) {
switch (e.getErrorCode()) {
case NOT_FOUND:
return new ErrorResponse(NOT_FOUND, e.getErrorCode().name(), Exceptions.toMessageString(e));
case ACTIVATION_CONFLICT:
return new ErrorResponse(CONFLICT, e.getErrorCode().name(), Exceptions.toMessageString(e));
case INTERNAL_SERVER_ERROR:
return new ErrorResponse(INTERNAL_SERVER_ERROR, e.getErrorCode().name(), Exceptions.toMessageString(e));
default:
return new ErrorResponse(BAD_REQUEST, e.getErrorCode().name(), Exceptions.toMessageString(e));
}
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/tenant")) return tenants(request);
if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePUT(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePATCH(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleOPTIONS() {
EmptyResponse response = new EmptyResponse();
response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS");
return response;
}
private HttpResponse recursiveRoot(HttpRequest request) {
Slime slime = new Slime();
Cursor tenantArray = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
toSlime(tenantArray.addObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse root(HttpRequest request) {
return recurseOverTenants(request)
? recursiveRoot(request)
: new ResourceResponse(request, "tenant");
}
private HttpResponse tenants(HttpRequest request) {
Slime slime = new Slime();
Cursor response = slime.setArray();
for (Tenant tenant : controller.tenants().asList())
tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject());
return new SlimeJsonResponse(slime);
}
private HttpResponse tenant(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenant(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenant(Tenant tenant, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), tenant, request);
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
if (controller.tenants().get(tenantName).isEmpty())
return ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist");
Slime slime = new Slime();
Cursor applicationArray = slime.setArray();
for (com.yahoo.vespa.hosted.controller.Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true)) {
Cursor applicationObject = applicationArray.addObject();
applicationObject.setString("tenant", application.id().tenant().value());
applicationObject.setString("application", application.id().application().value());
applicationObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value(),
request.getUri()).toString());
Cursor instanceArray = applicationObject.setArray("instances");
for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet()
: application.instances().keySet()) {
Cursor instanceObject = instanceArray.addObject();
instanceObject.setString("instance", instance.value());
instanceObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/instance/" + instance.value(),
request.getUri()).toString());
}
}
}
return new SlimeJsonResponse(slime);
}
private HttpResponse devApplicationPackage(ApplicationId id, JobType type) {
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Only manually deployed zones have dev packages");
ZoneId zone = type.zone(controller.system());
byte[] applicationPackage = controller.applications().applicationStore().getDev(id, zone);
return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage);
}
private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse compileVersion(String tenantName, String applicationName) {
Slime slime = new Slime();
slime.setObject().setString("compileVersion",
compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString());
return new SlimeJsonResponse(slime);
}
private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
Principal user = request.getJDiscRequest().getUserPrincipal();
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withDeveloperKey(developerKey, user);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Principal user = ((CloudTenant) controller.tenants().require(TenantName.from(tenantName))).developerKeys().get(developerKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withoutDeveloperKey(developerKey);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) {
keys.forEach((key, principal) -> {
Cursor keyObject = keysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", principal.getName());
});
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withoutDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes.");
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
Inspector majorVersionField = requestObject.field("majorVersion");
if (majorVersionField.valid()) {
Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong();
application = application.withMajorVersion(majorVersion);
messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion));
}
Inspector pemDeployKeyField = requestObject.field("pemDeployKey");
if (pemDeployKeyField.valid()) {
String pemDeployKey = pemDeployKeyField.asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
application = application.withDeployKey(deployKey);
messageBuilder.add("Added deploy key " + pemDeployKey);
}
controller.applications().store(application);
});
return new MessageResponse(messageBuilder.toString());
}
private com.yahoo.vespa.hosted.controller.Application getApplication(String tenantName, String applicationName) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
return controller.applications().getApplication(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private Instance getInstance(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
return controller.applications().getInstance(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, id);
Slime slime = new Slime();
Cursor nodesArray = slime.setObject().setArray("nodes");
for (Node node : nodes) {
Cursor nodeObject = nodesArray.addObject();
nodeObject.setString("hostname", node.hostname().value());
nodeObject.setString("state", valueOf(node.state()));
node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.flavor());
toSlime(node.resources(), nodeObject);
nodeObject.setBool("fastDisk", node.resources().diskSpeed() == NodeResources.DiskSpeed.fast);
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
return new SlimeJsonResponse(slime);
}
private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id);
Slime slime = new Slime();
Cursor clustersObject = slime.setObject().setObject("clusters");
for (Cluster cluster : application.clusters().values()) {
Cursor clusterObject = clustersObject.setObject(cluster.id().value());
toSlime(cluster.min(), clusterObject.setObject("min"));
toSlime(cluster.max(), clusterObject.setObject("max"));
toSlime(cluster.current(), clusterObject.setObject("current"));
cluster.target().ifPresent(target -> toSlime(target, clusterObject.setObject("target")));
cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested")));
}
return new SlimeJsonResponse(slime);
}
private static String valueOf(Node.State state) {
switch (state) {
case failed: return "failed";
case parked: return "parked";
case dirty: return "dirty";
case ready: return "ready";
case active: return "active";
case inactive: return "inactive";
case reserved: return "reserved";
case provisioned: return "provisioned";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ServiceState state) {
switch (state) {
case expectedUp: return "expectedUp";
case allowedDown: return "allowedDown";
case unorchestrated: return "unorchestrated";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
private static String valueOf(Node.ClusterType type) {
switch (type) {
case admin: return "admin";
case content: return "content";
case container: return "container";
case combined: return "combined";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
private static String valueOf(NodeResources.DiskSpeed diskSpeed) {
switch (diskSpeed) {
case fast : return "fast";
case slow : return "slow";
case any : return "any";
default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'");
}
}
private static String valueOf(NodeResources.StorageType storageType) {
switch (storageType) {
case remote : return "remote";
case local : return "local";
case any : return "any";
default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'");
}
}
private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters);
return new HttpResponse(200) {
@Override
public void render(OutputStream outputStream) throws IOException {
logStream.transferTo(outputStream);
}
};
}
private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
boolean requireTests = ! requestObject.field("skipTests").asBool();
boolean reTrigger = requestObject.field("reTrigger").asBool();
String triggered = reTrigger
? controller.applications().deploymentTrigger()
.reTrigger(id, type).type().jobName()
: controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests)
.stream().map(job -> job.type().jobName()).collect(joining(", "));
return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered"
: "Triggered " + triggered + " for " + id);
}
private HttpResponse pause(ApplicationId id, JobType type) {
Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause);
controller.applications().deploymentTrigger().pauseJob(id, type, until);
return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause);
}
private HttpResponse resume(ApplicationId id, JobType type) {
controller.applications().deploymentTrigger().resumeJob(id, type);
return new MessageResponse(type.jobName() + " for " + id + " resumed");
}
private void toSlime(Cursor object, com.yahoo.vespa.hosted.controller.Application application, HttpRequest request) {
object.setString("tenant", application.id().tenant().value());
object.setString("application", application.id().application().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/job/",
request.getUri()).toString());
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
application.instances().values().stream().findFirst().ifPresent(instance -> {
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
});
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request);
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
if (deploymentSpec.instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec.requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
globalEndpointsToSlime(object, instance);
List<Deployment> deployments = deploymentSpec.instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor deploymentsArray = object.setArray("deployments");
for (Deployment deployment : deployments) {
Cursor deploymentObject = deploymentsArray.addObject();
if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty())
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/instance/" + instance.name().value() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
}
private void globalEndpointsToSlime(Cursor object, Instance instance) {
var globalEndpointUrls = new LinkedHashSet<String>();
controller.routing().endpointsOf(instance.id())
.requiresRotation()
.not().legacy()
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalEndpointUrls::add);
var globalRotationsArray = object.setArray("globalRotations");
globalEndpointUrls.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
}
private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) {
com.yahoo.vespa.hosted.controller.Application application = status.application();
object.setString("tenant", instance.id().tenant().value());
object.setString("application", instance.id().application().value());
object.setString("instance", instance.id().instance().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + instance.id().tenant().value() +
"/application/" + instance.id().application().value() +
"/instance/" + instance.id().instance().value() + "/job/",
request.getUri()).toString());
application.latestVersion().ifPresent(version -> {
sourceRevisionToSlime(version.source(), object.setObject("source"));
version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
version.commit().ifPresent(commit -> object.setString("commit", commit));
});
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if (application.deploymentSpec().instance(instance.name()).isPresent()) {
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec().requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
globalEndpointsToSlime(object, instance);
List<Deployment> deployments =
application.deploymentSpec().instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor instancesArray = object.setArray("instances");
for (Deployment deployment : deployments) {
Cursor deploymentObject = instancesArray.addObject();
if (deployment.zone().environment() == Environment.prod) {
if (instance.rotations().size() == 1) {
toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment),
deploymentObject);
}
if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) {
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
}
}
if (recurseOverDeployments(request))
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("instance", instance.id().instance().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
status.jobSteps().keySet().stream()
.filter(job -> job.application().instance().equals(instance.name()))
.filter(job -> job.type().isProduction() && job.type().isDeployment())
.map(job -> job.type().zone(controller.system()))
.filter(zone -> ! instance.deployments().containsKey(zone))
.forEach(zone -> {
Cursor deploymentObject = instancesArray.addObject();
deploymentObject.setString("environment", zone.environment().value());
deploymentObject.setString("region", zone.region().value());
});
application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key)));
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().getInstance(id)
.orElseThrow(() -> new NotExistsException(id + " not found"));
DeploymentId deploymentId = new DeploymentId(instance.id(),
ZoneId.from(environment, region));
Deployment deployment = instance.deployments().get(deploymentId.zoneId());
if (deployment == null)
throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId());
Slime slime = new Slime();
toSlime(slime.setObject(), deploymentId, deployment, request);
return new SlimeJsonResponse(slime);
}
private void toSlime(Cursor object, Change change) {
change.platform().ifPresent(version -> object.setString("version", version.toString()));
change.application()
.filter(version -> !version.isUnknown())
.ifPresent(version -> toSlime(version, object.setObject("revision")));
}
private void toSlime(Endpoint endpoint, String cluster, Cursor object) {
object.setString("cluster", cluster);
object.setBool("tls", endpoint.tls());
object.setString("url", endpoint.url().toString());
object.setString("scope", endpointScopeString(endpoint.scope()));
object.setString("routingMethod", routingMethodString(endpoint.routingMethod()));
}
private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) {
response.setString("tenant", deploymentId.applicationId().tenant().value());
response.setString("application", deploymentId.applicationId().application().value());
response.setString("instance", deploymentId.applicationId().instance().value());
response.setString("environment", deploymentId.zoneId().environment().value());
response.setString("region", deploymentId.zoneId().region().value());
var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId()));
var endpointArray = response.setArray("endpoints");
for (var endpoint : controller.routing().endpointsOf(deploymentId)
.scope(Endpoint.Scope.zone)
.not().legacy()) {
toSlime(endpoint, endpoint.name(), endpointArray.addObject());
}
var globalEndpoints = controller.routing().endpointsOf(application, deploymentId.applicationId().instance())
.not().legacy()
.targets(deploymentId.zoneId());
for (var endpoint : globalEndpoints) {
toSlime(endpoint, endpoint.cluster().value(), endpointArray.addObject());
}
response.setString("nodes", withPath("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/?&recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString());
response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString());
response.setString("version", deployment.version().toFullString());
response.setString("revision", deployment.applicationVersion().id());
response.setLong("deployTimeEpochMs", deployment.at().toEpochMilli());
controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId())
.ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", deployment.at().plus(deploymentTimeToLive).toEpochMilli()));
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
var instance = application.instances().get(deploymentId.applicationId().instance());
if (instance != null) {
if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod)
toSlime(instance.rotations(), instance.rotationStatus(), deployment, response);
JobType.from(controller.system(), deployment.zone())
.map(type -> new JobId(instance.id(), type))
.map(status.jobSteps()::get)
.ifPresent(stepStatus -> {
JobControllerApiHandlerHelper.applicationVersionToSlime(
response.setObject("applicationVersion"), deployment.applicationVersion());
if (!status.jobsToRun().containsKey(stepStatus.job().get()))
response.setString("status", "complete");
else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true))
response.setString("status", "pending");
else response.setString("status", "running");
});
}
Cursor activity = response.setObject("activity");
deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried",
instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten",
instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
DeploymentMetrics metrics = deployment.metrics();
Cursor metricsObject = response.setObject("metrics");
metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond());
metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond());
metricsObject.setDouble("documentCount", metrics.documentCount());
metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis());
metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli()));
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if ( ! applicationVersion.isUnknown()) {
object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong());
object.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if (revision.isEmpty()) return;
object.setString("gitRepository", revision.get().repository());
object.setString("gitBranch", revision.get().branch());
object.setString("gitCommit", revision.get().commit());
}
private void toSlime(RotationState state, Cursor object) {
Cursor bcpStatus = object.setObject("bcpStatus");
bcpStatus.setString("rotationStatus", rotationStateString(state));
}
private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) {
var array = object.setArray("endpointStatus");
for (var rotation : rotations) {
var statusObject = array.addObject();
var targets = status.of(rotation.rotationId());
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("rotationId", rotation.rotationId().asString());
statusObject.setString("clusterId", rotation.clusterId().value());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli());
}
}
private URI monitoringSystemUri(DeploymentId deploymentId) {
return controller.zoneRegistry().getMonitoringSystemUri(deploymentId);
}
/**
* Returns a non-broken, released version at least as old as the oldest platform the given application is on.
*
* If no known version is applicable, the newest version at least as old as the oldest platform is selected,
* among all versions released for this system. If no such versions exists, throws an IllegalStateException.
*/
private Version compileVersion(TenantAndApplicationId id) {
Version oldestPlatform = controller.applications().oldestInstalledPlatform(id);
VersionStatus versionStatus = controller.versionStatus();
return versionStatus.versions().stream()
.filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low))
.filter(VespaVersion::isReleased)
.map(VespaVersion::versionNumber)
.filter(version -> ! version.isAfter(oldestPlatform))
.max(Comparator.naturalOrder())
.orElseGet(() -> controller.mavenRepository().metadata().versions().stream()
.filter(version -> ! version.isAfter(oldestPlatform))
.filter(version -> ! versionStatus.versions().stream()
.map(VespaVersion::versionNumber)
.collect(Collectors.toSet()).contains(version))
.max(Comparator.naturalOrder())
.orElseThrow(() -> new IllegalStateException("No available releases of " +
controller.mavenRepository().artifactId())));
}
private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
ZoneId zone = ZoneId.from(environment, region);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
var deploymentId = new DeploymentId(instance.id(), zone);
setGlobalRotationStatus(deploymentId, inService, request);
setGlobalEndpointStatus(deploymentId, inService, request);
return new MessageResponse(String.format("Successfully set %s in %s %s service",
instance.id().toShortString(), zone, inService ? "in" : "out of"));
}
/** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */
private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
var status = inService ? GlobalRouting.Status.in : GlobalRouting.Status.out;
controller.routing().policies().setGlobalRoutingStatus(deployment, status, agent);
}
/** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */
private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var requestData = toSlime(request.getData()).get();
var reason = mandatory("reason", requestData).asString();
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
long timestamp = controller.clock().instant().getEpochSecond();
var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp);
controller.routing().setGlobalRotationStatus(deployment, endpointStatus);
}
private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Slime slime = new Slime();
Cursor array = slime.setObject().setArray("globalrotationoverride");
controller.routing().globalRotationStatus(deploymentId)
.forEach((endpoint, status) -> {
array.addString(endpoint.upstreamIdOf(deploymentId));
Cursor statusObject = array.addObject();
statusObject.setString("status", status.getStatus().name());
statusObject.setString("reason", status.getReason() == null ? "" : status.getReason());
statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent());
statusObject.setLong("timestamp", status.getEpoch());
});
return new SlimeJsonResponse(slime);
}
private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().requireInstance(applicationId);
ZoneId zone = ZoneId.from(environment, region);
RotationId rotation = findRotationId(instance, endpointId);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
Slime slime = new Slime();
Cursor response = slime.setObject();
toSlime(instance.rotationStatus().of(rotation, deployment), response);
return new SlimeJsonResponse(slime);
}
private HttpResponse metering(String tenant, String application, HttpRequest request) {
Slime slime = new Slime();
Cursor root = slime.setObject();
MeteringData meteringData = controller.serviceRegistry()
.meteringService()
.getMeteringData(TenantName.from(tenant), ApplicationName.from(application));
ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringData.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringData.getLastMonth();
Cursor lastmonth = root.setObject("lastmonth");
lastmonth.setDouble("cpu", lastMonth.getCpuCores());
lastmonth.setDouble("mem", lastMonth.getMemoryGb());
lastmonth.setDouble("disk", lastMonth.getDiskGb());
Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory();
Cursor details = root.setObject("details");
Cursor detailsCpu = details.setObject("cpu");
Cursor detailsMem = details.setObject("mem");
Cursor detailsDisk = details.setObject("disk");
history.entrySet().stream()
.forEach(entry -> {
String instanceName = entry.getKey().instance().value();
Cursor detailsCpuApp = detailsCpu.setObject(instanceName);
Cursor detailsMemApp = detailsMem.setObject(instanceName);
Cursor detailsDiskApp = detailsDisk.setObject(instanceName);
Cursor detailsCpuData = detailsCpuApp.setArray("data");
Cursor detailsMemData = detailsMemApp.setArray("data");
Cursor detailsDiskData = detailsDiskApp.setArray("data");
entry.getValue().stream()
.forEach(resourceSnapshot -> {
Cursor cpu = detailsCpuData.addObject();
cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
cpu.setDouble("value", resourceSnapshot.getCpuCores());
Cursor mem = detailsMemData.addObject();
mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
mem.setDouble("value", resourceSnapshot.getMemoryGb());
Cursor disk = detailsDiskData.addObject();
disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
disk.setDouble("value", resourceSnapshot.getDiskGb());
});
});
return new SlimeJsonResponse(slime);
}
private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! instance.change().isEmpty()) {
instance.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", instance.change().isPinned());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
boolean suspended = controller.applications().isSuspended(deploymentId);
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setBool("suspended", suspended);
return new SlimeJsonResponse(slime);
}
private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region);
ServiceApiResponse response = new ServiceApiResponse(ZoneId.from(environment, region),
new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(),
controller.zoneRegistry().getConfigServerApiUris(ZoneId.from(environment, region)),
request.getUri());
response.setResponse(applicationView);
return response;
}
private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), ZoneId.from(environment, region));
if ("container-clustercontroller".equals((serviceName)) && restPath.contains("/status/")) {
String result = controller.serviceRegistry().configServer().getClusterControllerStatus(deploymentId, restPath);
return new HtmlResponse(result);
}
Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath);
ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(),
deploymentId.applicationId(),
controller.zoneRegistry().getConfigServerApiUris(deploymentId.zoneId()),
request.getUri());
response.setResponse(result, serviceName, restPath);
return response;
}
private HttpResponse updateTenant(String tenantName, HttpRequest request) {
getTenantOrThrow(tenantName);
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().update(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createTenant(String tenantName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().create(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest());
com.yahoo.vespa.hosted.controller.Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
if (controller.applications().getApplication(applicationId).isEmpty())
createApplication(tenantName, applicationName, request);
controller.applications().createInstance(applicationId.instance(instanceName));
Slime slime = new Slime();
toSlime(applicationId.instance(instanceName), slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
/** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */
private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) {
request = controller.auditLogger().log(request);
String versionString = readToString(request.getData());
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Version version = Version.fromString(versionString);
if (version.equals(Version.emptyVersion))
version = controller.systemVersion();
if ( ! systemHasVersion(version))
throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " +
"Version is not active in this system. " +
"Active versions: " + controller.versionStatus().versions()
.stream()
.map(VespaVersion::versionNumber)
.map(Version::toString)
.collect(joining(", ")));
Change change = Change.of(version);
if (pin)
change = change.withPin();
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Trigger deployment to the last known application package for the given application. */
private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) {
controller.auditLogger().log(request);
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */
private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = application.get().require(id.instance()).change();
if (change.isEmpty()) {
response.append("No deployment in progress for ").append(id).append(" at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Schedule restart of deployment, or specific host in a deployment */
private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
Optional<Hostname> hostname = Optional.ofNullable(request.getProperty("hostname")).map(Hostname::new);
controller.applications().restart(deploymentId, hostname);
return new MessageResponse("Requested restart of " + deploymentId);
}
private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) {
if ( ! type.environment().isManuallyDeployed() && ! isOperator(request))
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("applicationZip"))
throw new IllegalArgumentException("Missing required form part 'applicationZip'");
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(id.tenant(),
Optional.of(id.instance()),
Optional.of(type.zone(controller.system())),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions"))
.map(json -> SlimeUtils.jsonToSlime(json).get())
.flatMap(options -> optional("vespaVersion", options))
.map(Version::fromString);
controller.jobController().deploy(id, type, version, applicationPackage);
RunId runId = controller.jobController().last(id, type).get().id();
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("message", "Deployment started in " + runId +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<com.yahoo.vespa.hosted.controller.Application> application = controller.applications().getApplication(TenantAndApplicationId.from(applicationId));
Inspector sourceRevision = deployOptions.field("sourceRevision");
Inspector buildNumber = deployOptions.field("buildNumber");
if (sourceRevision.valid() != buildNumber.valid())
throw new IllegalArgumentException("Source revision and build number must both be provided, or not");
Optional<ApplicationVersion> applicationVersion = Optional.empty();
if (sourceRevision.valid()) {
if (applicationPackage.isPresent())
throw new IllegalArgumentException("Application version and application package can't both be provided.");
applicationVersion = Optional.of(ApplicationVersion.from(toSourceRevision(sourceRevision),
buildNumber.asLong()));
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
boolean deployDirectly = deployOptions.field("deployDirectly").asBool();
Optional<Version> vespaVersion = optional("vespaVersion", deployOptions).map(Version::new);
if (deployDirectly && applicationPackage.isEmpty() && applicationVersion.isEmpty() && vespaVersion.isEmpty()) {
Optional<Deployment> deployment = controller.applications().getInstance(applicationId)
.map(Instance::deployments)
.flatMap(deployments -> Optional.ofNullable(deployments.get(zone)));
if(deployment.isEmpty())
throw new IllegalArgumentException("Can't redeploy application, no deployment currently exist");
ApplicationVersion version = deployment.get().applicationVersion();
if(version.isUnknown())
throw new IllegalArgumentException("Can't redeploy application, application version is unknown");
applicationVersion = Optional.of(version);
vespaVersion = Optional.of(deployment.get().version());
applicationPackage = Optional.of(controller.applications().getApplicationPackage(applicationId,
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
Optional.of(applicationId.instance()),
Optional.of(zone),
aPackage,
Optional.of(requireUserPrincipal(request))));
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass);
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if (tenant.isEmpty())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
controller.tenants().delete(tenant.get().name(),
accessControlRequests.credentials(tenant.get().name(),
toSlime(request.getData()).get(),
request.getJDiscRequest()));
return tenant(tenant.get(), request);
}
private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
return new MessageResponse("Deleted application " + id);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty()) {
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
}
return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
ZoneId.from(environment, region));
controller.applications().deactivate(id.applicationId(), id.zoneId());
return new MessageResponse("Deactivated " + id);
}
/** Returns test config for indicated job, with production deployments of the default instance. */
private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
HashSet<DeploymentId> deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toCollection(HashSet::new));
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.routing().zoneEndpointsOf(deployments),
controller.applications().contentClustersByZone(deployments)));
}
private static SourceRevision toSourceRevision(Inspector object) {
if (!object.field("repository").valid() ||
!object.field("branch").valid() ||
!object.field("commit").valid()) {
throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\".");
}
return new SourceRevision(object.field("repository").asString(),
object.field("branch").asString(),
object.field("commit").asString());
}
private Tenant getTenantOrThrow(String tenantName) {
return controller.tenants().get(tenantName)
.orElseThrow(() -> new NotExistsException(new TenantId(tenantName)));
}
private void toSlime(Cursor object, Tenant tenant, HttpRequest request) {
object.setString("tenant", tenant.name().value());
object.setString("type", tenantType(tenant));
List<com.yahoo.vespa.hosted.controller.Application> applications = controller.applications().asList(tenant.name());
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
object.setString("athensDomain", athenzTenant.domain().getName());
object.setString("property", athenzTenant.property().id());
athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString()));
athenzTenant.contact().ifPresent(c -> {
object.setString("propertyUrl", c.propertyUrl().toString());
object.setString("contactsUrl", c.url().toString());
object.setString("issueCreationUrl", c.issueTrackerUrl().toString());
Cursor contactsArray = object.setArray("contacts");
c.persons().forEach(persons -> {
Cursor personArray = contactsArray.addArray();
persons.forEach(personArray::addString);
});
});
break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys");
cloudTenant.developerKeys().forEach((key, user) -> {
Cursor keyObject = pemDeveloperKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", user.getName());
});
break;
}
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
Cursor applicationArray = object.setArray("applications");
for (com.yahoo.vespa.hosted.controller.Application application : applications) {
DeploymentStatus status = controller.jobController().deploymentStatus(application);
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, status, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
}
private void toSlime(ClusterResources resources, Cursor object) {
object.setLong("nodes", resources.nodes());
object.setLong("groups", resources.groups());
toSlime(resources.nodeResources(), object.setObject("nodeResources"));
if ( ! controller.zoneRegistry().system().isPublic())
object.setDouble("cost", Math.round(resources.nodes() * resources.nodeResources().cost() * 100.0 / 3.0) / 100.0);
}
private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", valueOf(resources.diskSpeed()));
object.setString("storageType", valueOf(resources.storageType()));
}
private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) {
object.setString("tenant", tenant.name().value());
Cursor metaData = object.setObject("metaData");
metaData.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
metaData.setString("athensDomain", athenzTenant.domain().getName());
metaData.setString("property", athenzTenant.property().id());
break;
case cloud: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString());
}
/** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */
private URI withPath(String newPath, URI uri) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, null, null);
}
catch (URISyntaxException e) {
throw new RuntimeException("Will not happen", e);
}
}
private long asLong(String valueOrNull, long defaultWhenNull) {
if (valueOrNull == null) return defaultWhenNull;
try {
return Long.parseLong(valueOrNull);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'");
}
}
private void toSlime(Run run, Cursor object) {
object.setLong("id", run.id().number());
object.setString("version", run.versions().targetPlatform().toFullString());
if ( ! run.versions().targetApplication().isUnknown())
toSlime(run.versions().targetApplication(), object.setObject("revision"));
object.setString("reason", "unknown reason");
object.setLong("at", run.end().orElse(run.start()).toEpochMilli());
}
private Slime toSlime(InputStream jsonStream) {
try {
byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000);
return SlimeUtils.jsonToSlime(jsonBytes);
} catch (IOException e) {
throw new RuntimeException();
}
}
private static Principal requireUserPrincipal(HttpRequest request) {
Principal principal = request.getJDiscRequest().getUserPrincipal();
if (principal == null) throw new InternalServerErrorException("Expected a user principal");
return principal;
}
private Inspector mandatory(String key, Inspector object) {
if ( ! object.field(key).valid())
throw new IllegalArgumentException("'" + key + "' is missing");
return object.field(key);
}
private Optional<String> optional(String key, Inspector object) {
return SlimeUtils.optionalString(object.field(key));
}
private static String path(Object... elements) {
return Joiner.on("/").join(elements);
}
private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value(),
request.getUri()).toString());
}
private void toSlime(ApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value() +
"/instance/" + id.instance().value(),
request.getUri()).toString());
}
private Slime toSlime(ActivateResult result) {
Slime slime = new Slime();
Cursor object = slime.setObject();
object.setString("revisionId", result.revisionId().id());
object.setLong("applicationZipSize", result.applicationZipSizeBytes());
Cursor logArray = object.setArray("prepareMessages");
if (result.prepareResponse().log != null) {
for (Log logMessage : result.prepareResponse().log) {
Cursor logObject = logArray.addObject();
logObject.setLong("time", logMessage.time);
logObject.setString("level", logMessage.level);
logObject.setString("message", logMessage.message);
}
}
Cursor changeObject = object.setObject("configChangeActions");
Cursor restartActionsArray = changeObject.setArray("restart");
for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) {
Cursor restartActionObject = restartActionsArray.addObject();
restartActionObject.setString("clusterName", restartAction.clusterName);
restartActionObject.setString("clusterType", restartAction.clusterType);
restartActionObject.setString("serviceType", restartAction.serviceType);
serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services"));
stringsToSlime(restartAction.messages, restartActionObject.setArray("messages"));
}
Cursor refeedActionsArray = changeObject.setArray("refeed");
for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) {
Cursor refeedActionObject = refeedActionsArray.addObject();
refeedActionObject.setString("name", refeedAction.name);
refeedActionObject.setBool("allowed", refeedAction.allowed);
refeedActionObject.setString("documentType", refeedAction.documentType);
refeedActionObject.setString("clusterName", refeedAction.clusterName);
serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services"));
stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages"));
}
return slime;
}
private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) {
for (ServiceInfo serviceInfo : serviceInfoList) {
Cursor serviceInfoObject = array.addObject();
serviceInfoObject.setString("serviceName", serviceInfo.serviceName);
serviceInfoObject.setString("serviceType", serviceInfo.serviceType);
serviceInfoObject.setString("configId", serviceInfo.configId);
serviceInfoObject.setString("hostName", serviceInfo.hostName);
}
}
private void stringsToSlime(List<String> strings, Cursor array) {
for (String string : strings)
array.addString(string);
}
private String readToString(InputStream stream) {
Scanner scanner = new Scanner(stream).useDelimiter("\\A");
if ( ! scanner.hasNext()) return null;
return scanner.next();
}
private boolean systemHasVersion(Version version) {
return controller.versionStatus().versions().stream().anyMatch(v -> v.versionNumber().equals(version));
}
private static boolean recurseOverTenants(HttpRequest request) {
return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive"));
}
private static boolean recurseOverApplications(HttpRequest request) {
return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive"));
}
private static boolean recurseOverDeployments(HttpRequest request) {
return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive"));
}
private static boolean showOnlyProductionInstances(HttpRequest request) {
return "true".equals(request.getProperty("production"));
}
private static String tenantType(Tenant tenant) {
switch (tenant.type()) {
case athenz: return "ATHENS";
case cloud: return "CLOUD";
default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName());
}
}
private static ApplicationId appIdFromPath(Path path) {
return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance"));
}
private static JobType jobTypeFromPath(Path path) {
return JobType.fromJobName(path.get("jobtype"));
}
private static RunId runIdFromPath(Path path) {
long number = Long.parseLong(path.get("number"));
return new RunId(appIdFromPath(path), jobTypeFromPath(path), number);
}
private HttpResponse submit(String tenant, String application, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
Optional<String> repository = optional("repository", submitOptions);
Optional<String> branch = optional("branch", submitOptions);
Optional<String> commit = optional("commit", submitOptions);
Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent()
? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get()))
: Optional.empty();
Optional<String> sourceUrl = optional("sourceUrl", submitOptions);
Optional<String> authorEmail = optional("authorEmail", submitOptions);
sourceUrl.map(URI::create).ifPresent(url -> {
if (url.getHost() == null || url.getScheme() == null)
throw new IllegalArgumentException("Source URL must include scheme and host");
});
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true);
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
Optional.empty(),
Optional.empty(),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
sourceUrl,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
private HttpResponse removeAllProdDeployments(String tenant, String application) {
JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application,
Optional.empty(), Optional.empty(), Optional.empty(), 1,
ApplicationPackage.deploymentRemoval(), new byte[0]);
return new MessageResponse("All deployments removed");
}
private static Map<String, byte[]> parseDataParts(HttpRequest request) {
String contentHash = request.getHeader("x-Content-Hash");
if (contentHash == null)
return new MultipartParser().parse(request);
DigestInputStream digester = Signatures.sha256Digester(request.getData());
var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri());
if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash)))
throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash");
return dataParts;
}
private static RotationId findRotationId(Instance instance, Optional<String> endpointId) {
if (instance.rotations().isEmpty()) {
throw new NotExistsException("global rotation does not exist for " + instance);
}
if (endpointId.isPresent()) {
return instance.rotations().stream()
.filter(r -> r.endpointId().id().equals(endpointId.get()))
.map(AssignedRotation::rotationId)
.findFirst()
.orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() +
" does not exist for " + instance));
} else if (instance.rotations().size() > 1) {
throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given");
}
return instance.rotations().get(0).rotationId();
}
private static String rotationStateString(RotationState state) {
switch (state) {
case in: return "IN";
case out: return "OUT";
}
return "UNKNOWN";
}
private static String endpointScopeString(Endpoint.Scope scope) {
switch (scope) {
case global: return "global";
case zone: return "zone";
}
throw new IllegalArgumentException("Unknown endpoint scope " + scope);
}
private static String routingMethodString(RoutingMethod method) {
switch (method) {
case exclusive: return "exclusive";
case shared: return "shared";
case sharedLayer4: return "sharedLayer4";
}
throw new IllegalArgumentException("Unknown routing method " + method);
}
private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) {
return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName))
.filter(cls::isInstance)
.map(cls::cast)
.orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request"));
}
/** Returns whether given request is by an operator */
private static boolean isOperator(HttpRequest request) {
var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class);
return securityContext.roles().stream()
.map(Role::definition)
.anyMatch(definition -> definition == RoleDefinition.hostedOperator);
}
} |
Done | public void testRemovingAllDeployments() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 432L);
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
tester.controller().jobController().deploy(app.instanceId(), JobType.devUsEast1, Optional.empty(), applicationPackage);
assertEquals(Set.of(ZoneId.from("prod.us-west-1"), ZoneId.from("prod.us-east-3"), ZoneId.from("prod.eu-west-1"), ZoneId.from("dev.us-east-1")),
app.instance().deployments().keySet());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/deployment", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Application package version: 1.0.2-unknown\"}");
assertEquals(Set.of(ZoneId.from("dev.us-east-1")), app.instance().deployments().keySet());
} | "{\"message\":\"Application package version: 1.0.2-unknown\"}"); | public void testRemovingAllDeployments() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 432L);
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
tester.controller().jobController().deploy(app.instanceId(), JobType.devUsEast1, Optional.empty(), applicationPackage);
assertEquals(Set.of(ZoneId.from("prod.us-west-1"), ZoneId.from("prod.us-east-3"), ZoneId.from("prod.eu-west-1"), ZoneId.from("dev.us-east-1")),
app.instance().deployments().keySet());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/deployment", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"All deployments removed\"}");
assertEquals(Set.of(ZoneId.from("dev.us-east-1")), app.instance().deployments().keySet());
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private ContainerTester tester;
private DeploymentTester deploymentTester;
@Before
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().computeVersionStatus();
}
@Test
public void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
new File("root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("application-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("application-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.properties(Map.of("recursive", "true",
"production", "true")),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID)
.properties(Map.of("recursive", "true",
"production", "true")),
new File("application-without-instances.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
var app1 = deploymentTester.newDeploymentContext(id);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/production-us-east-3/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Direct deployments are only allowed to manually deployed environments.\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/production-us-east-3/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Deployment started in run 1 of production-us-east-3 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.productionUsEast3);
tester.controller().applications().deactivate(app1.instanceId(), ZoneId.from("prod", "us-east-3"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.devUsEast1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/dev-us-east-1/package", GET)
.userIdentity(USER_ID),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1.instance1.dev.us-east-1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/deploy/dev-us-east-1", POST)
.userIdentity(USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/environment/dev/region/us-east-1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.myuser in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.myuser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
id.application());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsCentral1);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 666)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1 with version 1.0.666-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
entity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
id2.application());
deploymentTester.applications().deploymentTrigger().triggerChange(id2, Change.of(Version.fromString("7.0")));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage, 1000)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/job/production-us-west-1", POST)
.data("{\"skipTests\":true}")
.userIdentity(USER_ID),
"{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1\"}");
app2.runJob(JobType.productionUsWest1);
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/job/production-us-west-1", POST)
.data("{\"reTrigger\":true}")
.userIdentity(USER_ID),
"{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/environment/prod/region/us-west-1", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Deactivated tenant2.application2.instance1 in prod.us-west-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.userIdentity(USER_ID),
new File("application2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("application2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", PATCH)
.userIdentity(USER_ID)
.data("{\"majorVersion\":7}"),
"{\"message\":\"Set major version to 7\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/key", POST)
.userIdentity(USER_ID)
.data("{\"key\":\"" + pemPublicKey + "\"}"),
"{\"keys\":[\"-----BEGIN PUBLIC KEY-----\\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\\nz/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\\n-----END PUBLIC KEY-----\\n\"]}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", PATCH)
.userIdentity(USER_ID)
.data("{\"pemDeployKey\":\"" + pemPublicKey + "\"}"),
"{\"message\":\"Added deploy key " + quotedPemPublicKey + "\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.userIdentity(USER_ID),
new File("application2-with-patches.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", PATCH)
.userIdentity(USER_ID)
.data("{\"majorVersion\":null}"),
"{\"message\":\"Set major version to empty\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/compile-version", GET)
.userIdentity(USER_ID),
"{\"compileVersion\":\"6.1.0\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/key", DELETE)
.userIdentity(USER_ID)
.data("{\"key\":\"" + pemPublicKey + "\"}"),
"{\"keys\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.userIdentity(USER_ID),
new File("application2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant2.application2.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant2.application2\"}");
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
deploymentTester.controllerTester().computeVersionStatus();
setDeploymentMaintainedInfo();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("deployment"),
new File("recursive-root.json"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("tenant"),
new File("recursive-until-tenant-root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("tenant1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/clusters", GET)
.userIdentity(USER_ID),
new File("application-clusters.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-central-1/instance/default/logs?from=1233&to=3214", GET)
.userIdentity(USER_ID),
"INFO - All good");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Changed deployment from 'application change to 1.0.1-commit1' to 'no change' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(USER_ID)
.data("{\"cancel\":\"all\"}"),
"{\"message\":\"No deployment in progress for tenant1.application1.instance1 at this time\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", POST)
.userIdentity(USER_ID)
.data("6.1.0"),
"{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
assertTrue("Action is logged to audit log",
tester.controller().auditLogger().readLog().entries().stream()
.anyMatch(entry -> entry.resource().equals("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin?")));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Changed deployment from 'pin to 6.1' to 'upgrade to 6.1' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":false}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", POST)
.userIdentity(USER_ID)
.data("6.1"),
"{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/platform", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Changed deployment from 'pin to 6.1' to 'pin to current platform' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Changed deployment from 'pin to current platform' to 'no change' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1/pause", POST)
.userIdentity(USER_ID),
"{\"message\":\"production-us-west-1 for tenant1.application1.instance1 paused for " + DeploymentTrigger.maxPause + "\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1/pause", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"production-us-west-1 for tenant1.application1.instance1 resumed\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1", POST)
.userIdentity(USER_ID),
"{\"message\":\"Triggered production-us-west-1 for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
.userIdentity(USER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
addUserToHostedOperatorRole(HostedAthenzIdentities.from(SCREWDRIVER_ID));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-central-1/instance/instance1/restart", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in staging.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-central-1/instance/instance1/restart", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in test.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-central-1/instance/instance1/restart", POST)
.userIdentity(USER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in dev.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
.properties(Map.of("hostname", "node-1-tenant-host-prod.us-central-1"))
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
ApplicationPackage packageWithServiceForWrongDomain = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN_2.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"message\":\"Application package version: 1.0.2-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
.properties(Map.of("build", "1"))
.userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
.data(streamer),
"{\"message\":\"Application package version: 1.0.3-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.environment(Environment.prod)
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec, 123)),
"{\"message\":\"Application package version: 1.0.4-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
.userIdentity(USER_ID),
new File("jobs.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/deployment", GET)
.userIdentity(USER_ID),
new File("deployment-overview.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
.userIdentity(USER_ID),
new File("system-test-job.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
.userIdentity(USER_ID),
new File("system-test-details.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/", Request.Method.OPTIONS)
.userIdentity(USER_ID),
"");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
}
private void addIssues(DeploymentTester tester, TenantAndApplicationId id) {
tester.applications().lockApplicationOrThrow(id, application ->
tester.controller().applications().store(application.withDeploymentIssueId(IssueId.from("123"))
.withOwnershipIssueId(IssueId.from("321"))
.withOwner(User.from("owner-username"))));
}
@Test
public void testRotationOverride() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
var westZone = ZoneId.from("prod", "us-west-1");
var eastZone = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region(westZone.region())
.region(eastZone.region())
.build();
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
app.submit(applicationPackage).deploy();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/environment/prod/region/us-west-1/instance/default/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"tenant2.application2 not found\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/global-rotation/override", PUT)
.userIdentity(USER_ID)
.data("{\"reason\":\"unit-test\"}"),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
404);
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
new File("global-rotation.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", GET)
.userIdentity(USER_ID),
new File("global-rotation-get.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", PUT)
.userIdentity(USER_ID)
.data("{\"reason\":\"unit-test\"}"),
new File("global-rotation-put.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), GlobalRouting.Status.out, GlobalRouting.Agent.tenant);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", DELETE)
.userIdentity(USER_ID)
.data("{\"reason\":\"unit-test\"}"),
new File("global-rotation-delete.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), GlobalRouting.Status.in, GlobalRouting.Agent.tenant);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", PUT)
.userIdentity(HOSTED_VESPA_OPERATOR)
.data("{\"reason\":\"unit-test\"}"),
new File("global-rotation-put.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), GlobalRouting.Status.out, GlobalRouting.Agent.operator);
}
@Test
public void multiple_endpoints() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-west-1"));
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-east-3"));
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "eu-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.properties(Map.of("endpointId", "default"))
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"IN\"}}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.properties(Map.of("endpointId", "eu"))
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/eu-west-1/global-rotation", GET)
.properties(Map.of("endpointId", "eu"))
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"IN\"}}",
200);
}
@Test
public void testDeployDirectly() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST).userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(SCREWDRIVER_ID));
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(entity)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
MultiPartStreamer noAppEntity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Deployment of system applications during a system upgrade is not allowed\"}",
400);
deploymentTester.controllerTester().upgradeSystem(deploymentTester.controller().versionStatus().controllerVersion().get().versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/proxy-host/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-no-deployment.json"), 400);
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = tester.serviceRegistry().meteringService();
ResourceAllocation currentSnapshot = new ResourceAllocation(1, 2, 3);
ResourceAllocation thisMonth = new ResourceAllocation(12, 24, 1000);
ResourceAllocation lastMonth = new ResourceAllocation(24, 48, 2000);
ApplicationId applicationId = ApplicationId.from("doesnotexist", "doesnotexist", "default");
Map<ApplicationId, List<ResourceSnapshot>> snapshotHistory = Map.of(applicationId, List.of(
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(123), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringData(new MeteringData(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
@Test
public void testErrorResponses() throws Exception {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/hosted-vespa", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", "Invalid application package", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
.properties(Map.of("build", "42"))
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
.properties(Map.of("build", "foobar"))
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", "Out of capacity", ConfigServerException.ErrorCode.OUT_OF_CAPACITY, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-out-of-capacity.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to activate application", "Activation conflict", ConfigServerException.ErrorCode.ACTIVATION_CONFLICT, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-activation-conflict.json"), 409);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to deploy application", "Internal server error", ConfigServerException.ErrorCode.INTERNAL_SERVER_ERROR, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-internal-server-error.json"), 500);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 1234L);
var application = deploymentTester.newDeploymentContext("tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId("123");
addScrewdriverUserToDeployRole(screwdriverId, ATHENZ_TENANT_DOMAIN, application.instanceId().application());
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
400);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
public void personal_deployment_with_athenz_service_requires_user_is_admin() {
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.build();
createTenantAndApplication();
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
.admin(HostedAthenzIdentities.from(userId));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
@Test
public void developers_can_deploy_when_privileged() {
UserId tenantAdmin = new UserId("tenant-admin");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
UserId developer = new UserId("developer");
AthenzDomain sandboxDomain = new AthenzDomain("sandbox");
createAthenzDomainWithAdmin(sandboxDomain, developer);
AthenzTenantSpec tenantSpec = new AthenzTenantSpec(TenantName.from("sandbox"),
sandboxDomain,
new Property("vespa"),
Optional.empty());
AthenzCredentials credentials = new AthenzCredentials(
new AthenzPrincipal(new AthenzUser(developer.id())), sandboxDomain, OKTA_IT, OKTA_AT);
tester.controller().tenants().create(tenantSpec, credentials);
tester.controller().applications().createApplication(TenantAndApplicationId.from("sandbox", "myapp"), credentials);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.build();
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(developer),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"User user.developer is not allowed to launch service domain1.service. Please reach out to the domain admin.\"}",
400);
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(ATHENZ_TENANT_DOMAIN);
domainMock.withPolicy("user." + developer.id(), "launch", "service.service");
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(developer),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for sandbox.myapp. This may take about 15 minutes the first time.\",\"run\":1}",
200);
UserId developer2 = new UserId("developer2");
tester.athenzClientFactory().getSetup().getOrCreateDomain(sandboxDomain).tenantAdmin(new AthenzUser(developer2.id()));
tester.athenzClientFactory().getSetup().getOrCreateDomain(ATHENZ_TENANT_DOMAIN).tenantAdmin(new AthenzUser(developer2.id()));
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(developer2),
"{\"message\":\"Deployment started in run 2 of dev-us-east-1 for sandbox.myapp. This may take about 15 minutes the first time.\",\"run\":2}",
200);
}
@Test
public void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
var zone = ZoneId.from(Environment.prod, RegionName.from("us-west-1"));
deploymentTester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone),
List.of(RoutingMethod.exclusive, RoutingMethod.shared));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain"), AthenzService.from("service"))
.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.environment(Environment.prod)
.instances("instance1")
.region(zone.region().value())
.build();
app.submit(applicationPackage).deploy();
app.addInactiveRoutingPolicy(zone);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private MultiPartStreamer createApplicationDeployData(ApplicationPackage applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(Optional.of(applicationPackage), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(applicationPackage, Optional.empty(), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage,
Optional<ApplicationVersion> applicationVersion, boolean deployDirectly) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", deployOptions(deployDirectly, applicationVersion));
applicationPackage.ifPresent(ap -> streamer.addBytes("applicationZip", ap.zippedContent()));
return streamer;
}
static MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage, long projectId) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repository1\",\"branch\":\"master\",\"commit\":\"commit1\","
+ "\"projectId\":" + projectId + ",\"authorEmail\":\"a@b\"}")
.addBytes(EnvironmentResource.APPLICATION_ZIP, applicationPackage.zippedContent())
.addBytes(EnvironmentResource.APPLICATION_TEST_ZIP, "content".getBytes());
}
private String deployOptions(boolean deployDirectly, Optional<ApplicationVersion> applicationVersion) {
return "{\"vespaVersion\":null," +
"\"ignoreValidationErrors\":false," +
"\"deployDirectly\":" + deployDirectly +
applicationVersion.map(version ->
"," +
"\"buildNumber\":" + version.buildNumber().getAsLong() + "," +
"\"sourceRevision\":{" +
"\"repository\":\"" + version.source().get().repository() + "\"," +
"\"branch\":\"" + version.source().get().branch() + "\"," +
"\"commit\":\"" + version.source().get().commit() + "\"" +
"}"
).orElse("") +
"}";
}
/** Make a request with (athens) user domain1.mytenant */
private RequestBuilder request(String path, Request.Method method) {
return new RequestBuilder(path, method);
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void createAthenzDomainWithAdmin(AthenzDomain domain, UserId userId) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(domain);
domainMock.markAsVespaTenant();
domainMock.admin(AthenzUser.fromUserId(userId.id()));
}
/**
* Mock athenz service identity configuration. Simulates that configserver is allowed to launch a service
*/
private void allowLaunchOfService(com.yahoo.vespa.athenz.api.AthenzService service) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(service.getDomain());
domainMock.withPolicy(tester.controller().zoneRegistry().accessControlDomain().value()+".provider.*","launch", "service." + service.getName());
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void addScrewdriverUserToDeployRole(ScrewdriverId screwdriverId,
AthenzDomain domain,
ApplicationName application) {
tester.authorize(domain, HostedAthenzIdentities.from(screwdriverId), ApplicationAction.deploy, application);
}
private ApplicationId createTenantAndApplication() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
/**
* Cluster info, utilization and application and deployment metrics are maintained async by maintainers.
*
* This sets these values as if the maintainers has been ran.
*/
private void setDeploymentMaintainedInfo() {
for (Application application : deploymentTester.applications().asList()) {
deploymentTester.applications().lockApplicationOrThrow(application.id(), lockedApplication -> {
lockedApplication = lockedApplication.with(new ApplicationMetrics(0.5, 0.7));
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.deployments().values()) {
DeploymentMetrics metrics = new DeploymentMetrics(1, 2, 3, 4, 5,
Optional.of(Instant.ofEpochMilli(123123)), Map.of());
lockedApplication = lockedApplication.with(instance.name(),
lockedInstance -> lockedInstance.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
deploymentTester.applications().store(lockedApplication);
}
});
}
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
tester.serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1)).run();
}
private void updateContactInformation() {
Contact contact = new Contact(URI.create("www.contacts.tld/1234"),
URI.create("www.properties.tld/1234"),
URI.create("www.issues.tld/1234"),
List.of(List.of("alice"), List.of("bob")), "queue", Optional.empty());
tester.controller().tenants().lockIfPresent(TenantName.from("tenant2"),
LockedTenant.Athenz.class,
lockedTenant -> tester.controller().tenants().store(lockedTenant.with(contact)));
}
private void registerContact(long propertyId) {
PropertyId p = new PropertyId(String.valueOf(propertyId));
tester.serviceRegistry().contactRetrieverMock().addContact(p, new Contact(URI.create("www.issues.tld/" + p.id()),
URI.create("www.contacts.tld/" + p.id()),
URI.create("www.properties.tld/" + p.id()),
List.of(Collections.singletonList("alice"),
Collections.singletonList("bob")),
"queue", Optional.empty()));
}
private void assertGlobalRouting(DeploymentId deployment, GlobalRouting.Status status, GlobalRouting.Agent agent) {
var changedAt = tester.controller().clock().instant();
var westPolicies = tester.controller().routing().policies().get(deployment);
assertEquals(1, westPolicies.size());
var westPolicy = westPolicies.values().iterator().next();
assertEquals(status, westPolicy.status().globalRouting().status());
assertEquals(agent, westPolicy.status().globalRouting().agent());
assertEquals(changedAt.truncatedTo(ChronoUnit.MILLIS), westPolicy.status().globalRouting().changedAt());
}
private static class RequestBuilder implements Supplier<Request> {
private final String path;
private final Request.Method method;
private byte[] data = new byte[0];
private AthenzIdentity identity;
private OktaIdentityToken oktaIdentityToken;
private OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private final Map<String, List<String>> headers = new HashMap<>();
private final Map<String, String> properties = new HashMap<>();
private RequestBuilder(String path, Request.Method method) {
this.path = path;
this.method = method;
}
private RequestBuilder data(byte[] data) { this.data = data; return this; }
private RequestBuilder data(String data) { return data(data.getBytes(UTF_8)); }
private RequestBuilder data(MultiPartStreamer streamer) {
return Exceptions.uncheck(() -> data(streamer.data().readAllBytes()).contentType(streamer.contentType()));
}
private RequestBuilder userIdentity(UserId userId) { this.identity = HostedAthenzIdentities.from(userId); return this; }
private RequestBuilder screwdriverIdentity(ScrewdriverId screwdriverId) { this.identity = HostedAthenzIdentities.from(screwdriverId); return this; }
private RequestBuilder oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) {return properties(Map.of("recursive", recursive)); }
private RequestBuilder properties(Map<String, String> properties) { this.properties.putAll(properties); return this; }
private RequestBuilder header(String name, String value) {
this.headers.putIfAbsent(name, new ArrayList<>());
this.headers.get(name).add(value);
return this;
}
@Override
public Request get() {
Request request = new Request("http:
properties.entrySet().stream()
.map(entry -> encode(entry.getKey(), UTF_8) + "=" + encode(entry.getValue(), UTF_8))
.collect(joining("&", "?", "")),
data, method);
request.getHeaders().addAll(headers);
request.getHeaders().put("Content-Type", contentType);
if (identity != null) {
addIdentityToRequest(request, identity);
}
if (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private ContainerTester tester;
private DeploymentTester deploymentTester;
@Before
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().computeVersionStatus();
}
@Test
public void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
new File("root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("application-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("application-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.properties(Map.of("recursive", "true",
"production", "true")),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID)
.properties(Map.of("recursive", "true",
"production", "true")),
new File("application-without-instances.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
var app1 = deploymentTester.newDeploymentContext(id);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/production-us-east-3/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Direct deployments are only allowed to manually deployed environments.\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/production-us-east-3/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Deployment started in run 1 of production-us-east-3 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.productionUsEast3);
tester.controller().applications().deactivate(app1.instanceId(), ZoneId.from("prod", "us-east-3"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.devUsEast1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/dev-us-east-1/package", GET)
.userIdentity(USER_ID),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1.instance1.dev.us-east-1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/deploy/dev-us-east-1", POST)
.userIdentity(USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/environment/dev/region/us-east-1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.myuser in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.myuser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
id.application());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsCentral1);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 666)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1 with version 1.0.666-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
entity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
id2.application());
deploymentTester.applications().deploymentTrigger().triggerChange(id2, Change.of(Version.fromString("7.0")));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage, 1000)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/job/production-us-west-1", POST)
.data("{\"skipTests\":true}")
.userIdentity(USER_ID),
"{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1\"}");
app2.runJob(JobType.productionUsWest1);
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/job/production-us-west-1", POST)
.data("{\"reTrigger\":true}")
.userIdentity(USER_ID),
"{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/environment/prod/region/us-west-1", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Deactivated tenant2.application2.instance1 in prod.us-west-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.userIdentity(USER_ID),
new File("application2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("application2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", PATCH)
.userIdentity(USER_ID)
.data("{\"majorVersion\":7}"),
"{\"message\":\"Set major version to 7\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/key", POST)
.userIdentity(USER_ID)
.data("{\"key\":\"" + pemPublicKey + "\"}"),
"{\"keys\":[\"-----BEGIN PUBLIC KEY-----\\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\\nz/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\\n-----END PUBLIC KEY-----\\n\"]}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", PATCH)
.userIdentity(USER_ID)
.data("{\"pemDeployKey\":\"" + pemPublicKey + "\"}"),
"{\"message\":\"Added deploy key " + quotedPemPublicKey + "\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.userIdentity(USER_ID),
new File("application2-with-patches.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", PATCH)
.userIdentity(USER_ID)
.data("{\"majorVersion\":null}"),
"{\"message\":\"Set major version to empty\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/compile-version", GET)
.userIdentity(USER_ID),
"{\"compileVersion\":\"6.1.0\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/key", DELETE)
.userIdentity(USER_ID)
.data("{\"key\":\"" + pemPublicKey + "\"}"),
"{\"keys\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
.userIdentity(USER_ID),
new File("application2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant2.application2.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant2.application2\"}");
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
deploymentTester.controllerTester().computeVersionStatus();
setDeploymentMaintainedInfo();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("deployment"),
new File("recursive-root.json"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("tenant"),
new File("recursive-until-tenant-root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("tenant1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/clusters", GET)
.userIdentity(USER_ID),
new File("application-clusters.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-central-1/instance/default/logs?from=1233&to=3214", GET)
.userIdentity(USER_ID),
"INFO - All good");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Changed deployment from 'application change to 1.0.1-commit1' to 'no change' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(USER_ID)
.data("{\"cancel\":\"all\"}"),
"{\"message\":\"No deployment in progress for tenant1.application1.instance1 at this time\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", POST)
.userIdentity(USER_ID)
.data("6.1.0"),
"{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
assertTrue("Action is logged to audit log",
tester.controller().auditLogger().readLog().entries().stream()
.anyMatch(entry -> entry.resource().equals("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin?")));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Changed deployment from 'pin to 6.1' to 'upgrade to 6.1' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":false}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", POST)
.userIdentity(USER_ID)
.data("6.1"),
"{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/platform", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Changed deployment from 'pin to 6.1' to 'pin to current platform' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Changed deployment from 'pin to current platform' to 'no change' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
.userIdentity(USER_ID), "{}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1/pause", POST)
.userIdentity(USER_ID),
"{\"message\":\"production-us-west-1 for tenant1.application1.instance1 paused for " + DeploymentTrigger.maxPause + "\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1/pause", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"production-us-west-1 for tenant1.application1.instance1 resumed\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1", POST)
.userIdentity(USER_ID),
"{\"message\":\"Triggered production-us-west-1 for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
.userIdentity(USER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
addUserToHostedOperatorRole(HostedAthenzIdentities.from(SCREWDRIVER_ID));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-central-1/instance/instance1/restart", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in staging.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-central-1/instance/instance1/restart", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in test.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-central-1/instance/instance1/restart", POST)
.userIdentity(USER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in dev.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
.properties(Map.of("hostname", "node-1-tenant-host-prod.us-central-1"))
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
ApplicationPackage packageWithServiceForWrongDomain = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN_2.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"message\":\"Application package version: 1.0.2-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
.properties(Map.of("build", "1"))
.userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
.data(streamer),
"{\"message\":\"Application package version: 1.0.3-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.environment(Environment.prod)
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec, 123)),
"{\"message\":\"Application package version: 1.0.4-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
.userIdentity(USER_ID),
new File("jobs.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/deployment", GET)
.userIdentity(USER_ID),
new File("deployment-overview.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
.userIdentity(USER_ID),
new File("system-test-job.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
.userIdentity(USER_ID),
new File("system-test-details.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/", Request.Method.OPTIONS)
.userIdentity(USER_ID),
"");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
}
private void addIssues(DeploymentTester tester, TenantAndApplicationId id) {
tester.applications().lockApplicationOrThrow(id, application ->
tester.controller().applications().store(application.withDeploymentIssueId(IssueId.from("123"))
.withOwnershipIssueId(IssueId.from("321"))
.withOwner(User.from("owner-username"))));
}
@Test
public void testRotationOverride() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
var westZone = ZoneId.from("prod", "us-west-1");
var eastZone = ZoneId.from("prod", "us-east-3");
var applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region(westZone.region())
.region(eastZone.region())
.build();
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
app.submit(applicationPackage).deploy();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/environment/prod/region/us-west-1/instance/default/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"tenant2.application2 not found\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/global-rotation/override", PUT)
.userIdentity(USER_ID)
.data("{\"reason\":\"unit-test\"}"),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
404);
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
new File("global-rotation.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", GET)
.userIdentity(USER_ID),
new File("global-rotation-get.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", PUT)
.userIdentity(USER_ID)
.data("{\"reason\":\"unit-test\"}"),
new File("global-rotation-put.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), GlobalRouting.Status.out, GlobalRouting.Agent.tenant);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", DELETE)
.userIdentity(USER_ID)
.data("{\"reason\":\"unit-test\"}"),
new File("global-rotation-delete.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), GlobalRouting.Status.in, GlobalRouting.Agent.tenant);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", PUT)
.userIdentity(HOSTED_VESPA_OPERATOR)
.data("{\"reason\":\"unit-test\"}"),
new File("global-rotation-put.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), GlobalRouting.Status.out, GlobalRouting.Agent.operator);
}
@Test
public void multiple_endpoints() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-west-1"));
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-east-3"));
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "eu-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.properties(Map.of("endpointId", "default"))
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"IN\"}}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.properties(Map.of("endpointId", "eu"))
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/eu-west-1/global-rotation", GET)
.properties(Map.of("endpointId", "eu"))
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"IN\"}}",
200);
}
@Test
public void testDeployDirectly() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST).userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(SCREWDRIVER_ID));
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(entity)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
MultiPartStreamer noAppEntity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Deployment of system applications during a system upgrade is not allowed\"}",
400);
deploymentTester.controllerTester().upgradeSystem(deploymentTester.controller().versionStatus().controllerVersion().get().versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/proxy-host/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-no-deployment.json"), 400);
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = tester.serviceRegistry().meteringService();
ResourceAllocation currentSnapshot = new ResourceAllocation(1, 2, 3);
ResourceAllocation thisMonth = new ResourceAllocation(12, 24, 1000);
ResourceAllocation lastMonth = new ResourceAllocation(24, 48, 2000);
ApplicationId applicationId = ApplicationId.from("doesnotexist", "doesnotexist", "default");
Map<ApplicationId, List<ResourceSnapshot>> snapshotHistory = Map.of(applicationId, List.of(
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(123), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringData(new MeteringData(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
@Test
public void testErrorResponses() throws Exception {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/hosted-vespa", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", "Invalid application package", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
.properties(Map.of("build", "42"))
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
.properties(Map.of("build", "foobar"))
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", "Out of capacity", ConfigServerException.ErrorCode.OUT_OF_CAPACITY, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-out-of-capacity.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to activate application", "Activation conflict", ConfigServerException.ErrorCode.ACTIVATION_CONFLICT, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-activation-conflict.json"), 409);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to deploy application", "Internal server error", ConfigServerException.ErrorCode.INTERNAL_SERVER_ERROR, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-internal-server-error.json"), 500);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 1234L);
var application = deploymentTester.newDeploymentContext("tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId("123");
addScrewdriverUserToDeployRole(screwdriverId, ATHENZ_TENANT_DOMAIN, application.instanceId().application());
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
400);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
public void personal_deployment_with_athenz_service_requires_user_is_admin() {
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.build();
createTenantAndApplication();
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
.admin(HostedAthenzIdentities.from(userId));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
@Test
public void developers_can_deploy_when_privileged() {
UserId tenantAdmin = new UserId("tenant-admin");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
UserId developer = new UserId("developer");
AthenzDomain sandboxDomain = new AthenzDomain("sandbox");
createAthenzDomainWithAdmin(sandboxDomain, developer);
AthenzTenantSpec tenantSpec = new AthenzTenantSpec(TenantName.from("sandbox"),
sandboxDomain,
new Property("vespa"),
Optional.empty());
AthenzCredentials credentials = new AthenzCredentials(
new AthenzPrincipal(new AthenzUser(developer.id())), sandboxDomain, OKTA_IT, OKTA_AT);
tester.controller().tenants().create(tenantSpec, credentials);
tester.controller().applications().createApplication(TenantAndApplicationId.from("sandbox", "myapp"), credentials);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.build();
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(developer),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"User user.developer is not allowed to launch service domain1.service. Please reach out to the domain admin.\"}",
400);
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(ATHENZ_TENANT_DOMAIN);
domainMock.withPolicy("user." + developer.id(), "launch", "service.service");
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(developer),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for sandbox.myapp. This may take about 15 minutes the first time.\",\"run\":1}",
200);
UserId developer2 = new UserId("developer2");
tester.athenzClientFactory().getSetup().getOrCreateDomain(sandboxDomain).tenantAdmin(new AthenzUser(developer2.id()));
tester.athenzClientFactory().getSetup().getOrCreateDomain(ATHENZ_TENANT_DOMAIN).tenantAdmin(new AthenzUser(developer2.id()));
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(developer2),
"{\"message\":\"Deployment started in run 2 of dev-us-east-1 for sandbox.myapp. This may take about 15 minutes the first time.\",\"run\":2}",
200);
}
@Test
public void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
var zone = ZoneId.from(Environment.prod, RegionName.from("us-west-1"));
deploymentTester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone),
List.of(RoutingMethod.exclusive, RoutingMethod.shared));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain"), AthenzService.from("service"))
.compileVersion(RoutingController.DIRECT_ROUTING_MIN_VERSION)
.environment(Environment.prod)
.instances("instance1")
.region(zone.region().value())
.build();
app.submit(applicationPackage).deploy();
app.addInactiveRoutingPolicy(zone);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private MultiPartStreamer createApplicationDeployData(ApplicationPackage applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(Optional.of(applicationPackage), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(applicationPackage, Optional.empty(), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage,
Optional<ApplicationVersion> applicationVersion, boolean deployDirectly) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", deployOptions(deployDirectly, applicationVersion));
applicationPackage.ifPresent(ap -> streamer.addBytes("applicationZip", ap.zippedContent()));
return streamer;
}
static MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage, long projectId) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repository1\",\"branch\":\"master\",\"commit\":\"commit1\","
+ "\"projectId\":" + projectId + ",\"authorEmail\":\"a@b\"}")
.addBytes(EnvironmentResource.APPLICATION_ZIP, applicationPackage.zippedContent())
.addBytes(EnvironmentResource.APPLICATION_TEST_ZIP, "content".getBytes());
}
private String deployOptions(boolean deployDirectly, Optional<ApplicationVersion> applicationVersion) {
return "{\"vespaVersion\":null," +
"\"ignoreValidationErrors\":false," +
"\"deployDirectly\":" + deployDirectly +
applicationVersion.map(version ->
"," +
"\"buildNumber\":" + version.buildNumber().getAsLong() + "," +
"\"sourceRevision\":{" +
"\"repository\":\"" + version.source().get().repository() + "\"," +
"\"branch\":\"" + version.source().get().branch() + "\"," +
"\"commit\":\"" + version.source().get().commit() + "\"" +
"}"
).orElse("") +
"}";
}
/** Make a request with (athens) user domain1.mytenant */
private RequestBuilder request(String path, Request.Method method) {
return new RequestBuilder(path, method);
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void createAthenzDomainWithAdmin(AthenzDomain domain, UserId userId) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(domain);
domainMock.markAsVespaTenant();
domainMock.admin(AthenzUser.fromUserId(userId.id()));
}
/**
* Mock athenz service identity configuration. Simulates that configserver is allowed to launch a service
*/
private void allowLaunchOfService(com.yahoo.vespa.athenz.api.AthenzService service) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(service.getDomain());
domainMock.withPolicy(tester.controller().zoneRegistry().accessControlDomain().value()+".provider.*","launch", "service." + service.getName());
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void addScrewdriverUserToDeployRole(ScrewdriverId screwdriverId,
AthenzDomain domain,
ApplicationName application) {
tester.authorize(domain, HostedAthenzIdentities.from(screwdriverId), ApplicationAction.deploy, application);
}
private ApplicationId createTenantAndApplication() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
/**
* Cluster info, utilization and application and deployment metrics are maintained async by maintainers.
*
* This sets these values as if the maintainers has been ran.
*/
private void setDeploymentMaintainedInfo() {
for (Application application : deploymentTester.applications().asList()) {
deploymentTester.applications().lockApplicationOrThrow(application.id(), lockedApplication -> {
lockedApplication = lockedApplication.with(new ApplicationMetrics(0.5, 0.7));
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.deployments().values()) {
DeploymentMetrics metrics = new DeploymentMetrics(1, 2, 3, 4, 5,
Optional.of(Instant.ofEpochMilli(123123)), Map.of());
lockedApplication = lockedApplication.with(instance.name(),
lockedInstance -> lockedInstance.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
deploymentTester.applications().store(lockedApplication);
}
});
}
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
tester.serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1)).run();
}
private void updateContactInformation() {
Contact contact = new Contact(URI.create("www.contacts.tld/1234"),
URI.create("www.properties.tld/1234"),
URI.create("www.issues.tld/1234"),
List.of(List.of("alice"), List.of("bob")), "queue", Optional.empty());
tester.controller().tenants().lockIfPresent(TenantName.from("tenant2"),
LockedTenant.Athenz.class,
lockedTenant -> tester.controller().tenants().store(lockedTenant.with(contact)));
}
private void registerContact(long propertyId) {
PropertyId p = new PropertyId(String.valueOf(propertyId));
tester.serviceRegistry().contactRetrieverMock().addContact(p, new Contact(URI.create("www.issues.tld/" + p.id()),
URI.create("www.contacts.tld/" + p.id()),
URI.create("www.properties.tld/" + p.id()),
List.of(Collections.singletonList("alice"),
Collections.singletonList("bob")),
"queue", Optional.empty()));
}
private void assertGlobalRouting(DeploymentId deployment, GlobalRouting.Status status, GlobalRouting.Agent agent) {
var changedAt = tester.controller().clock().instant();
var westPolicies = tester.controller().routing().policies().get(deployment);
assertEquals(1, westPolicies.size());
var westPolicy = westPolicies.values().iterator().next();
assertEquals(status, westPolicy.status().globalRouting().status());
assertEquals(agent, westPolicy.status().globalRouting().agent());
assertEquals(changedAt.truncatedTo(ChronoUnit.MILLIS), westPolicy.status().globalRouting().changedAt());
}
private static class RequestBuilder implements Supplier<Request> {
private final String path;
private final Request.Method method;
private byte[] data = new byte[0];
private AthenzIdentity identity;
private OktaIdentityToken oktaIdentityToken;
private OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private final Map<String, List<String>> headers = new HashMap<>();
private final Map<String, String> properties = new HashMap<>();
private RequestBuilder(String path, Request.Method method) {
this.path = path;
this.method = method;
}
private RequestBuilder data(byte[] data) { this.data = data; return this; }
private RequestBuilder data(String data) { return data(data.getBytes(UTF_8)); }
private RequestBuilder data(MultiPartStreamer streamer) {
return Exceptions.uncheck(() -> data(streamer.data().readAllBytes()).contentType(streamer.contentType()));
}
private RequestBuilder userIdentity(UserId userId) { this.identity = HostedAthenzIdentities.from(userId); return this; }
private RequestBuilder screwdriverIdentity(ScrewdriverId screwdriverId) { this.identity = HostedAthenzIdentities.from(screwdriverId); return this; }
private RequestBuilder oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) {return properties(Map.of("recursive", recursive)); }
private RequestBuilder properties(Map<String, String> properties) { this.properties.putAll(properties); return this; }
private RequestBuilder header(String name, String value) {
this.headers.putIfAbsent(name, new ArrayList<>());
this.headers.get(name).add(value);
return this;
}
@Override
public Request get() {
Request request = new Request("http:
properties.entrySet().stream()
.map(entry -> encode(entry.getKey(), UTF_8) + "=" + encode(entry.getValue(), UTF_8))
.collect(joining("&", "?", "")),
data, method);
request.getHeaders().addAll(headers);
request.getHeaders().put("Content-Type", contentType);
if (identity != null) {
addIdentityToRequest(request, identity);
}
if (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} |
Fixed | public void access_control_filter_chains_are_set_up() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain' />",
" </filtering>",
" </http>",
"</container>");
FilterChains filterChains = http.getFilterChains();
assertTrue(filterChains.hasChain(AccessControl.ACCESS_CONTROL_CHAIN_ID));
assertTrue(filterChains.hasChain(AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID));
Chain<Filter> excludedChain = filterChains.allChains().getComponent(AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID);
Collection<Filter> innerComponents = excludedChain.getInnerComponents();
assertThat(innerComponents, hasSize(1));
String accessControlExcludedChain = innerComponents.iterator().next().getClassId().stringValue();
assertEquals("com.yahoo.jdisc.http.filter.security.misc.NoopFilter", accessControlExcludedChain);
} | "<container version='1.0'>", | public void access_control_filter_chains_are_set_up() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain' />",
" </filtering>",
" </http>");
FilterChains filterChains = http.getFilterChains();
assertTrue(filterChains.hasChain(AccessControl.ACCESS_CONTROL_CHAIN_ID));
assertTrue(filterChains.hasChain(AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID));
} | class AccessControlTest extends ContainerModelBuilderTestBase {
@Test
@Test
public void properties_are_set_from_xml() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain'/>",
" </filtering>",
" </http>",
"</container>");
AccessControl accessControl = http.getAccessControl().get();
assertEquals("Wrong domain.", "my-tenant-domain", accessControl.domain);
}
@Test
public void read_is_disabled_and_write_is_enabled_by_default() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain'/>",
" </filtering>",
" </http>",
"</container>");
assertFalse("Wrong default value for read.", http.getAccessControl().get().readEnabled);
assertTrue("Wrong default value for write.", http.getAccessControl().get().writeEnabled);
}
@Test
public void read_and_write_can_be_overridden() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain' read='true' write='false'/>",
" </filtering>",
" </http>",
"</container>");
assertTrue("Given read value not honoured.", http.getAccessControl().get().readEnabled);
assertFalse("Given write value not honoured.", http.getAccessControl().get().writeEnabled);
}
@Test
public void access_control_excluded_filter_chain_has_all_bindings_from_excluded_handlers() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <filtering>",
" <access-control/>",
" </filtering>",
" </http>",
"</container>");
Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID);
assertThat(actualBindings, containsInAnyOrder(
"http:
"http:
"http:
"http:
"http:
"http:
"http:
"http:
"http:
}
@Test
public void access_control_excluded_filter_chain_has_user_provided_excluded_bindings() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <handler id='custom.Handler'>",
" <binding>http:
" </handler>",
" <filtering>",
" <access-control>",
" <exclude>",
" <binding>http:
" <binding>http:
" </exclude>",
" </access-control>",
" </filtering>",
" </http>",
"</container>");
Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID);
assertThat(actualBindings, hasItems("http:
}
@Test
public void access_control_filter_chain_contains_catchall_bindings() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <filtering>",
" <access-control/>",
" </filtering>",
" </http>",
"</container>");
Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_CHAIN_ID);
assertThat(actualBindings, containsInAnyOrder("http:
}
@Test
public void access_control_is_implicitly_added_for_hosted_apps() {
Http http = createModelAndGetHttp("<container version='1.0'/>");
Optional<AccessControl> maybeAccessControl = http.getAccessControl();
assertThat(maybeAccessControl.isPresent(), is(true));
AccessControl accessControl = maybeAccessControl.get();
assertThat(accessControl.writeEnabled, is(false));
assertThat(accessControl.readEnabled, is(false));
assertThat(accessControl.domain, equalTo("my-tenant-domain"));
}
@Test
public void access_control_is_implicitly_added_for_hosted_apps_with_existing_http_element() {
Http http = createModelAndGetHttp(
"<container version='1.0'>",
" <http>",
" <server port='" + getDefaults().vespaWebServicePort() + "' id='main' />",
" <filtering>",
" <filter id='outer' />",
" <request-chain id='myChain'>",
" <filter id='inner' />",
" </request-chain>",
" </filtering>",
" </http>",
"</container>" );
assertThat(http.getAccessControl().isPresent(), is(true));
assertThat(http.getFilterChains().hasChain(AccessControl.ACCESS_CONTROL_CHAIN_ID), is(true));
assertThat(http.getFilterChains().hasChain(ComponentId.fromString("myChain")), is(true));
}
private Http createModelAndGetHttp(String... servicesXml) {
AthenzDomain tenantDomain = AthenzDomain.from("my-tenant-domain");
DeployState state = new DeployState.Builder().properties(
new TestProperties()
.setAthenzDomain(tenantDomain)
.setHostedVespa(true))
.build();
createModel(root, state, null, DomBuilderTest.parse(servicesXml));
return ((ApplicationContainer) root.getProducer("container/container.0")).getHttp();
}
private static Set<String> getFilterBindings(Http http, ComponentId filerChain) {
return http.getBindings().stream()
.filter(binding -> binding.filterId().toId().equals(filerChain))
.map(binding -> binding.binding().patternString())
.collect(Collectors.toSet());
}
} | class AccessControlTest extends ContainerModelBuilderTestBase {
@Test
@Test
public void properties_are_set_from_xml() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain'/>",
" </filtering>",
" </http>");
AccessControl accessControl = http.getAccessControl().get();
assertEquals("Wrong domain.", "my-tenant-domain", accessControl.domain);
}
@Test
public void read_is_disabled_and_write_is_enabled_by_default() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain'/>",
" </filtering>",
" </http>");
assertFalse("Wrong default value for read.", http.getAccessControl().get().readEnabled);
assertTrue("Wrong default value for write.", http.getAccessControl().get().writeEnabled);
}
@Test
public void read_and_write_can_be_overridden() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control domain='my-tenant-domain' read='true' write='false'/>",
" </filtering>",
" </http>");
assertTrue("Given read value not honoured.", http.getAccessControl().get().readEnabled);
assertFalse("Given write value not honoured.", http.getAccessControl().get().writeEnabled);
}
@Test
public void access_control_excluded_filter_chain_has_all_bindings_from_excluded_handlers() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control/>",
" </filtering>",
" </http>");
Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID);
assertThat(actualBindings, containsInAnyOrder(
"http:
"http:
"http:
"http:
"http:
"http:
"http:
"http:
"http:
}
@Test
public void access_control_excluded_chain_does_not_contain_any_bindings_from_access_control_chain() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control/>",
" </filtering>",
" </http>");
Set<String> bindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_CHAIN_ID);
Set<String> excludedBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID);
for (String binding : bindings) {
assertThat(excludedBindings, not(hasItem(binding)));
}
}
@Test
public void access_control_excluded_filter_chain_has_user_provided_excluded_bindings() {
Http http = createModelAndGetHttp(
" <http>",
" <handler id='custom.Handler'>",
" <binding>http:
" </handler>",
" <filtering>",
" <access-control>",
" <exclude>",
" <binding>http:
" <binding>http:
" </exclude>",
" </access-control>",
" </filtering>",
" </http>");
Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_EXCLUDED_CHAIN_ID);
assertThat(actualBindings, hasItems("http:
}
@Test
public void access_control_filter_chain_contains_catchall_bindings() {
Http http = createModelAndGetHttp(
" <http>",
" <filtering>",
" <access-control/>",
" </filtering>",
" </http>");
Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_CHAIN_ID);
assertThat(actualBindings, containsInAnyOrder("http:
}
@Test
public void access_control_is_implicitly_added_for_hosted_apps() {
Http http = createModelAndGetHttp("<container version='1.0'/>");
Optional<AccessControl> maybeAccessControl = http.getAccessControl();
assertThat(maybeAccessControl.isPresent(), is(true));
AccessControl accessControl = maybeAccessControl.get();
assertThat(accessControl.writeEnabled, is(false));
assertThat(accessControl.readEnabled, is(false));
assertThat(accessControl.domain, equalTo("my-tenant-domain"));
}
@Test
public void access_control_is_implicitly_added_for_hosted_apps_with_existing_http_element() {
Http http = createModelAndGetHttp(
" <http>",
" <server port='" + getDefaults().vespaWebServicePort() + "' id='main' />",
" <filtering>",
" <filter id='outer' />",
" <request-chain id='myChain'>",
" <filter id='inner' />",
" </request-chain>",
" </filtering>",
" </http>");
assertThat(http.getAccessControl().isPresent(), is(true));
assertThat(http.getFilterChains().hasChain(AccessControl.ACCESS_CONTROL_CHAIN_ID), is(true));
assertThat(http.getFilterChains().hasChain(ComponentId.fromString("myChain")), is(true));
}
private Http createModelAndGetHttp(String... httpElement) {
List<String> servicesXml = new ArrayList<>();
servicesXml.add("<container version='1.0'>");
servicesXml.addAll(List.of(httpElement));
servicesXml.add("</container>");
AthenzDomain tenantDomain = AthenzDomain.from("my-tenant-domain");
DeployState state = new DeployState.Builder().properties(
new TestProperties()
.setAthenzDomain(tenantDomain)
.setHostedVespa(true))
.build();
createModel(root, state, null, DomBuilderTest.parse(servicesXml.toArray(String[]::new)));
return ((ApplicationContainer) root.getProducer("container/container.0")).getHttp();
}
private static Set<String> getFilterBindings(Http http, ComponentId filerChain) {
return http.getBindings().stream()
.filter(binding -> binding.chainId().toId().equals(filerChain))
.map(binding -> binding.binding().patternString())
.collect(Collectors.toSet());
}
} |
Yes, good point, that's better | public Optional<ApplicationId> getOptionalApplicationId() {
try {
return Optional.of(getApplicationId());
} catch (RuntimeException e) {
return Optional.empty();
}
} | return Optional.of(getApplicationId()); | public Optional<ApplicationId> getOptionalApplicationId() {
try {
return Optional.of(getApplicationId());
} catch (RuntimeException e) {
return Optional.empty();
}
} | class Session implements Comparable<Session> {
private final long sessionId;
protected final TenantName tenant;
protected final SessionZooKeeperClient sessionZooKeeperClient;
protected final Optional<ApplicationPackage> applicationPackage;
protected Session(TenantName tenant, long sessionId, SessionZooKeeperClient sessionZooKeeperClient) {
this(tenant, sessionId, sessionZooKeeperClient, Optional.empty());
}
protected Session(TenantName tenant, long sessionId, SessionZooKeeperClient sessionZooKeeperClient,
ApplicationPackage applicationPackage) {
this(tenant, sessionId, sessionZooKeeperClient, Optional.of(applicationPackage));
}
private Session(TenantName tenant, long sessionId, SessionZooKeeperClient sessionZooKeeperClient,
Optional<ApplicationPackage> applicationPackage) {
this.tenant = tenant;
this.sessionId = sessionId;
this.sessionZooKeeperClient = sessionZooKeeperClient;
this.applicationPackage = applicationPackage;
}
public final long getSessionId() {
return sessionId;
}
public Session.Status getStatus() {
return sessionZooKeeperClient.readStatus();
}
public SessionZooKeeperClient getSessionZooKeeperClient() {
return sessionZooKeeperClient;
}
@Override
public String toString() {
return "Session,id=" + sessionId;
}
public long getActiveSessionAtCreate() {
return getMetaData().getPreviousActiveGeneration();
}
/**
* The status of this session.
*/
public enum Status {
NEW, PREPARE, ACTIVATE, DEACTIVATE, DELETE, NONE;
public static Status parse(String data) {
for (Status status : Status.values()) {
if (status.name().equals(data)) {
return status;
}
}
return Status.NEW;
}
}
public TenantName getTenantName() { return tenant; }
/**
* Helper to provide a log message preamble for code dealing with sessions
* @return log preamble
*/
public String logPre() {
Optional<ApplicationId> applicationId;
try {
applicationId = Optional.of(getApplicationId());
} catch (Exception e) {
applicationId = Optional.empty();
}
return applicationId
.filter(appId -> ! appId.equals(ApplicationId.defaultId()))
.map(TenantRepository::logPre)
.orElse(TenantRepository.logPre(getTenantName()));
}
public Instant getCreateTime() {
return sessionZooKeeperClient.readCreateTime();
}
public void setApplicationId(ApplicationId applicationId) {
sessionZooKeeperClient.writeApplicationId(applicationId);
}
void setApplicationPackageReference(FileReference applicationPackageReference) {
if (applicationPackageReference == null) throw new IllegalArgumentException(String.format(
"Null application package file reference for tenant %s, session id %d", tenant, sessionId));
sessionZooKeeperClient.writeApplicationPackageReference(applicationPackageReference);
}
public void setVespaVersion(Version version) {
sessionZooKeeperClient.writeVespaVersion(version);
}
public void setDockerImageRepository(Optional<DockerImage> dockerImageRepository) {
sessionZooKeeperClient.writeDockerImageRepository(dockerImageRepository);
}
public void setAthenzDomain(Optional<AthenzDomain> athenzDomain) {
sessionZooKeeperClient.writeAthenzDomain(athenzDomain);
}
/** Returns application id read from ZooKeeper. Will throw RuntimeException if not found */
public ApplicationId getApplicationId() { return sessionZooKeeperClient.readApplicationId(); }
/** Returns application id read from ZooKeeper. Will return Optional.empty() if not found */
public FileReference getApplicationPackageReference() {return sessionZooKeeperClient.readApplicationPackageReference(); }
public Optional<DockerImage> getDockerImageRepository() { return sessionZooKeeperClient.readDockerImageRepository(); }
public Version getVespaVersion() { return sessionZooKeeperClient.readVespaVersion(); }
public Optional<AthenzDomain> getAthenzDomain() { return sessionZooKeeperClient.readAthenzDomain(); }
public AllocatedHosts getAllocatedHosts() {
return sessionZooKeeperClient.getAllocatedHosts();
}
public Transaction createDeactivateTransaction() {
return createSetStatusTransaction(Status.DEACTIVATE);
}
private Transaction createSetStatusTransaction(Status status) {
return sessionZooKeeperClient.createWriteStatusTransaction(status);
}
public boolean isNewerThan(long sessionId) { return getSessionId() > sessionId; }
public ApplicationMetaData getMetaData() {
return applicationPackage.isPresent()
? applicationPackage.get().getMetaData()
: sessionZooKeeperClient.loadApplicationPackage().getMetaData();
}
public ApplicationPackage getApplicationPackage() {
return applicationPackage.orElseThrow(() -> new RuntimeException("No application package found for " + this));
}
public ApplicationFile getApplicationFile(Path relativePath, LocalSession.Mode mode) {
if (mode.equals(Session.Mode.WRITE)) {
markSessionEdited();
}
return getApplicationPackage().getFile(relativePath);
}
private void markSessionEdited() {
setStatus(Session.Status.NEW);
}
void setStatus(Session.Status newStatus) {
sessionZooKeeperClient.writeStatus(newStatus);
}
@Override
public int compareTo(Session rhs) {
Long lhsId = getSessionId();
Long rhsId = rhs.getSessionId();
return lhsId.compareTo(rhsId);
}
public enum Mode {
READ, WRITE
}
} | class Session implements Comparable<Session> {
private final long sessionId;
protected final TenantName tenant;
protected final SessionZooKeeperClient sessionZooKeeperClient;
protected final Optional<ApplicationPackage> applicationPackage;
protected Session(TenantName tenant, long sessionId, SessionZooKeeperClient sessionZooKeeperClient) {
this(tenant, sessionId, sessionZooKeeperClient, Optional.empty());
}
protected Session(TenantName tenant, long sessionId, SessionZooKeeperClient sessionZooKeeperClient,
ApplicationPackage applicationPackage) {
this(tenant, sessionId, sessionZooKeeperClient, Optional.of(applicationPackage));
}
private Session(TenantName tenant, long sessionId, SessionZooKeeperClient sessionZooKeeperClient,
Optional<ApplicationPackage> applicationPackage) {
this.tenant = tenant;
this.sessionId = sessionId;
this.sessionZooKeeperClient = sessionZooKeeperClient;
this.applicationPackage = applicationPackage;
}
public final long getSessionId() {
return sessionId;
}
public Session.Status getStatus() {
return sessionZooKeeperClient.readStatus();
}
public SessionZooKeeperClient getSessionZooKeeperClient() {
return sessionZooKeeperClient;
}
@Override
public String toString() {
return "Session,id=" + sessionId;
}
public long getActiveSessionAtCreate() {
return getMetaData().getPreviousActiveGeneration();
}
/**
* The status of this session.
*/
public enum Status {
NEW, PREPARE, ACTIVATE, DEACTIVATE, DELETE, NONE;
public static Status parse(String data) {
for (Status status : Status.values()) {
if (status.name().equals(data)) {
return status;
}
}
return Status.NEW;
}
}
public TenantName getTenantName() { return tenant; }
/**
* Helper to provide a log message preamble for code dealing with sessions
* @return log preamble
*/
public String logPre() {
Optional<ApplicationId> applicationId;
try {
applicationId = Optional.of(getApplicationId());
} catch (Exception e) {
applicationId = Optional.empty();
}
return applicationId
.filter(appId -> ! appId.equals(ApplicationId.defaultId()))
.map(TenantRepository::logPre)
.orElse(TenantRepository.logPre(getTenantName()));
}
public Instant getCreateTime() {
return sessionZooKeeperClient.readCreateTime();
}
public void setApplicationId(ApplicationId applicationId) {
sessionZooKeeperClient.writeApplicationId(applicationId);
}
void setApplicationPackageReference(FileReference applicationPackageReference) {
if (applicationPackageReference == null) throw new IllegalArgumentException(String.format(
"Null application package file reference for tenant %s, session id %d", tenant, sessionId));
sessionZooKeeperClient.writeApplicationPackageReference(applicationPackageReference);
}
public void setVespaVersion(Version version) {
sessionZooKeeperClient.writeVespaVersion(version);
}
public void setDockerImageRepository(Optional<DockerImage> dockerImageRepository) {
sessionZooKeeperClient.writeDockerImageRepository(dockerImageRepository);
}
public void setAthenzDomain(Optional<AthenzDomain> athenzDomain) {
sessionZooKeeperClient.writeAthenzDomain(athenzDomain);
}
/** Returns application id read from ZooKeeper. Will throw RuntimeException if not found */
public ApplicationId getApplicationId() {
return sessionZooKeeperClient.readApplicationId()
.orElseThrow(() -> new RuntimeException("Unable to read application id for session " + sessionId));
}
/** Returns application id read from ZooKeeper. Will return Optional.empty() if not found */
public FileReference getApplicationPackageReference() {return sessionZooKeeperClient.readApplicationPackageReference(); }
public Optional<DockerImage> getDockerImageRepository() { return sessionZooKeeperClient.readDockerImageRepository(); }
public Version getVespaVersion() { return sessionZooKeeperClient.readVespaVersion(); }
public Optional<AthenzDomain> getAthenzDomain() { return sessionZooKeeperClient.readAthenzDomain(); }
public AllocatedHosts getAllocatedHosts() {
return sessionZooKeeperClient.getAllocatedHosts();
}
public Transaction createDeactivateTransaction() {
return createSetStatusTransaction(Status.DEACTIVATE);
}
private Transaction createSetStatusTransaction(Status status) {
return sessionZooKeeperClient.createWriteStatusTransaction(status);
}
public boolean isNewerThan(long sessionId) { return getSessionId() > sessionId; }
public ApplicationMetaData getMetaData() {
return applicationPackage.isPresent()
? applicationPackage.get().getMetaData()
: sessionZooKeeperClient.loadApplicationPackage().getMetaData();
}
public ApplicationPackage getApplicationPackage() {
return applicationPackage.orElseThrow(() -> new RuntimeException("No application package found for " + this));
}
public ApplicationFile getApplicationFile(Path relativePath, LocalSession.Mode mode) {
if (mode.equals(Session.Mode.WRITE)) {
markSessionEdited();
}
return getApplicationPackage().getFile(relativePath);
}
private void markSessionEdited() {
setStatus(Session.Status.NEW);
}
void setStatus(Session.Status newStatus) {
sessionZooKeeperClient.writeStatus(newStatus);
}
@Override
public int compareTo(Session rhs) {
Long lhsId = getSessionId();
Long rhsId = rhs.getSessionId();
return lhsId.compareTo(rhsId);
}
public enum Mode {
READ, WRITE
}
} |
Perhaps we could start this method by creating a map from binding->id? | private void removeDuplicateBindingsFromAccessControlChain(Http http) {
Set<FilterBinding> duplicateBindings = new HashSet<>();
for (FilterBinding binding : http.getBindings()) {
if (binding.filterId().toId().equals(ACCESS_CONTROL_CHAIN_ID)) {
for (FilterBinding otherBinding : http.getBindings()) {
if (!binding.filterId().equals(otherBinding.filterId())
&& binding.binding().equals(otherBinding.binding())) {
duplicateBindings.add(binding);
}
}
}
}
duplicateBindings.forEach(http.getBindings()::remove);
} | for (FilterBinding binding : http.getBindings()) { | private void removeDuplicateBindingsFromAccessControlChain(Http http) {
Set<FilterBinding> duplicateBindings = new HashSet<>();
for (FilterBinding binding : http.getBindings()) {
if (binding.chainId().toId().equals(ACCESS_CONTROL_CHAIN_ID)) {
for (FilterBinding otherBinding : http.getBindings()) {
if (!binding.chainId().equals(otherBinding.chainId())
&& binding.binding().equals(otherBinding.binding())) {
duplicateBindings.add(binding);
}
}
}
}
duplicateBindings.forEach(http.getBindings()::remove);
} | class Builder {
private final String domain;
private boolean readEnabled = false;
private boolean writeEnabled = true;
private final Set<BindingPattern> excludeBindings = new LinkedHashSet<>();
private Collection<Handler<?>> handlers = Collections.emptyList();
public Builder(String domain) {
this.domain = domain;
}
public Builder readEnabled(boolean readEnabled) {
this.readEnabled = readEnabled;
return this;
}
public Builder writeEnabled(boolean writeEnabled) {
this.writeEnabled = writeEnabled;
return this;
}
public Builder excludeBinding(BindingPattern binding) {
this.excludeBindings.add(binding);
return this;
}
public Builder setHandlers(ApplicationContainerCluster cluster) {
this.handlers = cluster.getHandlers();
return this;
}
public AccessControl build() {
return new AccessControl(domain, writeEnabled, readEnabled, excludeBindings, handlers);
}
} | class Builder {
private final String domain;
private boolean readEnabled = false;
private boolean writeEnabled = true;
private final Set<BindingPattern> excludeBindings = new LinkedHashSet<>();
private Collection<Handler<?>> handlers = Collections.emptyList();
public Builder(String domain) {
this.domain = domain;
}
public Builder readEnabled(boolean readEnabled) {
this.readEnabled = readEnabled;
return this;
}
public Builder writeEnabled(boolean writeEnabled) {
this.writeEnabled = writeEnabled;
return this;
}
public Builder excludeBinding(BindingPattern binding) {
this.excludeBindings.add(binding);
return this;
}
public Builder setHandlers(ApplicationContainerCluster cluster) {
this.handlers = cluster.getHandlers();
return this;
}
public AccessControl build() {
return new AccessControl(domain, writeEnabled, readEnabled, excludeBindings, handlers);
}
} |
BTW, is `filterId()` the correct name? Sounds like it should be `chainId`. | private void removeDuplicateBindingsFromAccessControlChain(Http http) {
Set<FilterBinding> duplicateBindings = new HashSet<>();
for (FilterBinding binding : http.getBindings()) {
if (binding.filterId().toId().equals(ACCESS_CONTROL_CHAIN_ID)) {
for (FilterBinding otherBinding : http.getBindings()) {
if (!binding.filterId().equals(otherBinding.filterId())
&& binding.binding().equals(otherBinding.binding())) {
duplicateBindings.add(binding);
}
}
}
}
duplicateBindings.forEach(http.getBindings()::remove);
} | if (binding.filterId().toId().equals(ACCESS_CONTROL_CHAIN_ID)) { | private void removeDuplicateBindingsFromAccessControlChain(Http http) {
Set<FilterBinding> duplicateBindings = new HashSet<>();
for (FilterBinding binding : http.getBindings()) {
if (binding.chainId().toId().equals(ACCESS_CONTROL_CHAIN_ID)) {
for (FilterBinding otherBinding : http.getBindings()) {
if (!binding.chainId().equals(otherBinding.chainId())
&& binding.binding().equals(otherBinding.binding())) {
duplicateBindings.add(binding);
}
}
}
}
duplicateBindings.forEach(http.getBindings()::remove);
} | class Builder {
private final String domain;
private boolean readEnabled = false;
private boolean writeEnabled = true;
private final Set<BindingPattern> excludeBindings = new LinkedHashSet<>();
private Collection<Handler<?>> handlers = Collections.emptyList();
public Builder(String domain) {
this.domain = domain;
}
public Builder readEnabled(boolean readEnabled) {
this.readEnabled = readEnabled;
return this;
}
public Builder writeEnabled(boolean writeEnabled) {
this.writeEnabled = writeEnabled;
return this;
}
public Builder excludeBinding(BindingPattern binding) {
this.excludeBindings.add(binding);
return this;
}
public Builder setHandlers(ApplicationContainerCluster cluster) {
this.handlers = cluster.getHandlers();
return this;
}
public AccessControl build() {
return new AccessControl(domain, writeEnabled, readEnabled, excludeBindings, handlers);
}
} | class Builder {
private final String domain;
private boolean readEnabled = false;
private boolean writeEnabled = true;
private final Set<BindingPattern> excludeBindings = new LinkedHashSet<>();
private Collection<Handler<?>> handlers = Collections.emptyList();
public Builder(String domain) {
this.domain = domain;
}
public Builder readEnabled(boolean readEnabled) {
this.readEnabled = readEnabled;
return this;
}
public Builder writeEnabled(boolean writeEnabled) {
this.writeEnabled = writeEnabled;
return this;
}
public Builder excludeBinding(BindingPattern binding) {
this.excludeBindings.add(binding);
return this;
}
public Builder setHandlers(ApplicationContainerCluster cluster) {
this.handlers = cluster.getHandlers();
return this;
}
public AccessControl build() {
return new AccessControl(domain, writeEnabled, readEnabled, excludeBindings, handlers);
}
} |
There are multiple strategies to solve this specific problem, but I don't think creating a mapping will be significantly better. | private void removeDuplicateBindingsFromAccessControlChain(Http http) {
Set<FilterBinding> duplicateBindings = new HashSet<>();
for (FilterBinding binding : http.getBindings()) {
if (binding.filterId().toId().equals(ACCESS_CONTROL_CHAIN_ID)) {
for (FilterBinding otherBinding : http.getBindings()) {
if (!binding.filterId().equals(otherBinding.filterId())
&& binding.binding().equals(otherBinding.binding())) {
duplicateBindings.add(binding);
}
}
}
}
duplicateBindings.forEach(http.getBindings()::remove);
} | for (FilterBinding binding : http.getBindings()) { | private void removeDuplicateBindingsFromAccessControlChain(Http http) {
Set<FilterBinding> duplicateBindings = new HashSet<>();
for (FilterBinding binding : http.getBindings()) {
if (binding.chainId().toId().equals(ACCESS_CONTROL_CHAIN_ID)) {
for (FilterBinding otherBinding : http.getBindings()) {
if (!binding.chainId().equals(otherBinding.chainId())
&& binding.binding().equals(otherBinding.binding())) {
duplicateBindings.add(binding);
}
}
}
}
duplicateBindings.forEach(http.getBindings()::remove);
} | class Builder {
private final String domain;
private boolean readEnabled = false;
private boolean writeEnabled = true;
private final Set<BindingPattern> excludeBindings = new LinkedHashSet<>();
private Collection<Handler<?>> handlers = Collections.emptyList();
public Builder(String domain) {
this.domain = domain;
}
public Builder readEnabled(boolean readEnabled) {
this.readEnabled = readEnabled;
return this;
}
public Builder writeEnabled(boolean writeEnabled) {
this.writeEnabled = writeEnabled;
return this;
}
public Builder excludeBinding(BindingPattern binding) {
this.excludeBindings.add(binding);
return this;
}
public Builder setHandlers(ApplicationContainerCluster cluster) {
this.handlers = cluster.getHandlers();
return this;
}
public AccessControl build() {
return new AccessControl(domain, writeEnabled, readEnabled, excludeBindings, handlers);
}
} | class Builder {
private final String domain;
private boolean readEnabled = false;
private boolean writeEnabled = true;
private final Set<BindingPattern> excludeBindings = new LinkedHashSet<>();
private Collection<Handler<?>> handlers = Collections.emptyList();
public Builder(String domain) {
this.domain = domain;
}
public Builder readEnabled(boolean readEnabled) {
this.readEnabled = readEnabled;
return this;
}
public Builder writeEnabled(boolean writeEnabled) {
this.writeEnabled = writeEnabled;
return this;
}
public Builder excludeBinding(BindingPattern binding) {
this.excludeBindings.add(binding);
return this;
}
public Builder setHandlers(ApplicationContainerCluster cluster) {
this.handlers = cluster.getHandlers();
return this;
}
public AccessControl build() {
return new AccessControl(domain, writeEnabled, readEnabled, excludeBindings, handlers);
}
} |
Fixed | public Optional<ApplicationId> getOptionalApplicationId() {
try {
return Optional.of(getApplicationId());
} catch (RuntimeException e) {
return Optional.empty();
}
} | return Optional.of(getApplicationId()); | public Optional<ApplicationId> getOptionalApplicationId() {
try {
return Optional.of(getApplicationId());
} catch (RuntimeException e) {
return Optional.empty();
}
} | class Session implements Comparable<Session> {
private final long sessionId;
protected final TenantName tenant;
protected final SessionZooKeeperClient sessionZooKeeperClient;
protected final Optional<ApplicationPackage> applicationPackage;
protected Session(TenantName tenant, long sessionId, SessionZooKeeperClient sessionZooKeeperClient) {
this(tenant, sessionId, sessionZooKeeperClient, Optional.empty());
}
protected Session(TenantName tenant, long sessionId, SessionZooKeeperClient sessionZooKeeperClient,
ApplicationPackage applicationPackage) {
this(tenant, sessionId, sessionZooKeeperClient, Optional.of(applicationPackage));
}
private Session(TenantName tenant, long sessionId, SessionZooKeeperClient sessionZooKeeperClient,
Optional<ApplicationPackage> applicationPackage) {
this.tenant = tenant;
this.sessionId = sessionId;
this.sessionZooKeeperClient = sessionZooKeeperClient;
this.applicationPackage = applicationPackage;
}
public final long getSessionId() {
return sessionId;
}
public Session.Status getStatus() {
return sessionZooKeeperClient.readStatus();
}
public SessionZooKeeperClient getSessionZooKeeperClient() {
return sessionZooKeeperClient;
}
@Override
public String toString() {
return "Session,id=" + sessionId;
}
public long getActiveSessionAtCreate() {
return getMetaData().getPreviousActiveGeneration();
}
/**
* The status of this session.
*/
public enum Status {
NEW, PREPARE, ACTIVATE, DEACTIVATE, DELETE, NONE;
public static Status parse(String data) {
for (Status status : Status.values()) {
if (status.name().equals(data)) {
return status;
}
}
return Status.NEW;
}
}
public TenantName getTenantName() { return tenant; }
/**
* Helper to provide a log message preamble for code dealing with sessions
* @return log preamble
*/
public String logPre() {
Optional<ApplicationId> applicationId;
try {
applicationId = Optional.of(getApplicationId());
} catch (Exception e) {
applicationId = Optional.empty();
}
return applicationId
.filter(appId -> ! appId.equals(ApplicationId.defaultId()))
.map(TenantRepository::logPre)
.orElse(TenantRepository.logPre(getTenantName()));
}
public Instant getCreateTime() {
return sessionZooKeeperClient.readCreateTime();
}
public void setApplicationId(ApplicationId applicationId) {
sessionZooKeeperClient.writeApplicationId(applicationId);
}
void setApplicationPackageReference(FileReference applicationPackageReference) {
if (applicationPackageReference == null) throw new IllegalArgumentException(String.format(
"Null application package file reference for tenant %s, session id %d", tenant, sessionId));
sessionZooKeeperClient.writeApplicationPackageReference(applicationPackageReference);
}
public void setVespaVersion(Version version) {
sessionZooKeeperClient.writeVespaVersion(version);
}
public void setDockerImageRepository(Optional<DockerImage> dockerImageRepository) {
sessionZooKeeperClient.writeDockerImageRepository(dockerImageRepository);
}
public void setAthenzDomain(Optional<AthenzDomain> athenzDomain) {
sessionZooKeeperClient.writeAthenzDomain(athenzDomain);
}
/** Returns application id read from ZooKeeper. Will throw RuntimeException if not found */
public ApplicationId getApplicationId() { return sessionZooKeeperClient.readApplicationId(); }
/** Returns application id read from ZooKeeper. Will return Optional.empty() if not found */
public FileReference getApplicationPackageReference() {return sessionZooKeeperClient.readApplicationPackageReference(); }
public Optional<DockerImage> getDockerImageRepository() { return sessionZooKeeperClient.readDockerImageRepository(); }
public Version getVespaVersion() { return sessionZooKeeperClient.readVespaVersion(); }
public Optional<AthenzDomain> getAthenzDomain() { return sessionZooKeeperClient.readAthenzDomain(); }
public AllocatedHosts getAllocatedHosts() {
return sessionZooKeeperClient.getAllocatedHosts();
}
public Transaction createDeactivateTransaction() {
return createSetStatusTransaction(Status.DEACTIVATE);
}
private Transaction createSetStatusTransaction(Status status) {
return sessionZooKeeperClient.createWriteStatusTransaction(status);
}
public boolean isNewerThan(long sessionId) { return getSessionId() > sessionId; }
public ApplicationMetaData getMetaData() {
return applicationPackage.isPresent()
? applicationPackage.get().getMetaData()
: sessionZooKeeperClient.loadApplicationPackage().getMetaData();
}
public ApplicationPackage getApplicationPackage() {
return applicationPackage.orElseThrow(() -> new RuntimeException("No application package found for " + this));
}
public ApplicationFile getApplicationFile(Path relativePath, LocalSession.Mode mode) {
if (mode.equals(Session.Mode.WRITE)) {
markSessionEdited();
}
return getApplicationPackage().getFile(relativePath);
}
private void markSessionEdited() {
setStatus(Session.Status.NEW);
}
void setStatus(Session.Status newStatus) {
sessionZooKeeperClient.writeStatus(newStatus);
}
@Override
public int compareTo(Session rhs) {
Long lhsId = getSessionId();
Long rhsId = rhs.getSessionId();
return lhsId.compareTo(rhsId);
}
public enum Mode {
READ, WRITE
}
} | class Session implements Comparable<Session> {
private final long sessionId;
protected final TenantName tenant;
protected final SessionZooKeeperClient sessionZooKeeperClient;
protected final Optional<ApplicationPackage> applicationPackage;
protected Session(TenantName tenant, long sessionId, SessionZooKeeperClient sessionZooKeeperClient) {
this(tenant, sessionId, sessionZooKeeperClient, Optional.empty());
}
protected Session(TenantName tenant, long sessionId, SessionZooKeeperClient sessionZooKeeperClient,
ApplicationPackage applicationPackage) {
this(tenant, sessionId, sessionZooKeeperClient, Optional.of(applicationPackage));
}
private Session(TenantName tenant, long sessionId, SessionZooKeeperClient sessionZooKeeperClient,
Optional<ApplicationPackage> applicationPackage) {
this.tenant = tenant;
this.sessionId = sessionId;
this.sessionZooKeeperClient = sessionZooKeeperClient;
this.applicationPackage = applicationPackage;
}
public final long getSessionId() {
return sessionId;
}
public Session.Status getStatus() {
return sessionZooKeeperClient.readStatus();
}
public SessionZooKeeperClient getSessionZooKeeperClient() {
return sessionZooKeeperClient;
}
@Override
public String toString() {
return "Session,id=" + sessionId;
}
public long getActiveSessionAtCreate() {
return getMetaData().getPreviousActiveGeneration();
}
/**
* The status of this session.
*/
public enum Status {
NEW, PREPARE, ACTIVATE, DEACTIVATE, DELETE, NONE;
public static Status parse(String data) {
for (Status status : Status.values()) {
if (status.name().equals(data)) {
return status;
}
}
return Status.NEW;
}
}
public TenantName getTenantName() { return tenant; }
/**
* Helper to provide a log message preamble for code dealing with sessions
* @return log preamble
*/
public String logPre() {
Optional<ApplicationId> applicationId;
try {
applicationId = Optional.of(getApplicationId());
} catch (Exception e) {
applicationId = Optional.empty();
}
return applicationId
.filter(appId -> ! appId.equals(ApplicationId.defaultId()))
.map(TenantRepository::logPre)
.orElse(TenantRepository.logPre(getTenantName()));
}
public Instant getCreateTime() {
return sessionZooKeeperClient.readCreateTime();
}
public void setApplicationId(ApplicationId applicationId) {
sessionZooKeeperClient.writeApplicationId(applicationId);
}
void setApplicationPackageReference(FileReference applicationPackageReference) {
if (applicationPackageReference == null) throw new IllegalArgumentException(String.format(
"Null application package file reference for tenant %s, session id %d", tenant, sessionId));
sessionZooKeeperClient.writeApplicationPackageReference(applicationPackageReference);
}
public void setVespaVersion(Version version) {
sessionZooKeeperClient.writeVespaVersion(version);
}
public void setDockerImageRepository(Optional<DockerImage> dockerImageRepository) {
sessionZooKeeperClient.writeDockerImageRepository(dockerImageRepository);
}
public void setAthenzDomain(Optional<AthenzDomain> athenzDomain) {
sessionZooKeeperClient.writeAthenzDomain(athenzDomain);
}
/** Returns application id read from ZooKeeper. Will throw RuntimeException if not found */
public ApplicationId getApplicationId() {
return sessionZooKeeperClient.readApplicationId()
.orElseThrow(() -> new RuntimeException("Unable to read application id for session " + sessionId));
}
/** Returns application id read from ZooKeeper. Will return Optional.empty() if not found */
public FileReference getApplicationPackageReference() {return sessionZooKeeperClient.readApplicationPackageReference(); }
public Optional<DockerImage> getDockerImageRepository() { return sessionZooKeeperClient.readDockerImageRepository(); }
public Version getVespaVersion() { return sessionZooKeeperClient.readVespaVersion(); }
public Optional<AthenzDomain> getAthenzDomain() { return sessionZooKeeperClient.readAthenzDomain(); }
public AllocatedHosts getAllocatedHosts() {
return sessionZooKeeperClient.getAllocatedHosts();
}
public Transaction createDeactivateTransaction() {
return createSetStatusTransaction(Status.DEACTIVATE);
}
private Transaction createSetStatusTransaction(Status status) {
return sessionZooKeeperClient.createWriteStatusTransaction(status);
}
public boolean isNewerThan(long sessionId) { return getSessionId() > sessionId; }
public ApplicationMetaData getMetaData() {
return applicationPackage.isPresent()
? applicationPackage.get().getMetaData()
: sessionZooKeeperClient.loadApplicationPackage().getMetaData();
}
public ApplicationPackage getApplicationPackage() {
return applicationPackage.orElseThrow(() -> new RuntimeException("No application package found for " + this));
}
public ApplicationFile getApplicationFile(Path relativePath, LocalSession.Mode mode) {
if (mode.equals(Session.Mode.WRITE)) {
markSessionEdited();
}
return getApplicationPackage().getFile(relativePath);
}
private void markSessionEdited() {
setStatus(Session.Status.NEW);
}
void setStatus(Session.Status newStatus) {
sessionZooKeeperClient.writeStatus(newStatus);
}
@Override
public int compareTo(Session rhs) {
Long lhsId = getSessionId();
Long rhsId = rhs.getSessionId();
return lhsId.compareTo(rhsId);
}
public enum Mode {
READ, WRITE
}
} |
Pretty sure there's some `optionalString` somewhere, perhaps in `SlimeUtils`. | private CloudTenant cloudTenantFrom(Inspector tenantObject) {
TenantName name = TenantName.from(tenantObject.field(nameField).asString());
Optional<Principal> creator = tenantObject.field(creatorField).valid() ?
Optional.of(new SimplePrincipal(tenantObject.field(creatorField).asString())) :
Optional.empty();
BiMap<PublicKey, Principal> developerKeys = developerKeysFromSlime(tenantObject.field(pemDeveloperKeysField));
return new CloudTenant(name, creator, developerKeys);
} | Optional<Principal> creator = tenantObject.field(creatorField).valid() ? | private CloudTenant cloudTenantFrom(Inspector tenantObject) {
TenantName name = TenantName.from(tenantObject.field(nameField).asString());
Optional<Principal> creator = SlimeUtils.optionalString(tenantObject.field(creatorField)).map(SimplePrincipal::new);
BiMap<PublicKey, Principal> developerKeys = developerKeysFromSlime(tenantObject.field(pemDeveloperKeysField));
return new CloudTenant(name, creator, developerKeys);
} | class TenantSerializer {
private static final String nameField = "name";
private static final String typeField = "type";
private static final String athenzDomainField = "athenzDomain";
private static final String propertyField = "property";
private static final String propertyIdField = "propertyId";
private static final String creatorField = "creator";
private static final String createdAtField = "createdAt";
private static final String contactField = "contact";
private static final String contactUrlField = "contactUrl";
private static final String propertyUrlField = "propertyUrl";
private static final String issueTrackerUrlField = "issueTrackerUrl";
private static final String personsField = "persons";
private static final String personField = "person";
private static final String queueField = "queue";
private static final String componentField = "component";
private static final String billingInfoField = "billingInfo";
private static final String customerIdField = "customerId";
private static final String productCodeField = "productCode";
private static final String pemDeveloperKeysField = "pemDeveloperKeys";
public Slime toSlime(Tenant tenant) {
Slime slime = new Slime();
Cursor tenantObject = slime.setObject();
tenantObject.setString(nameField, tenant.name().value());
tenantObject.setString(typeField, valueOf(tenant.type()));
switch (tenant.type()) {
case athenz: toSlime((AthenzTenant) tenant, tenantObject); break;
case cloud: toSlime((CloudTenant) tenant, tenantObject); break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
return slime;
}
private void toSlime(AthenzTenant tenant, Cursor tenantObject) {
tenantObject.setString(athenzDomainField, tenant.domain().getName());
tenantObject.setString(propertyField, tenant.property().id());
tenant.propertyId().ifPresent(propertyId -> tenantObject.setString(propertyIdField, propertyId.id()));
tenant.contact().ifPresent(contact -> {
Cursor contactCursor = tenantObject.setObject(contactField);
writeContact(contact, contactCursor);
});
}
private void toSlime(CloudTenant tenant, Cursor root) {
var legacyBillingInfo = new BillingInfo("customer", "Vespa");
tenant.creator().ifPresent(creator -> root.setString(creatorField, creator.getName()));
developerKeysToSlime(tenant.developerKeys(), root.setArray(pemDeveloperKeysField));
toSlime(legacyBillingInfo, root.setObject(billingInfoField));
}
private void developerKeysToSlime(BiMap<PublicKey, Principal> keys, Cursor array) {
keys.forEach((key, user) -> {
Cursor object = array.addObject();
object.setString("key", KeyUtils.toPem(key));
object.setString("user", user.getName());
});
}
private void toSlime(BillingInfo billingInfo, Cursor billingInfoObject) {
billingInfoObject.setString(customerIdField, billingInfo.customerId());
billingInfoObject.setString(productCodeField, billingInfo.productCode());
}
public Tenant tenantFrom(Slime slime) {
Inspector tenantObject = slime.get();
Tenant.Type type;
type = typeOf(tenantObject.field(typeField).asString());
switch (type) {
case athenz: return athenzTenantFrom(tenantObject);
case cloud: return cloudTenantFrom(tenantObject);
default: throw new IllegalArgumentException("Unexpected tenant type '" + type + "'.");
}
}
private AthenzTenant athenzTenantFrom(Inspector tenantObject) {
TenantName name = TenantName.from(tenantObject.field(nameField).asString());
AthenzDomain domain = new AthenzDomain(tenantObject.field(athenzDomainField).asString());
Property property = new Property(tenantObject.field(propertyField).asString());
Optional<PropertyId> propertyId = SlimeUtils.optionalString(tenantObject.field(propertyIdField)).map(PropertyId::new);
Optional<Contact> contact = contactFrom(tenantObject.field(contactField));
return new AthenzTenant(name, domain, property, propertyId, contact);
}
private BiMap<PublicKey, Principal> developerKeysFromSlime(Inspector array) {
ImmutableBiMap.Builder<PublicKey, Principal> keys = ImmutableBiMap.builder();
array.traverse((ArrayTraverser) (__, keyObject) ->
keys.put(KeyUtils.fromPemEncodedPublicKey(keyObject.field("key").asString()),
new SimplePrincipal(keyObject.field("user").asString())));
return keys.build();
}
private Optional<Contact> contactFrom(Inspector object) {
if ( ! object.valid()) return Optional.empty();
URI contactUrl = URI.create(object.field(contactUrlField).asString());
URI propertyUrl = URI.create(object.field(propertyUrlField).asString());
URI issueTrackerUrl = URI.create(object.field(issueTrackerUrlField).asString());
List<List<String>> persons = personsFrom(object.field(personsField));
String queue = object.field(queueField).asString();
Optional<String> component = object.field(componentField).valid() ? Optional.of(object.field(componentField).asString()) : Optional.empty();
return Optional.of(new Contact(contactUrl,
propertyUrl,
issueTrackerUrl,
persons,
queue,
component));
}
private void writeContact(Contact contact, Cursor contactCursor) {
contactCursor.setString(contactUrlField, contact.url().toString());
contactCursor.setString(propertyUrlField, contact.propertyUrl().toString());
contactCursor.setString(issueTrackerUrlField, contact.issueTrackerUrl().toString());
Cursor personsArray = contactCursor.setArray(personsField);
contact.persons().forEach(personList -> {
Cursor personArray = personsArray.addArray();
personList.forEach(person -> {
Cursor personObject = personArray.addObject();
personObject.setString(personField, person);
});
});
contactCursor.setString(queueField, contact.queue());
contact.component().ifPresent(component -> contactCursor.setString(componentField, component));
}
private List<List<String>> personsFrom(Inspector array) {
List<List<String>> personLists = new ArrayList<>();
array.traverse((ArrayTraverser) (i, personArray) -> {
List<String> persons = new ArrayList<>();
personArray.traverse((ArrayTraverser) (j, inspector) -> persons.add(inspector.field("person").asString()));
personLists.add(persons);
});
return personLists;
}
private BillingInfo billingInfoFrom(Inspector billingInfoObject) {
return new BillingInfo(billingInfoObject.field(customerIdField).asString(),
billingInfoObject.field(productCodeField).asString());
}
private static Tenant.Type typeOf(String value) {
switch (value) {
case "athenz": return Tenant.Type.athenz;
case "cloud": return Tenant.Type.cloud;
default: throw new IllegalArgumentException("Unknown tenant type '" + value + "'.");
}
}
private static String valueOf(Tenant.Type type) {
switch (type) {
case athenz: return "athenz";
case cloud: return "cloud";
default: throw new IllegalArgumentException("Unexpected tenant type '" + type + "'.");
}
}
} | class TenantSerializer {
private static final String nameField = "name";
private static final String typeField = "type";
private static final String athenzDomainField = "athenzDomain";
private static final String propertyField = "property";
private static final String propertyIdField = "propertyId";
private static final String creatorField = "creator";
private static final String createdAtField = "createdAt";
private static final String contactField = "contact";
private static final String contactUrlField = "contactUrl";
private static final String propertyUrlField = "propertyUrl";
private static final String issueTrackerUrlField = "issueTrackerUrl";
private static final String personsField = "persons";
private static final String personField = "person";
private static final String queueField = "queue";
private static final String componentField = "component";
private static final String billingInfoField = "billingInfo";
private static final String customerIdField = "customerId";
private static final String productCodeField = "productCode";
private static final String pemDeveloperKeysField = "pemDeveloperKeys";
public Slime toSlime(Tenant tenant) {
Slime slime = new Slime();
Cursor tenantObject = slime.setObject();
tenantObject.setString(nameField, tenant.name().value());
tenantObject.setString(typeField, valueOf(tenant.type()));
switch (tenant.type()) {
case athenz: toSlime((AthenzTenant) tenant, tenantObject); break;
case cloud: toSlime((CloudTenant) tenant, tenantObject); break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
return slime;
}
private void toSlime(AthenzTenant tenant, Cursor tenantObject) {
tenantObject.setString(athenzDomainField, tenant.domain().getName());
tenantObject.setString(propertyField, tenant.property().id());
tenant.propertyId().ifPresent(propertyId -> tenantObject.setString(propertyIdField, propertyId.id()));
tenant.contact().ifPresent(contact -> {
Cursor contactCursor = tenantObject.setObject(contactField);
writeContact(contact, contactCursor);
});
}
private void toSlime(CloudTenant tenant, Cursor root) {
var legacyBillingInfo = new BillingInfo("customer", "Vespa");
tenant.creator().ifPresent(creator -> root.setString(creatorField, creator.getName()));
developerKeysToSlime(tenant.developerKeys(), root.setArray(pemDeveloperKeysField));
toSlime(legacyBillingInfo, root.setObject(billingInfoField));
}
private void developerKeysToSlime(BiMap<PublicKey, Principal> keys, Cursor array) {
keys.forEach((key, user) -> {
Cursor object = array.addObject();
object.setString("key", KeyUtils.toPem(key));
object.setString("user", user.getName());
});
}
private void toSlime(BillingInfo billingInfo, Cursor billingInfoObject) {
billingInfoObject.setString(customerIdField, billingInfo.customerId());
billingInfoObject.setString(productCodeField, billingInfo.productCode());
}
public Tenant tenantFrom(Slime slime) {
Inspector tenantObject = slime.get();
Tenant.Type type;
type = typeOf(tenantObject.field(typeField).asString());
switch (type) {
case athenz: return athenzTenantFrom(tenantObject);
case cloud: return cloudTenantFrom(tenantObject);
default: throw new IllegalArgumentException("Unexpected tenant type '" + type + "'.");
}
}
private AthenzTenant athenzTenantFrom(Inspector tenantObject) {
TenantName name = TenantName.from(tenantObject.field(nameField).asString());
AthenzDomain domain = new AthenzDomain(tenantObject.field(athenzDomainField).asString());
Property property = new Property(tenantObject.field(propertyField).asString());
Optional<PropertyId> propertyId = SlimeUtils.optionalString(tenantObject.field(propertyIdField)).map(PropertyId::new);
Optional<Contact> contact = contactFrom(tenantObject.field(contactField));
return new AthenzTenant(name, domain, property, propertyId, contact);
}
private BiMap<PublicKey, Principal> developerKeysFromSlime(Inspector array) {
ImmutableBiMap.Builder<PublicKey, Principal> keys = ImmutableBiMap.builder();
array.traverse((ArrayTraverser) (__, keyObject) ->
keys.put(KeyUtils.fromPemEncodedPublicKey(keyObject.field("key").asString()),
new SimplePrincipal(keyObject.field("user").asString())));
return keys.build();
}
private Optional<Contact> contactFrom(Inspector object) {
if ( ! object.valid()) return Optional.empty();
URI contactUrl = URI.create(object.field(contactUrlField).asString());
URI propertyUrl = URI.create(object.field(propertyUrlField).asString());
URI issueTrackerUrl = URI.create(object.field(issueTrackerUrlField).asString());
List<List<String>> persons = personsFrom(object.field(personsField));
String queue = object.field(queueField).asString();
Optional<String> component = object.field(componentField).valid() ? Optional.of(object.field(componentField).asString()) : Optional.empty();
return Optional.of(new Contact(contactUrl,
propertyUrl,
issueTrackerUrl,
persons,
queue,
component));
}
private void writeContact(Contact contact, Cursor contactCursor) {
contactCursor.setString(contactUrlField, contact.url().toString());
contactCursor.setString(propertyUrlField, contact.propertyUrl().toString());
contactCursor.setString(issueTrackerUrlField, contact.issueTrackerUrl().toString());
Cursor personsArray = contactCursor.setArray(personsField);
contact.persons().forEach(personList -> {
Cursor personArray = personsArray.addArray();
personList.forEach(person -> {
Cursor personObject = personArray.addObject();
personObject.setString(personField, person);
});
});
contactCursor.setString(queueField, contact.queue());
contact.component().ifPresent(component -> contactCursor.setString(componentField, component));
}
private List<List<String>> personsFrom(Inspector array) {
List<List<String>> personLists = new ArrayList<>();
array.traverse((ArrayTraverser) (i, personArray) -> {
List<String> persons = new ArrayList<>();
personArray.traverse((ArrayTraverser) (j, inspector) -> persons.add(inspector.field("person").asString()));
personLists.add(persons);
});
return personLists;
}
private BillingInfo billingInfoFrom(Inspector billingInfoObject) {
return new BillingInfo(billingInfoObject.field(customerIdField).asString(),
billingInfoObject.field(productCodeField).asString());
}
private static Tenant.Type typeOf(String value) {
switch (value) {
case "athenz": return Tenant.Type.athenz;
case "cloud": return Tenant.Type.cloud;
default: throw new IllegalArgumentException("Unknown tenant type '" + value + "'.");
}
}
private static String valueOf(Tenant.Type type) {
switch (type) {
case athenz: return "athenz";
case cloud: return "cloud";
default: throw new IllegalArgumentException("Unexpected tenant type '" + type + "'.");
}
}
} |
now you do the same anyway, this could be simpler: ``` while (true) { maintenance(); waitForTrigger(2000); } ``` | private void run() {
try {
while (true) {
while (maintenance()) {
waitForTrigger(2000);
}
waitForTrigger(2000);
}
} catch (Exception e) {
System.err.println("Fatal exception in FilesArchived-maintainer thread: "+e);
}
} | while (maintenance()) { | private void run() {
try {
while (true) {
maintenance();
waitForTrigger(2000);
}
} catch (Exception e) {
System.err.println("Fatal exception in FilesArchived-maintainer thread: "+e);
}
} | class FilesArchived {
private static final Logger log = Logger.getLogger(FilesArchived.class.getName());
/**
* File instance representing root directory of archive
*/
private final File root;
private final Object mutex = new Object();
private List<LogFile> knownFiles;
public static final long compressAfterMillis = 2L * 3600 * 1000;
private static final long maxAgeDays = 30;
private static final long sizeLimit = 30L * (1L << 30);
private void waitForTrigger(long milliS) throws InterruptedException {
synchronized (mutex) {
mutex.wait(milliS);
}
}
/**
* Creates an instance of FilesArchive managing the given directory
*/
public FilesArchived(File rootDir) {
this.root = rootDir;
rescan();
Thread thread = new Thread(this::run);
thread.setDaemon(true);
thread.setName("FilesArchived-maintainer");
thread.start();
}
public String toString() {
return FilesArchived.class.getName() + ": root=" + root;
}
public synchronized int highestGen(String prefix) {
int gen = 0;
for (LogFile lf : knownFiles) {
if (prefix.equals(lf.prefix)) {
gen = Math.max(gen, lf.generation);
}
}
return gen;
}
public void triggerMaintenance() {
synchronized (mutex) {
mutex.notifyAll();
}
}
synchronized boolean maintenance() {
boolean action = false;
rescan();
if (removeOlderThan(maxAgeDays)) {
action = true;
rescan();
}
if (compressOldFiles()) {
action = true;
rescan();
}
long days = maxAgeDays;
while (tooMuchDiskUsage() && (--days > 1)) {
if (removeOlderThan(days)) {
action = true;
rescan();
}
}
return action;
}
private void rescan() {
knownFiles = scanDir(root);
}
boolean tooMuchDiskUsage() {
long sz = sumFileSizes();
return sz > sizeLimit;
}
private boolean olderThan(LogFile lf, long days, long now) {
long mtime = lf.path.lastModified();
long diff = now - mtime;
return (diff > days * 86400L * 1000L);
}
private boolean removeOlderThan(long days) {
boolean action = false;
long now = System.currentTimeMillis();
for (LogFile lf : knownFiles) {
if (olderThan(lf, days, now)) {
lf.path.delete();
log.info("Deleted: "+lf.path);
action = true;
}
}
return action;
}
private boolean compressOldFiles() {
long now = System.currentTimeMillis();
int count = 0;
for (LogFile lf : knownFiles) {
if (lf.canCompress(now) && (count++ < 5)) {
compress(lf.path);
}
}
return count > 0;
}
private void compress(File oldFile) {
File gzippedFile = new File(oldFile.getPath() + ".gz");
try (GZIPOutputStream compressor = new GZIPOutputStream(new FileOutputStream(gzippedFile), 0x100000);
FileInputStream inputStream = new FileInputStream(oldFile))
{
long mtime = oldFile.lastModified();
byte [] buffer = new byte[0x100000];
for (int read = inputStream.read(buffer); read > 0; read = inputStream.read(buffer)) {
compressor.write(buffer, 0, read);
}
compressor.finish();
compressor.flush();
oldFile.delete();
gzippedFile.setLastModified(mtime);
log.info("Compressed: "+gzippedFile);
} catch (IOException e) {
log.warning("Got '" + e + "' while compressing '" + oldFile.getPath() + "'.");
}
}
long sumFileSizes() {
long sum = 0;
for (LogFile lf : knownFiles) {
sum += lf.path.length();
}
return sum;
}
private static final Pattern dateFormatRegexp = Pattern.compile(".*/" +
"[0-9][0-9][0-9][0-9]/" +
"[0-9][0-9]/" +
"[0-9][0-9]/" +
"[0-9][0-9]-" +
"[0-9].*");
private static List<LogFile> scanDir(File top) {
List<LogFile> retval = new ArrayList<>();
String[] names = top.list();
if (names != null) {
for (String name : names) {
File sub = new File(top, name);
if (sub.isFile()) {
String pathName = sub.toString();
if (dateFormatRegexp.matcher(pathName).matches()) {
retval.add(new LogFile(sub));
} else {
log.warning("skipping file not matching log archive pattern: "+pathName);
}
} else if (sub.isDirectory()) {
retval.addAll(scanDir(sub));
}
}
}
return retval;
}
static class LogFile {
public final File path;
public final String prefix;
public final int generation;
public final boolean zsuff;
public boolean canCompress(long now) {
if (zsuff) return false;
if (! path.isFile()) return false;
long diff = now - path.lastModified();
if (diff < compressAfterMillis) return false;
return true;
}
private static int generationOf(String name) {
int dash = name.lastIndexOf('-');
if (dash < 0) return 0;
String suff = name.substring(dash + 1);
int r = 0;
for (char ch : suff.toCharArray()) {
if (ch >= '0' && ch <= '9') {
r *= 10;
r += (ch - '0');
} else {
break;
}
}
return r;
}
private static String prefixOf(String name) {
int dash = name.lastIndexOf('-');
if (dash < 0) return name;
return name.substring(0, dash);
}
private static boolean zSuffix(String name) {
if (name.endsWith(".gz")) return true;
return false;
}
public LogFile(File path) {
String name = path.toString();
this.path = path;
this.prefix = prefixOf(name);
this.generation = generationOf(name);
this.zsuff = zSuffix(name);
}
public String toString() {
return "FilesArchived.LogFile{name="+path+" prefix="+prefix+" gen="+generation+" z="+zsuff+"}";
}
}
} | class FilesArchived {
private static final Logger log = Logger.getLogger(FilesArchived.class.getName());
/**
* File instance representing root directory of archive
*/
private final File root;
private final Object mutex = new Object();
private List<LogFile> knownFiles;
public static final long compressAfterMillis = 2L * 3600 * 1000;
private static final long maxAgeDays = 30;
private static final long sizeLimit = 30L * (1L << 30);
private void waitForTrigger(long milliS) throws InterruptedException {
synchronized (mutex) {
mutex.wait(milliS);
}
}
/**
* Creates an instance of FilesArchive managing the given directory
*/
public FilesArchived(File rootDir) {
this.root = rootDir;
rescan();
Thread thread = new Thread(this::run);
thread.setDaemon(true);
thread.setName("FilesArchived-maintainer");
thread.start();
}
public String toString() {
return FilesArchived.class.getName() + ": root=" + root;
}
public synchronized int highestGen(String prefix) {
int gen = 0;
for (LogFile lf : knownFiles) {
if (prefix.equals(lf.prefix)) {
gen = Math.max(gen, lf.generation);
}
}
return gen;
}
public void triggerMaintenance() {
synchronized (mutex) {
mutex.notifyAll();
}
}
synchronized boolean maintenance() {
boolean action = false;
rescan();
if (removeOlderThan(maxAgeDays)) {
action = true;
rescan();
}
if (compressOldFiles()) {
action = true;
rescan();
}
long days = maxAgeDays;
while (tooMuchDiskUsage() && (--days > 1)) {
if (removeOlderThan(days)) {
action = true;
rescan();
}
}
return action;
}
private void rescan() {
knownFiles = scanDir(root);
}
boolean tooMuchDiskUsage() {
long sz = sumFileSizes();
return sz > sizeLimit;
}
private boolean olderThan(LogFile lf, long days, long now) {
long mtime = lf.path.lastModified();
long diff = now - mtime;
return (diff > days * 86400L * 1000L);
}
private boolean removeOlderThan(long days) {
boolean action = false;
long now = System.currentTimeMillis();
for (LogFile lf : knownFiles) {
if (olderThan(lf, days, now)) {
lf.path.delete();
log.info("Deleted: "+lf.path);
action = true;
}
}
return action;
}
private boolean compressOldFiles() {
long now = System.currentTimeMillis();
int count = 0;
for (LogFile lf : knownFiles) {
if (lf.canCompress(now) && (count++ < 5)) {
compress(lf.path);
}
}
return count > 0;
}
private void compress(File oldFile) {
File gzippedFile = new File(oldFile.getPath() + ".gz");
try (GZIPOutputStream compressor = new GZIPOutputStream(new FileOutputStream(gzippedFile), 0x100000);
FileInputStream inputStream = new FileInputStream(oldFile))
{
long mtime = oldFile.lastModified();
byte [] buffer = new byte[0x100000];
for (int read = inputStream.read(buffer); read > 0; read = inputStream.read(buffer)) {
compressor.write(buffer, 0, read);
}
compressor.finish();
compressor.flush();
oldFile.delete();
gzippedFile.setLastModified(mtime);
log.info("Compressed: "+gzippedFile);
} catch (IOException e) {
log.warning("Got '" + e + "' while compressing '" + oldFile.getPath() + "'.");
}
}
long sumFileSizes() {
long sum = 0;
for (LogFile lf : knownFiles) {
sum += lf.path.length();
}
return sum;
}
private static final Pattern dateFormatRegexp = Pattern.compile(".*/" +
"[0-9][0-9][0-9][0-9]/" +
"[0-9][0-9]/" +
"[0-9][0-9]/" +
"[0-9][0-9]-" +
"[0-9].*");
private static List<LogFile> scanDir(File top) {
List<LogFile> retval = new ArrayList<>();
String[] names = top.list();
if (names != null) {
for (String name : names) {
File sub = new File(top, name);
if (sub.isFile()) {
String pathName = sub.toString();
if (dateFormatRegexp.matcher(pathName).matches()) {
retval.add(new LogFile(sub));
} else {
log.warning("skipping file not matching log archive pattern: "+pathName);
}
} else if (sub.isDirectory()) {
retval.addAll(scanDir(sub));
}
}
}
return retval;
}
static class LogFile {
public final File path;
public final String prefix;
public final int generation;
public final boolean zsuff;
public boolean canCompress(long now) {
if (zsuff) return false;
if (! path.isFile()) return false;
long diff = now - path.lastModified();
if (diff < compressAfterMillis) return false;
return true;
}
private static int generationOf(String name) {
int dash = name.lastIndexOf('-');
if (dash < 0) return 0;
String suff = name.substring(dash + 1);
int r = 0;
for (char ch : suff.toCharArray()) {
if (ch >= '0' && ch <= '9') {
r *= 10;
r += (ch - '0');
} else {
break;
}
}
return r;
}
private static String prefixOf(String name) {
int dash = name.lastIndexOf('-');
if (dash < 0) return name;
return name.substring(0, dash);
}
private static boolean zSuffix(String name) {
if (name.endsWith(".gz")) return true;
return false;
}
public LogFile(File path) {
String name = path.toString();
this.path = path;
this.prefix = prefixOf(name);
this.generation = generationOf(name);
this.zsuff = zSuffix(name);
}
public String toString() {
return "FilesArchived.LogFile{name="+path+" prefix="+prefix+" gen="+generation+" z="+zsuff+"}";
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.