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 |
|---|---|---|---|---|---|
Can do that. | public void removeInstance(ApplicationId id) {
curator.delete(applicationPath(id));
curator.delete(instancePath(id));
} | curator.delete(applicationPath(id)); | public void removeInstance(ApplicationId id) {
curator.delete(applicationPath(id));
curator.delete(instancePath(id));
} | class CuratorDb {
private static final Logger log = Logger.getLogger(CuratorDb.class.getName());
private static final Duration deployLockTimeout = Duration.ofMinutes(30);
private static final Duration defaultLockTimeout = Duration.ofMinutes(5);
private static final Duration defaultTryLockTimeout = Duration.ofSeconds(1);
private static final Path root = Path.fromString("/controller/v1");
private static final Path lockRoot = root.append("locks");
private static final Path tenantRoot = root.append("tenants");
private static final Path applicationRoot = root.append("applications");
private static final Path instanceRoot = root.append("instances");
private static final Path jobRoot = root.append("jobs");
private static final Path controllerRoot = root.append("controllers");
private static final Path routingPoliciesRoot = root.append("routingPolicies");
private static final Path applicationCertificateRoot = root.append("applicationCertificates");
private final StringSetSerializer stringSetSerializer = new StringSetSerializer();
private final VersionStatusSerializer versionStatusSerializer = new VersionStatusSerializer();
private final ControllerVersionSerializer controllerVersionSerializer = new ControllerVersionSerializer();
private final ConfidenceOverrideSerializer confidenceOverrideSerializer = new ConfidenceOverrideSerializer();
private final TenantSerializer tenantSerializer = new TenantSerializer();
private final InstanceSerializer instanceSerializer = new InstanceSerializer();
private final RunSerializer runSerializer = new RunSerializer();
private final OsVersionSerializer osVersionSerializer = new OsVersionSerializer();
private final OsVersionStatusSerializer osVersionStatusSerializer = new OsVersionStatusSerializer(osVersionSerializer);
private final RoutingPolicySerializer routingPolicySerializer = new RoutingPolicySerializer();
private final AuditLogSerializer auditLogSerializer = new AuditLogSerializer();
private final NameServiceQueueSerializer nameServiceQueueSerializer = new NameServiceQueueSerializer();
private final Curator curator;
private final Duration tryLockTimeout;
/**
* All keys, to allow reentrancy.
* This will grow forever, but this should be too slow to be a problem.
*/
private final ConcurrentHashMap<Path, Lock> locks = new ConcurrentHashMap<>();
@Inject
public CuratorDb(Curator curator) {
this(curator, defaultTryLockTimeout);
}
CuratorDb(Curator curator, Duration tryLockTimeout) {
this.curator = curator;
this.tryLockTimeout = tryLockTimeout;
}
/** Returns all hosts configured to be part of this ZooKeeper cluster */
public List<HostName> cluster() {
return Arrays.stream(curator.zooKeeperEnsembleConnectionSpec().split(","))
.filter(hostAndPort -> !hostAndPort.isEmpty())
.map(hostAndPort -> hostAndPort.split(":")[0])
.map(HostName::from)
.collect(Collectors.toList());
}
/** Creates a reentrant lock */
private Lock lock(Path path, Duration timeout) {
curator.create(path);
Lock lock = locks.computeIfAbsent(path, (pathArg) -> new Lock(pathArg.getAbsolute(), curator));
lock.acquire(timeout);
return lock;
}
public Lock lock(TenantName name) {
return lock(lockPath(name), defaultLockTimeout.multipliedBy(2));
}
public Lock lock(ApplicationId id) {
return lock(lockPath(id), defaultLockTimeout.multipliedBy(2));
}
public Lock lockForDeployment(ApplicationId id, ZoneId zone) {
return lock(lockPath(id, zone), deployLockTimeout);
}
public Lock lock(ApplicationId id, JobType type) {
return lock(lockPath(id, type), defaultLockTimeout);
}
public Lock lock(ApplicationId id, JobType type, Step step) throws TimeoutException {
return tryLock(lockPath(id, type, step));
}
public Lock lockRotations() {
return lock(lockRoot.append("rotations"), defaultLockTimeout);
}
public Lock lockConfidenceOverrides() {
return lock(lockRoot.append("confidenceOverrides"), defaultLockTimeout);
}
public Lock lockInactiveJobs() {
return lock(lockRoot.append("inactiveJobsLock"), defaultLockTimeout);
}
public Lock lockMaintenanceJob(String jobName) throws TimeoutException {
return tryLock(lockRoot.append("maintenanceJobLocks").append(jobName));
}
@SuppressWarnings("unused")
public Lock lockProvisionState(String provisionStateId) {
return lock(lockPath(provisionStateId), Duration.ofSeconds(1));
}
public Lock lockOsVersions() {
return lock(lockRoot.append("osTargetVersion"), defaultLockTimeout);
}
public Lock lockOsVersionStatus() {
return lock(lockRoot.append("osVersionStatus"), defaultLockTimeout);
}
public Lock lockRoutingPolicies() {
return lock(lockRoot.append("routingPolicies"), defaultLockTimeout);
}
public Lock lockAuditLog() {
return lock(lockRoot.append("auditLog"), defaultLockTimeout);
}
public Lock lockNameServiceQueue() {
return lock(lockRoot.append("nameServiceQueue"), defaultLockTimeout);
}
/** Try locking with a low timeout, meaning it is OK to fail lock acquisition.
*
* Useful for maintenance jobs, where there is no point in running the jobs back to back.
*/
private Lock tryLock(Path path) throws TimeoutException {
try {
return lock(path, tryLockTimeout);
}
catch (UncheckedTimeoutException e) {
throw new TimeoutException(e.getMessage());
}
}
private <T> Optional<T> read(Path path, Function<byte[], T> mapper) {
return curator.getData(path).filter(data -> data.length > 0).map(mapper);
}
private Optional<Slime> readSlime(Path path) {
return read(path, SlimeUtils::jsonToSlime);
}
private static byte[] asJson(Slime slime) {
try {
return SlimeUtils.toJsonBytes(slime);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public Set<String> readInactiveJobs() {
try {
return readSlime(inactiveJobsPath()).map(stringSetSerializer::fromSlime).orElseGet(HashSet::new);
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Error reading inactive jobs, deleting inactive state");
writeInactiveJobs(Collections.emptySet());
return new HashSet<>();
}
}
public void writeInactiveJobs(Set<String> inactiveJobs) {
curator.set(inactiveJobsPath(), stringSetSerializer.toJson(inactiveJobs));
}
public double readUpgradesPerMinute() {
return read(upgradesPerMinutePath(), ByteBuffer::wrap).map(ByteBuffer::getDouble).orElse(0.125);
}
public void writeUpgradesPerMinute(double n) {
curator.set(upgradesPerMinutePath(), ByteBuffer.allocate(Double.BYTES).putDouble(n).array());
}
public Optional<Integer> readTargetMajorVersion() {
return read(targetMajorVersionPath(), ByteBuffer::wrap).map(ByteBuffer::getInt);
}
public void writeTargetMajorVersion(Optional<Integer> targetMajorVersion) {
if (targetMajorVersion.isPresent())
curator.set(targetMajorVersionPath(), ByteBuffer.allocate(Integer.BYTES).putInt(targetMajorVersion.get()).array());
else
curator.delete(targetMajorVersionPath());
}
public void writeVersionStatus(VersionStatus status) {
curator.set(versionStatusPath(), asJson(versionStatusSerializer.toSlime(status)));
}
public VersionStatus readVersionStatus() {
return readSlime(versionStatusPath()).map(versionStatusSerializer::fromSlime).orElseGet(VersionStatus::empty);
}
public void writeConfidenceOverrides(Map<Version, VespaVersion.Confidence> overrides) {
curator.set(confidenceOverridesPath(), asJson(confidenceOverrideSerializer.toSlime(overrides)));
}
public Map<Version, VespaVersion.Confidence> readConfidenceOverrides() {
return readSlime(confidenceOverridesPath()).map(confidenceOverrideSerializer::fromSlime)
.orElseGet(Collections::emptyMap);
}
public void writeControllerVersion(HostName hostname, ControllerVersion version) {
curator.set(controllerPath(hostname.value()), asJson(controllerVersionSerializer.toSlime(version)));
}
public ControllerVersion readControllerVersion(HostName hostname) {
return readSlime(controllerPath(hostname.value()))
.map(controllerVersionSerializer::fromSlime)
.orElse(ControllerVersion.CURRENT);
}
public void writeOsVersions(Set<OsVersion> versions) {
curator.set(osTargetVersionPath(), asJson(osVersionSerializer.toSlime(versions)));
}
public Set<OsVersion> readOsVersions() {
return readSlime(osTargetVersionPath()).map(osVersionSerializer::fromSlime).orElseGet(Collections::emptySet);
}
public void writeOsVersionStatus(OsVersionStatus status) {
curator.set(osVersionStatusPath(), asJson(osVersionStatusSerializer.toSlime(status)));
}
public OsVersionStatus readOsVersionStatus() {
return readSlime(osVersionStatusPath()).map(osVersionStatusSerializer::fromSlime).orElse(OsVersionStatus.empty);
}
public void writeTenant(Tenant tenant) {
curator.set(tenantPath(tenant.name()), asJson(tenantSerializer.toSlime(tenant)));
}
public Optional<Tenant> readTenant(TenantName name) {
return readSlime(tenantPath(name)).map(tenantSerializer::tenantFrom);
}
public List<Tenant> readTenants() {
return readTenantNames().stream()
.map(this::readTenant)
.flatMap(Optional::stream)
.collect(collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
}
public List<TenantName> readTenantNames() {
return curator.getChildren(tenantRoot).stream()
.map(TenantName::from)
.collect(Collectors.toList());
}
public void removeTenant(TenantName name) {
curator.delete(tenantPath(name));
}
public void writeInstance(Instance instance) {
curator.set(applicationPath(instance.id()), asJson(instanceSerializer.toSlime(instance)));
curator.set(instancePath(instance.id()), asJson(instanceSerializer.toSlime(instance)));
}
public Optional<Instance> readInstance(ApplicationId application) {
return readSlime(instancePath(application)).or(() -> readSlime(applicationPath(application)))
.map(instanceSerializer::fromSlime);
}
public List<Instance> readInstances() {
return readInstances(ignored -> true);
}
public List<Instance> readInstances(TenantName name) {
return readInstances(application -> application.tenant().equals(name));
}
private Stream<ApplicationId> readInstanceIds() {
return Stream.concat(curator.getChildren(applicationRoot).stream()
.filter(id -> id.split(":").length == 3),
curator.getChildren(instanceRoot).stream())
.distinct()
.map(ApplicationId::fromSerializedForm);
}
private List<Instance> readInstances(Predicate<ApplicationId> instanceFilter) {
return readInstanceIds().filter(instanceFilter)
.map(this::readInstance)
.flatMap(Optional::stream)
.collect(Collectors.toUnmodifiableList());
}
public void writeLastRun(Run run) {
curator.set(lastRunPath(run.id().application(), run.id().type()), asJson(runSerializer.toSlime(run)));
}
public void writeHistoricRuns(ApplicationId id, JobType type, Iterable<Run> runs) {
curator.set(runsPath(id, type), asJson(runSerializer.toSlime(runs)));
}
public Optional<Run> readLastRun(ApplicationId id, JobType type) {
return readSlime(lastRunPath(id, type)).map(runSerializer::runFromSlime);
}
public SortedMap<RunId, Run> readHistoricRuns(ApplicationId id, JobType type) {
return readSlime(runsPath(id, type)).map(runSerializer::runsFromSlime).orElse(new TreeMap<>(comparing(RunId::number)));
}
public void deleteRunData(ApplicationId id, JobType type) {
curator.delete(runsPath(id, type));
curator.delete(lastRunPath(id, type));
}
public void deleteRunData(ApplicationId id) {
curator.delete(jobRoot.append(id.serializedForm()));
}
public List<ApplicationId> applicationsWithJobs() {
return curator.getChildren(jobRoot).stream()
.map(ApplicationId::fromSerializedForm)
.collect(Collectors.toList());
}
public Optional<byte[]> readLog(ApplicationId id, JobType type, long chunkId) {
return curator.getData(logPath(id, type, chunkId));
}
public void writeLog(ApplicationId id, JobType type, long chunkId, byte[] log) {
curator.set(logPath(id, type, chunkId), log);
}
public void deleteLog(ApplicationId id, JobType type) {
curator.delete(runsPath(id, type).append("logs"));
}
public Optional<Long> readLastLogEntryId(ApplicationId id, JobType type) {
return curator.getData(lastLogPath(id, type))
.map(String::new).map(Long::parseLong);
}
public void writeLastLogEntryId(ApplicationId id, JobType type, long lastId) {
curator.set(lastLogPath(id, type), Long.toString(lastId).getBytes());
}
public LongStream getLogChunkIds(ApplicationId id, JobType type) {
return curator.getChildren(runsPath(id, type).append("logs")).stream()
.mapToLong(Long::parseLong)
.sorted();
}
public AuditLog readAuditLog() {
return readSlime(auditLogPath()).map(auditLogSerializer::fromSlime)
.orElse(AuditLog.empty);
}
public void writeAuditLog(AuditLog log) {
curator.set(auditLogPath(), asJson(auditLogSerializer.toSlime(log)));
}
public NameServiceQueue readNameServiceQueue() {
return readSlime(nameServiceQueuePath()).map(nameServiceQueueSerializer::fromSlime)
.orElse(NameServiceQueue.EMPTY);
}
public void writeNameServiceQueue(NameServiceQueue queue) {
curator.set(nameServiceQueuePath(), asJson(nameServiceQueueSerializer.toSlime(queue)));
}
@SuppressWarnings("unused")
public Optional<byte[]> readProvisionState(String provisionId) {
return curator.getData(provisionStatePath(provisionId));
}
@SuppressWarnings("unused")
public void writeProvisionState(String provisionId, byte[] data) {
curator.set(provisionStatePath(provisionId), data);
}
@SuppressWarnings("unused")
public List<String> readProvisionStateIds() {
return curator.getChildren(provisionStatePath());
}
public void writeRoutingPolicies(ApplicationId application, Set<RoutingPolicy> policies) {
curator.set(routingPolicyPath(application), asJson(routingPolicySerializer.toSlime(policies)));
}
public Map<ApplicationId, Set<RoutingPolicy>> readRoutingPolicies() {
return curator.getChildren(routingPoliciesRoot).stream()
.map(ApplicationId::fromSerializedForm)
.collect(Collectors.toUnmodifiableMap(Function.identity(), this::readRoutingPolicies));
}
public Set<RoutingPolicy> readRoutingPolicies(ApplicationId application) {
return readSlime(routingPolicyPath(application)).map(slime -> routingPolicySerializer.fromSlime(application, slime))
.orElseGet(Collections::emptySet);
}
public void writeApplicationCertificate(ApplicationId applicationId, ApplicationCertificate applicationCertificate) {
curator.set(applicationCertificatePath(applicationId), applicationCertificate.secretsKeyNamePrefix().getBytes());
}
public Optional<ApplicationCertificate> readApplicationCertificate(ApplicationId applicationId) {
return curator.getData(applicationCertificatePath(applicationId)).map(String::new).map(ApplicationCertificate::new);
}
private Path lockPath(TenantName tenant) {
return lockRoot
.append(tenant.value());
}
private Path lockPath(ApplicationId application) {
return lockPath(application.tenant())
.append(application.application().value())
.append(application.instance().value());
}
private Path lockPath(ApplicationId application, ZoneId zone) {
return lockPath(application)
.append(zone.environment().value())
.append(zone.region().value());
}
private Path lockPath(ApplicationId application, JobType type) {
return lockPath(application)
.append(type.jobName());
}
private Path lockPath(ApplicationId application, JobType type, Step step) {
return lockPath(application, type)
.append(step.name());
}
private Path lockPath(String provisionId) {
return lockRoot
.append(provisionStatePath())
.append(provisionId);
}
private static Path inactiveJobsPath() {
return root.append("inactiveJobs");
}
private static Path upgradesPerMinutePath() {
return root.append("upgrader").append("upgradesPerMinute");
}
private static Path targetMajorVersionPath() {
return root.append("upgrader").append("targetMajorVersion");
}
private static Path confidenceOverridesPath() {
return root.append("upgrader").append("confidenceOverrides");
}
private static Path osTargetVersionPath() {
return root.append("osUpgrader").append("targetVersion");
}
private static Path osVersionStatusPath() {
return root.append("osVersionStatus");
}
private static Path versionStatusPath() {
return root.append("versionStatus");
}
private static Path routingPolicyPath(ApplicationId application) {
return routingPoliciesRoot.append(application.serializedForm());
}
private static Path nameServiceQueuePath() {
return root.append("nameServiceQueue");
}
private static Path auditLogPath() {
return root.append("auditLog");
}
private static Path provisionStatePath() {
return root.append("provisioning").append("states");
}
private static Path provisionStatePath(String provisionId) {
return provisionStatePath().append(provisionId);
}
private static Path tenantPath(TenantName name) {
return tenantRoot.append(name.value());
}
private static Path applicationPath(ApplicationId application) {
return applicationRoot.append(application.serializedForm());
}
private static Path instancePath(ApplicationId id) {
return instanceRoot.append(id.serializedForm());
}
private static Path runsPath(ApplicationId id, JobType type) {
return jobRoot.append(id.serializedForm()).append(type.jobName());
}
private static Path lastRunPath(ApplicationId id, JobType type) {
return runsPath(id, type).append("last");
}
private static Path logPath(ApplicationId id, JobType type, long first) {
return runsPath(id, type).append("logs").append(Long.toString(first));
}
private static Path lastLogPath(ApplicationId id, JobType type) {
return runsPath(id, type).append("logs");
}
private static Path controllerPath(String hostname) {
return controllerRoot.append(hostname);
}
private static Path applicationCertificatePath(ApplicationId id) {
return applicationCertificateRoot.append(id.serializedForm());
}
} | class CuratorDb {
private static final Logger log = Logger.getLogger(CuratorDb.class.getName());
private static final Duration deployLockTimeout = Duration.ofMinutes(30);
private static final Duration defaultLockTimeout = Duration.ofMinutes(5);
private static final Duration defaultTryLockTimeout = Duration.ofSeconds(1);
private static final Path root = Path.fromString("/controller/v1");
private static final Path lockRoot = root.append("locks");
private static final Path tenantRoot = root.append("tenants");
private static final Path applicationRoot = root.append("applications");
private static final Path instanceRoot = root.append("instances");
private static final Path jobRoot = root.append("jobs");
private static final Path controllerRoot = root.append("controllers");
private static final Path routingPoliciesRoot = root.append("routingPolicies");
private static final Path applicationCertificateRoot = root.append("applicationCertificates");
private final StringSetSerializer stringSetSerializer = new StringSetSerializer();
private final VersionStatusSerializer versionStatusSerializer = new VersionStatusSerializer();
private final ControllerVersionSerializer controllerVersionSerializer = new ControllerVersionSerializer();
private final ConfidenceOverrideSerializer confidenceOverrideSerializer = new ConfidenceOverrideSerializer();
private final TenantSerializer tenantSerializer = new TenantSerializer();
private final InstanceSerializer instanceSerializer = new InstanceSerializer();
private final RunSerializer runSerializer = new RunSerializer();
private final OsVersionSerializer osVersionSerializer = new OsVersionSerializer();
private final OsVersionStatusSerializer osVersionStatusSerializer = new OsVersionStatusSerializer(osVersionSerializer);
private final RoutingPolicySerializer routingPolicySerializer = new RoutingPolicySerializer();
private final AuditLogSerializer auditLogSerializer = new AuditLogSerializer();
private final NameServiceQueueSerializer nameServiceQueueSerializer = new NameServiceQueueSerializer();
private final Curator curator;
private final Duration tryLockTimeout;
/**
* All keys, to allow reentrancy.
* This will grow forever, but this should be too slow to be a problem.
*/
private final ConcurrentHashMap<Path, Lock> locks = new ConcurrentHashMap<>();
@Inject
public CuratorDb(Curator curator) {
this(curator, defaultTryLockTimeout);
}
CuratorDb(Curator curator, Duration tryLockTimeout) {
this.curator = curator;
this.tryLockTimeout = tryLockTimeout;
}
/** Returns all hosts configured to be part of this ZooKeeper cluster */
public List<HostName> cluster() {
return Arrays.stream(curator.zooKeeperEnsembleConnectionSpec().split(","))
.filter(hostAndPort -> !hostAndPort.isEmpty())
.map(hostAndPort -> hostAndPort.split(":")[0])
.map(HostName::from)
.collect(Collectors.toList());
}
/** Creates a reentrant lock */
private Lock lock(Path path, Duration timeout) {
curator.create(path);
Lock lock = locks.computeIfAbsent(path, (pathArg) -> new Lock(pathArg.getAbsolute(), curator));
lock.acquire(timeout);
return lock;
}
public Lock lock(TenantName name) {
return lock(lockPath(name), defaultLockTimeout.multipliedBy(2));
}
public Lock lock(ApplicationId id) {
return lock(lockPath(id), defaultLockTimeout.multipliedBy(2));
}
public Lock lockForDeployment(ApplicationId id, ZoneId zone) {
return lock(lockPath(id, zone), deployLockTimeout);
}
public Lock lock(ApplicationId id, JobType type) {
return lock(lockPath(id, type), defaultLockTimeout);
}
public Lock lock(ApplicationId id, JobType type, Step step) throws TimeoutException {
return tryLock(lockPath(id, type, step));
}
public Lock lockRotations() {
return lock(lockRoot.append("rotations"), defaultLockTimeout);
}
public Lock lockConfidenceOverrides() {
return lock(lockRoot.append("confidenceOverrides"), defaultLockTimeout);
}
public Lock lockInactiveJobs() {
return lock(lockRoot.append("inactiveJobsLock"), defaultLockTimeout);
}
public Lock lockMaintenanceJob(String jobName) throws TimeoutException {
return tryLock(lockRoot.append("maintenanceJobLocks").append(jobName));
}
@SuppressWarnings("unused")
public Lock lockProvisionState(String provisionStateId) {
return lock(lockPath(provisionStateId), Duration.ofSeconds(1));
}
public Lock lockOsVersions() {
return lock(lockRoot.append("osTargetVersion"), defaultLockTimeout);
}
public Lock lockOsVersionStatus() {
return lock(lockRoot.append("osVersionStatus"), defaultLockTimeout);
}
public Lock lockRoutingPolicies() {
return lock(lockRoot.append("routingPolicies"), defaultLockTimeout);
}
public Lock lockAuditLog() {
return lock(lockRoot.append("auditLog"), defaultLockTimeout);
}
public Lock lockNameServiceQueue() {
return lock(lockRoot.append("nameServiceQueue"), defaultLockTimeout);
}
/** Try locking with a low timeout, meaning it is OK to fail lock acquisition.
*
* Useful for maintenance jobs, where there is no point in running the jobs back to back.
*/
private Lock tryLock(Path path) throws TimeoutException {
try {
return lock(path, tryLockTimeout);
}
catch (UncheckedTimeoutException e) {
throw new TimeoutException(e.getMessage());
}
}
private <T> Optional<T> read(Path path, Function<byte[], T> mapper) {
return curator.getData(path).filter(data -> data.length > 0).map(mapper);
}
private Optional<Slime> readSlime(Path path) {
return read(path, SlimeUtils::jsonToSlime);
}
private static byte[] asJson(Slime slime) {
try {
return SlimeUtils.toJsonBytes(slime);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public Set<String> readInactiveJobs() {
try {
return readSlime(inactiveJobsPath()).map(stringSetSerializer::fromSlime).orElseGet(HashSet::new);
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Error reading inactive jobs, deleting inactive state");
writeInactiveJobs(Collections.emptySet());
return new HashSet<>();
}
}
public void writeInactiveJobs(Set<String> inactiveJobs) {
curator.set(inactiveJobsPath(), stringSetSerializer.toJson(inactiveJobs));
}
public double readUpgradesPerMinute() {
return read(upgradesPerMinutePath(), ByteBuffer::wrap).map(ByteBuffer::getDouble).orElse(0.125);
}
public void writeUpgradesPerMinute(double n) {
curator.set(upgradesPerMinutePath(), ByteBuffer.allocate(Double.BYTES).putDouble(n).array());
}
public Optional<Integer> readTargetMajorVersion() {
return read(targetMajorVersionPath(), ByteBuffer::wrap).map(ByteBuffer::getInt);
}
public void writeTargetMajorVersion(Optional<Integer> targetMajorVersion) {
if (targetMajorVersion.isPresent())
curator.set(targetMajorVersionPath(), ByteBuffer.allocate(Integer.BYTES).putInt(targetMajorVersion.get()).array());
else
curator.delete(targetMajorVersionPath());
}
public void writeVersionStatus(VersionStatus status) {
curator.set(versionStatusPath(), asJson(versionStatusSerializer.toSlime(status)));
}
public VersionStatus readVersionStatus() {
return readSlime(versionStatusPath()).map(versionStatusSerializer::fromSlime).orElseGet(VersionStatus::empty);
}
public void writeConfidenceOverrides(Map<Version, VespaVersion.Confidence> overrides) {
curator.set(confidenceOverridesPath(), asJson(confidenceOverrideSerializer.toSlime(overrides)));
}
public Map<Version, VespaVersion.Confidence> readConfidenceOverrides() {
return readSlime(confidenceOverridesPath()).map(confidenceOverrideSerializer::fromSlime)
.orElseGet(Collections::emptyMap);
}
public void writeControllerVersion(HostName hostname, ControllerVersion version) {
curator.set(controllerPath(hostname.value()), asJson(controllerVersionSerializer.toSlime(version)));
}
public ControllerVersion readControllerVersion(HostName hostname) {
return readSlime(controllerPath(hostname.value()))
.map(controllerVersionSerializer::fromSlime)
.orElse(ControllerVersion.CURRENT);
}
public void writeOsVersions(Set<OsVersion> versions) {
curator.set(osTargetVersionPath(), asJson(osVersionSerializer.toSlime(versions)));
}
public Set<OsVersion> readOsVersions() {
return readSlime(osTargetVersionPath()).map(osVersionSerializer::fromSlime).orElseGet(Collections::emptySet);
}
public void writeOsVersionStatus(OsVersionStatus status) {
curator.set(osVersionStatusPath(), asJson(osVersionStatusSerializer.toSlime(status)));
}
public OsVersionStatus readOsVersionStatus() {
return readSlime(osVersionStatusPath()).map(osVersionStatusSerializer::fromSlime).orElse(OsVersionStatus.empty);
}
public void writeTenant(Tenant tenant) {
curator.set(tenantPath(tenant.name()), asJson(tenantSerializer.toSlime(tenant)));
}
public Optional<Tenant> readTenant(TenantName name) {
return readSlime(tenantPath(name)).map(tenantSerializer::tenantFrom);
}
public List<Tenant> readTenants() {
return readTenantNames().stream()
.map(this::readTenant)
.flatMap(Optional::stream)
.collect(collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
}
public List<TenantName> readTenantNames() {
return curator.getChildren(tenantRoot).stream()
.map(TenantName::from)
.collect(Collectors.toList());
}
public void removeTenant(TenantName name) {
curator.delete(tenantPath(name));
}
public void writeInstance(Instance instance) {
curator.set(applicationPath(instance.id()), asJson(instanceSerializer.toSlime(instance)));
curator.set(instancePath(instance.id()), asJson(instanceSerializer.toSlime(instance)));
}
public Optional<Instance> readInstance(ApplicationId application) {
return readSlime(instancePath(application)).or(() -> readSlime(applicationPath(application)))
.map(instanceSerializer::fromSlime);
}
public List<Instance> readInstances() {
return readInstances(ignored -> true);
}
public List<Instance> readInstances(TenantName name) {
return readInstances(application -> application.tenant().equals(name));
}
private Stream<ApplicationId> readInstanceIds() {
return Stream.concat(curator.getChildren(applicationRoot).stream()
.filter(id -> id.split(":").length == 3),
curator.getChildren(instanceRoot).stream())
.distinct()
.map(ApplicationId::fromSerializedForm);
}
private List<Instance> readInstances(Predicate<ApplicationId> instanceFilter) {
return readInstanceIds().filter(instanceFilter)
.map(this::readInstance)
.flatMap(Optional::stream)
.collect(Collectors.toUnmodifiableList());
}
public void writeLastRun(Run run) {
curator.set(lastRunPath(run.id().application(), run.id().type()), asJson(runSerializer.toSlime(run)));
}
public void writeHistoricRuns(ApplicationId id, JobType type, Iterable<Run> runs) {
curator.set(runsPath(id, type), asJson(runSerializer.toSlime(runs)));
}
public Optional<Run> readLastRun(ApplicationId id, JobType type) {
return readSlime(lastRunPath(id, type)).map(runSerializer::runFromSlime);
}
public SortedMap<RunId, Run> readHistoricRuns(ApplicationId id, JobType type) {
return readSlime(runsPath(id, type)).map(runSerializer::runsFromSlime).orElse(new TreeMap<>(comparing(RunId::number)));
}
public void deleteRunData(ApplicationId id, JobType type) {
curator.delete(runsPath(id, type));
curator.delete(lastRunPath(id, type));
}
public void deleteRunData(ApplicationId id) {
curator.delete(jobRoot.append(id.serializedForm()));
}
public List<ApplicationId> applicationsWithJobs() {
return curator.getChildren(jobRoot).stream()
.map(ApplicationId::fromSerializedForm)
.collect(Collectors.toList());
}
public Optional<byte[]> readLog(ApplicationId id, JobType type, long chunkId) {
return curator.getData(logPath(id, type, chunkId));
}
public void writeLog(ApplicationId id, JobType type, long chunkId, byte[] log) {
curator.set(logPath(id, type, chunkId), log);
}
public void deleteLog(ApplicationId id, JobType type) {
curator.delete(runsPath(id, type).append("logs"));
}
public Optional<Long> readLastLogEntryId(ApplicationId id, JobType type) {
return curator.getData(lastLogPath(id, type))
.map(String::new).map(Long::parseLong);
}
public void writeLastLogEntryId(ApplicationId id, JobType type, long lastId) {
curator.set(lastLogPath(id, type), Long.toString(lastId).getBytes());
}
public LongStream getLogChunkIds(ApplicationId id, JobType type) {
return curator.getChildren(runsPath(id, type).append("logs")).stream()
.mapToLong(Long::parseLong)
.sorted();
}
public AuditLog readAuditLog() {
return readSlime(auditLogPath()).map(auditLogSerializer::fromSlime)
.orElse(AuditLog.empty);
}
public void writeAuditLog(AuditLog log) {
curator.set(auditLogPath(), asJson(auditLogSerializer.toSlime(log)));
}
public NameServiceQueue readNameServiceQueue() {
return readSlime(nameServiceQueuePath()).map(nameServiceQueueSerializer::fromSlime)
.orElse(NameServiceQueue.EMPTY);
}
public void writeNameServiceQueue(NameServiceQueue queue) {
curator.set(nameServiceQueuePath(), asJson(nameServiceQueueSerializer.toSlime(queue)));
}
@SuppressWarnings("unused")
public Optional<byte[]> readProvisionState(String provisionId) {
return curator.getData(provisionStatePath(provisionId));
}
@SuppressWarnings("unused")
public void writeProvisionState(String provisionId, byte[] data) {
curator.set(provisionStatePath(provisionId), data);
}
@SuppressWarnings("unused")
public List<String> readProvisionStateIds() {
return curator.getChildren(provisionStatePath());
}
public void writeRoutingPolicies(ApplicationId application, Set<RoutingPolicy> policies) {
curator.set(routingPolicyPath(application), asJson(routingPolicySerializer.toSlime(policies)));
}
public Map<ApplicationId, Set<RoutingPolicy>> readRoutingPolicies() {
return curator.getChildren(routingPoliciesRoot).stream()
.map(ApplicationId::fromSerializedForm)
.collect(Collectors.toUnmodifiableMap(Function.identity(), this::readRoutingPolicies));
}
public Set<RoutingPolicy> readRoutingPolicies(ApplicationId application) {
return readSlime(routingPolicyPath(application)).map(slime -> routingPolicySerializer.fromSlime(application, slime))
.orElseGet(Collections::emptySet);
}
public void writeApplicationCertificate(ApplicationId applicationId, ApplicationCertificate applicationCertificate) {
curator.set(applicationCertificatePath(applicationId), applicationCertificate.secretsKeyNamePrefix().getBytes());
}
public Optional<ApplicationCertificate> readApplicationCertificate(ApplicationId applicationId) {
return curator.getData(applicationCertificatePath(applicationId)).map(String::new).map(ApplicationCertificate::new);
}
private Path lockPath(TenantName tenant) {
return lockRoot
.append(tenant.value());
}
private Path lockPath(ApplicationId application) {
return lockPath(application.tenant())
.append(application.application().value())
.append(application.instance().value());
}
private Path lockPath(ApplicationId application, ZoneId zone) {
return lockPath(application)
.append(zone.environment().value())
.append(zone.region().value());
}
private Path lockPath(ApplicationId application, JobType type) {
return lockPath(application)
.append(type.jobName());
}
private Path lockPath(ApplicationId application, JobType type, Step step) {
return lockPath(application, type)
.append(step.name());
}
private Path lockPath(String provisionId) {
return lockRoot
.append(provisionStatePath())
.append(provisionId);
}
private static Path inactiveJobsPath() {
return root.append("inactiveJobs");
}
private static Path upgradesPerMinutePath() {
return root.append("upgrader").append("upgradesPerMinute");
}
private static Path targetMajorVersionPath() {
return root.append("upgrader").append("targetMajorVersion");
}
private static Path confidenceOverridesPath() {
return root.append("upgrader").append("confidenceOverrides");
}
private static Path osTargetVersionPath() {
return root.append("osUpgrader").append("targetVersion");
}
private static Path osVersionStatusPath() {
return root.append("osVersionStatus");
}
private static Path versionStatusPath() {
return root.append("versionStatus");
}
private static Path routingPolicyPath(ApplicationId application) {
return routingPoliciesRoot.append(application.serializedForm());
}
private static Path nameServiceQueuePath() {
return root.append("nameServiceQueue");
}
private static Path auditLogPath() {
return root.append("auditLog");
}
private static Path provisionStatePath() {
return root.append("provisioning").append("states");
}
private static Path provisionStatePath(String provisionId) {
return provisionStatePath().append(provisionId);
}
private static Path tenantPath(TenantName name) {
return tenantRoot.append(name.value());
}
private static Path applicationPath(ApplicationId application) {
return applicationRoot.append(application.serializedForm());
}
private static Path instancePath(ApplicationId id) {
return instanceRoot.append(id.serializedForm());
}
private static Path runsPath(ApplicationId id, JobType type) {
return jobRoot.append(id.serializedForm()).append(type.jobName());
}
private static Path lastRunPath(ApplicationId id, JobType type) {
return runsPath(id, type).append("last");
}
private static Path logPath(ApplicationId id, JobType type, long first) {
return runsPath(id, type).append("logs").append(Long.toString(first));
}
private static Path lastLogPath(ApplicationId id, JobType type) {
return runsPath(id, type).append("logs");
}
private static Path controllerPath(String hostname) {
return controllerRoot.append(hostname);
}
private static Path applicationCertificatePath(ApplicationId id) {
return applicationCertificateRoot.append(id.serializedForm());
}
} |
```suggestion && ! directRoutingUseHttps.with(FetchVector.Dimension.APPLICATION_ID, id.tester().id().serializedForm()).value(); ``` | Optional<URI> testerEndpoint(RunId id) {
DeploymentId testerId = new DeploymentId(id.tester().id(), id.type().zone(controller.system()));
boolean useHttp = controller.system().isPublic()
&& ! directRoutingUseHttps.with(FetchVector.Dimension.APPLICATION_ID, id.tester().id().serializedForm()).value();
return controller.applications().getDeploymentEndpoints(testerId)
.stream().findAny()
.or(() -> controller.applications().routingPolicies().get(testerId).stream()
.findAny()
.map(policy -> policy.endpointIn(controller.system()).url()))
.map(uri -> useHttp ? URI.create("http:
} | && ! directRoutingUseHttps.with(FetchVector.Dimension.APPLICATION_ID, id.tester().id().serializedForm()).value(); | Optional<URI> testerEndpoint(RunId id) {
DeploymentId testerId = new DeploymentId(id.tester().id(), id.type().zone(controller.system()));
boolean useHttp = controller.system().isPublic()
&& ! directRoutingUseHttps.with(FetchVector.Dimension.APPLICATION_ID, id.tester().id().serializedForm()).value();
return controller.applications().getDeploymentEndpoints(testerId)
.stream().findAny()
.or(() -> controller.applications().routingPolicies().get(testerId).stream()
.findAny()
.map(policy -> policy.endpointIn(controller.system()).url()))
.map(uri -> useHttp ? URI.create("http:
} | class JobController {
private static final int historyLength = 256;
private static final Duration maxHistoryAge = Duration.ofDays(60);
private final Controller controller;
private final CuratorDb curator;
private final BufferedLogStore logs;
private final TesterCloud cloud;
private final Badges badges;
private final BooleanFlag directRoutingUseHttps;
private AtomicReference<Consumer<Run>> runner = new AtomicReference<>(__ -> { });
public JobController(Controller controller, FlagSource flagSource) {
this.controller = controller;
this.curator = controller.curator();
this.logs = new BufferedLogStore(curator, controller.serviceRegistry().runDataStore());
this.cloud = controller.serviceRegistry().testerCloud();
this.badges = new Badges(controller.zoneRegistry().badgeUrl());
this.directRoutingUseHttps = Flags.DIRECT_ROUTING_USE_HTTPS_4443.bindTo(flagSource);
}
public TesterCloud cloud() { return cloud; }
public int historyLength() { return historyLength; }
public void setRunner(Consumer<Run> runner) { this.runner.set(runner); }
/** Rewrite all job data with the newest format. */
public void updateStorage() {
for (ApplicationId id : applications())
for (JobType type : jobs(id)) {
locked(id, type, runs -> {
curator.readLastRun(id, type).ifPresent(curator::writeLastRun);
});
}
}
/** Returns all entries currently logged for the given run. */
public Optional<RunLog> details(RunId id) {
return details(id, -1);
}
/** Returns the logged entries for the given run, which are after the given id threshold. */
public Optional<RunLog> details(RunId id, long after) {
try (Lock __ = curator.lock(id.application(), id.type())) {
Run run = runs(id.application(), id.type()).get(id);
if (run == null)
return Optional.empty();
return active(id).isPresent()
? Optional.of(logs.readActive(id.application(), id.type(), after))
: logs.readFinished(id, after);
}
}
/** Stores the given log entries for the given run and step. */
public void log(RunId id, Step step, List<LogEntry> entries) {
locked(id, __ -> {
logs.append(id.application(), id.type(), step, entries);
return __;
});
}
/** Stores the given log messages for the given run and step. */
public void log(RunId id, Step step, Level level, List<String> messages) {
log(id, step, messages.stream()
.map(message -> new LogEntry(0, controller.clock().instant(), LogEntry.typeOf(level), message))
.collect(toList()));
}
/** Stores the given log message for the given run and step. */
public void log(RunId id, Step step, Level level, String message) {
log(id, step, level, Collections.singletonList(message));
}
/** Fetches any new Vespa log entries, and records the timestamp of the last of these, for continuation. */
public void updateVespaLog(RunId id) {
locked(id, run -> {
if ( ! run.steps().containsKey(copyVespaLogs))
return run;
ZoneId zone = id.type().zone(controller.system());
Optional<Deployment> deployment = Optional.ofNullable(controller.applications().require(id.application())
.deployments().get(zone));
if (deployment.isEmpty() || deployment.get().at().isBefore(run.start()))
return run;
Instant from = run.lastVespaLogTimestamp().isAfter(deployment.get().at()) ? run.lastVespaLogTimestamp() : deployment.get().at();
List<LogEntry> log = LogEntry.parseVespaLog(controller.serviceRegistry().configServer()
.getLogs(new DeploymentId(id.application(), zone),
Map.of("from", Long.toString(from.toEpochMilli()))),
from);
if (log.isEmpty())
return run;
logs.append(id.application(), id.type(), Step.copyVespaLogs, log);
return run.with(log.get(log.size() - 1).at());
});
}
/** Fetches any new test log entries, and records the id of the last of these, for continuation. */
public void updateTestLog(RunId id) {
locked(id, run -> {
if ( ! run.readySteps().contains(endTests))
return run;
Optional<URI> testerEndpoint = testerEndpoint(id);
if ( ! testerEndpoint.isPresent())
return run;
List<LogEntry> entries = cloud.getLog(testerEndpoint.get(), run.lastTestLogEntry());
if (entries.isEmpty())
return run;
logs.append(id.application(), id.type(), endTests, entries);
return run.with(entries.stream().mapToLong(LogEntry::id).max().getAsLong());
});
}
/** Stores the given certificate as the tester certificate for this run, or throws if it's already set. */
public void storeTesterCertificate(RunId id, X509Certificate testerCertificate) {
locked(id, run -> run.with(testerCertificate));
}
/** Returns a list of all application which have registered. */
public List<ApplicationId> applications() {
return copyOf(controller.applications().asList().stream()
.filter(application -> application.deploymentJobs().deployedInternally())
.map(Application::id)
.iterator());
}
/** Returns all job types which have been run for the given application. */
public List<JobType> jobs(ApplicationId id) {
return copyOf(Stream.of(JobType.values())
.filter(type -> last(id, type).isPresent())
.iterator());
}
/** Returns an immutable map of all known runs for the given application and job type. */
public Map<RunId, Run> runs(ApplicationId id, JobType type) {
SortedMap<RunId, Run> runs = curator.readHistoricRuns(id, type);
last(id, type).ifPresent(run -> runs.put(run.id(), run));
return ImmutableMap.copyOf(runs);
}
/** Returns the run with the given id, if it exists. */
public Optional<Run> run(RunId id) {
return runs(id.application(), id.type()).values().stream()
.filter(run -> run.id().equals(id))
.findAny();
}
/** Returns the last run of the given type, for the given application, if one has been run. */
public Optional<Run> last(ApplicationId id, JobType type) {
return curator.readLastRun(id, type);
}
/** Returns the run with the given id, provided it is still active. */
public Optional<Run> active(RunId id) {
return last(id.application(), id.type())
.filter(run -> ! run.hasEnded())
.filter(run -> run.id().equals(id));
}
/** Returns a list of all active runs. */
public List<Run> active() {
return copyOf(applications().stream()
.flatMap(id -> Stream.of(JobType.values())
.map(type -> last(id, type))
.flatMap(Optional::stream)
.filter(run -> ! run.hasEnded()))
.iterator());
}
/** Changes the status of the given step, for the given run, provided it is still active. */
public void update(RunId id, RunStatus status, LockedStep step) {
locked(id, run -> run.with(status, step));
}
/** Changes the status of the given run to inactive, and stores it as a historic run. */
public void finish(RunId id) {
locked(id, run -> {
Run finishedRun = run.finished(controller.clock().instant());
locked(id.application(), id.type(), runs -> {
runs.put(run.id(), finishedRun);
long last = id.number();
var oldEntries = runs.entrySet().iterator();
for (var old = oldEntries.next();
old.getKey().number() <= last - historyLength
|| old.getValue().start().isBefore(controller.clock().instant().minus(maxHistoryAge));
old = oldEntries.next()) {
logs.delete(old.getKey());
oldEntries.remove();
}
});
logs.flush(id);
return finishedRun;
});
}
/** Marks the given run as aborted; no further normal steps will run, but run-always steps will try to succeed. */
public void abort(RunId id) {
locked(id, run -> run.aborted());
}
/**
* Accepts and stores a new application package and test jar pair under a generated application version key.
*/
public ApplicationVersion submit(ApplicationId id, SourceRevision revision, String authorEmail, long projectId,
ApplicationPackage applicationPackage, byte[] testPackageBytes) {
AtomicReference<ApplicationVersion> version = new AtomicReference<>();
controller.applications().lockOrThrow(id, application -> {
if ( ! application.get().deploymentJobs().deployedInternally())
application = registered(application);
long run = nextBuild(id);
if (applicationPackage.compileVersion().isPresent() && applicationPackage.buildTime().isPresent())
version.set(ApplicationVersion.from(revision, run, authorEmail,
applicationPackage.compileVersion().get(),
applicationPackage.buildTime().get()));
else
version.set(ApplicationVersion.from(revision, run, authorEmail));
controller.applications().applicationStore().put(id,
version.get(),
applicationPackage.zippedContent());
controller.applications().applicationStore().put(TesterId.of(id),
version.get(),
testPackageBytes);
prunePackages(id);
controller.applications().storeWithUpdatedConfig(application, applicationPackage);
controller.applications().deploymentTrigger().notifyOfCompletion(DeploymentJobs.JobReport.ofSubmission(id, projectId, version.get()));
});
return version.get();
}
/** Registers the given application, copying necessary application packages, and returns the modified version. */
private LockedApplication registered(LockedApplication application) {
application.get().productionDeployments().values().stream()
.map(Deployment::applicationVersion)
.distinct()
.forEach(appVersion -> {
byte[] content = controller.applications().artifacts().getApplicationPackage(application.get().id(), appVersion.id());
controller.applications().applicationStore().put(application.get().id(), appVersion, content);
});
return application.withChange(application.get().change().withoutPlatform().withoutApplication())
.withBuiltInternally(true);
}
/** Orders a run of the given type, or throws an IllegalStateException if that job type is already running. */
public void start(ApplicationId id, JobType type, Versions versions) {
if ( ! type.environment().isManuallyDeployed() && versions.targetApplication().isUnknown())
throw new IllegalArgumentException("Target application must be a valid reference.");
controller.applications().lockIfPresent(id, application -> {
if ( ! application.get().deploymentJobs().deployedInternally())
throw new IllegalArgumentException(id + " is not built here!");
locked(id, type, __ -> {
Optional<Run> last = last(id, type);
if (last.flatMap(run -> active(run.id())).isPresent())
throw new IllegalStateException("Can not start " + type + " for " + id + "; it is already running!");
RunId newId = new RunId(id, type, last.map(run -> run.id().number()).orElse(0L) + 1);
curator.writeLastRun(Run.initial(newId, versions, controller.clock().instant()));
});
});
}
/** Stores the given package and starts a deployment of it, after aborting any such ongoing deployment. */
public void deploy(ApplicationId id, JobType type, Optional<Version> platform, ApplicationPackage applicationPackage) {
controller.applications().lockOrThrow(id, application -> {
if ( ! application.get().deploymentJobs().deployedInternally())
controller.applications().store(registered(application));
});
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
last(id, type).filter(run -> ! run.hasEnded()).ifPresent(run -> abortAndWait(run.id()));
locked(id, type, __ -> {
controller.applications().applicationStore().putDev(id, type.zone(controller.system()), applicationPackage.zippedContent());
start(id, type, new Versions(platform.orElse(controller.systemVersion()),
ApplicationVersion.unknown,
Optional.empty(),
Optional.empty()));
runner.get().accept(last(id, type).get());
});
}
/** Aborts a run and waits for it complete. */
private void abortAndWait(RunId id) {
abort(id);
runner.get().accept(last(id.application(), id.type()).get());
while ( ! last(id.application(), id.type()).get().hasEnded()) {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}
/** Unregisters the given application and makes all associated data eligible for garbage collection. */
public void unregister(ApplicationId id) {
controller.applications().lockIfPresent(id, application -> {
controller.applications().store(application.withBuiltInternally(false));
jobs(id).forEach(type -> last(id, type).ifPresent(last -> abort(last.id())));
});
}
/** Deletes run data and tester deployments for applications which are unknown, or no longer built internally. */
public void collectGarbage() {
Set<ApplicationId> applicationsToBuild = new HashSet<>(applications());
curator.applicationsWithJobs().stream()
.filter(id -> ! applicationsToBuild.contains(id))
.forEach(id -> {
try {
TesterId tester = TesterId.of(id);
for (JobType type : jobs(id))
locked(id, type, deactivateTester, __ -> {
try (Lock ___ = curator.lock(id, type)) {
deactivateTester(tester, type);
curator.deleteRunData(id, type);
logs.delete(id);
}
});
}
catch (TimeoutException e) {
return;
}
curator.deleteRunData(id);
});
}
public void deactivateTester(TesterId id, JobType type) {
try {
controller.serviceRegistry().configServer().deactivate(new DeploymentId(id.id(), type.zone(controller.system())));
}
catch (NotFoundException ignored) {
}
}
/** Returns a URI which points at a badge showing historic status of given length for the given job type for the given application. */
public URI historicBadge(ApplicationId id, JobType type, int historyLength) {
List<Run> runs = new ArrayList<>(runs(id, type).values());
Run lastCompleted = null;
if (runs.size() > 0)
lastCompleted = runs.get(runs.size() - 1);
if (runs.size() > 1 && ! lastCompleted.hasEnded())
lastCompleted = runs.get(runs.size() - 2);
return badges.historic(id, Optional.ofNullable(lastCompleted), runs.subList(Math.max(0, runs.size() - historyLength), runs.size()));
}
/** Returns a URI which points at a badge showing current status for all jobs for the given application. */
public URI overviewBadge(ApplicationId id) {
DeploymentSteps steps = new DeploymentSteps(controller.applications().require(id).deploymentSpec(), controller::system);
return badges.overview(id,
steps.jobs().stream()
.map(type -> last(id, type))
.flatMap(Optional::stream)
.collect(toList()));
}
/** Returns a URI of the tester endpoint retrieved from the routing generator, provided it matches an expected form. */
/** Returns a set containing the zone of the deployment tested in the given run, and all production zones for the application. */
public Set<ZoneId> testedZoneAndProductionZones(ApplicationId id, JobType type) {
return Stream.concat(Stream.of(type.zone(controller.system())),
controller.applications().require(id).productionDeployments().keySet().stream())
.collect(Collectors.toSet());
}
private long nextBuild(ApplicationId id) {
return 1 + controller.applications().require(id).deploymentJobs()
.statusOf(JobType.component)
.flatMap(JobStatus::lastCompleted)
.map(JobStatus.JobRun::id)
.orElse(0L);
}
private void prunePackages(ApplicationId id) {
controller.applications().lockIfPresent(id, application -> {
application.get().productionDeployments().values().stream()
.map(Deployment::applicationVersion)
.min(Comparator.comparingLong(applicationVersion -> applicationVersion.buildNumber().getAsLong()))
.ifPresent(oldestDeployed -> {
controller.applications().applicationStore().prune(id, oldestDeployed);
controller.applications().applicationStore().prune(TesterId.of(id), oldestDeployed);
});
});
}
/** Locks all runs and modifies the list of historic runs for the given application and job type. */
private void locked(ApplicationId id, JobType type, Consumer<SortedMap<RunId, Run>> modifications) {
try (Lock __ = curator.lock(id, type)) {
SortedMap<RunId, Run> runs = curator.readHistoricRuns(id, type);
modifications.accept(runs);
curator.writeHistoricRuns(id, type, runs.values());
}
}
/** Locks and modifies the run with the given id, provided it is still active. */
public void locked(RunId id, UnaryOperator<Run> modifications) {
try (Lock __ = curator.lock(id.application(), id.type())) {
active(id).ifPresent(run -> {
run = modifications.apply(run);
curator.writeLastRun(run);
});
}
}
/** Locks the given step and checks none of its prerequisites are running, then performs the given actions. */
public void locked(ApplicationId id, JobType type, Step step, Consumer<LockedStep> action) throws TimeoutException {
try (Lock lock = curator.lock(id, type, step)) {
for (Step prerequisite : step.prerequisites())
try (Lock __ = curator.lock(id, type, prerequisite)) { ; }
action.accept(new LockedStep(lock, step));
}
}
} | class JobController {
private static final int historyLength = 256;
private static final Duration maxHistoryAge = Duration.ofDays(60);
private final Controller controller;
private final CuratorDb curator;
private final BufferedLogStore logs;
private final TesterCloud cloud;
private final Badges badges;
private final BooleanFlag directRoutingUseHttps;
private AtomicReference<Consumer<Run>> runner = new AtomicReference<>(__ -> { });
public JobController(Controller controller, FlagSource flagSource) {
this.controller = controller;
this.curator = controller.curator();
this.logs = new BufferedLogStore(curator, controller.serviceRegistry().runDataStore());
this.cloud = controller.serviceRegistry().testerCloud();
this.badges = new Badges(controller.zoneRegistry().badgeUrl());
this.directRoutingUseHttps = Flags.DIRECT_ROUTING_USE_HTTPS_4443.bindTo(flagSource);
}
public TesterCloud cloud() { return cloud; }
public int historyLength() { return historyLength; }
public void setRunner(Consumer<Run> runner) { this.runner.set(runner); }
/** Rewrite all job data with the newest format. */
public void updateStorage() {
for (ApplicationId id : applications())
for (JobType type : jobs(id)) {
locked(id, type, runs -> {
curator.readLastRun(id, type).ifPresent(curator::writeLastRun);
});
}
}
/** Returns all entries currently logged for the given run. */
public Optional<RunLog> details(RunId id) {
return details(id, -1);
}
/** Returns the logged entries for the given run, which are after the given id threshold. */
public Optional<RunLog> details(RunId id, long after) {
try (Lock __ = curator.lock(id.application(), id.type())) {
Run run = runs(id.application(), id.type()).get(id);
if (run == null)
return Optional.empty();
return active(id).isPresent()
? Optional.of(logs.readActive(id.application(), id.type(), after))
: logs.readFinished(id, after);
}
}
/** Stores the given log entries for the given run and step. */
public void log(RunId id, Step step, List<LogEntry> entries) {
locked(id, __ -> {
logs.append(id.application(), id.type(), step, entries);
return __;
});
}
/** Stores the given log messages for the given run and step. */
public void log(RunId id, Step step, Level level, List<String> messages) {
log(id, step, messages.stream()
.map(message -> new LogEntry(0, controller.clock().instant(), LogEntry.typeOf(level), message))
.collect(toList()));
}
/** Stores the given log message for the given run and step. */
public void log(RunId id, Step step, Level level, String message) {
log(id, step, level, Collections.singletonList(message));
}
/** Fetches any new Vespa log entries, and records the timestamp of the last of these, for continuation. */
public void updateVespaLog(RunId id) {
locked(id, run -> {
if ( ! run.steps().containsKey(copyVespaLogs))
return run;
ZoneId zone = id.type().zone(controller.system());
Optional<Deployment> deployment = Optional.ofNullable(controller.applications().require(id.application())
.deployments().get(zone));
if (deployment.isEmpty() || deployment.get().at().isBefore(run.start()))
return run;
Instant from = run.lastVespaLogTimestamp().isAfter(deployment.get().at()) ? run.lastVespaLogTimestamp() : deployment.get().at();
List<LogEntry> log = LogEntry.parseVespaLog(controller.serviceRegistry().configServer()
.getLogs(new DeploymentId(id.application(), zone),
Map.of("from", Long.toString(from.toEpochMilli()))),
from);
if (log.isEmpty())
return run;
logs.append(id.application(), id.type(), Step.copyVespaLogs, log);
return run.with(log.get(log.size() - 1).at());
});
}
/** Fetches any new test log entries, and records the id of the last of these, for continuation. */
public void updateTestLog(RunId id) {
locked(id, run -> {
if ( ! run.readySteps().contains(endTests))
return run;
Optional<URI> testerEndpoint = testerEndpoint(id);
if ( ! testerEndpoint.isPresent())
return run;
List<LogEntry> entries = cloud.getLog(testerEndpoint.get(), run.lastTestLogEntry());
if (entries.isEmpty())
return run;
logs.append(id.application(), id.type(), endTests, entries);
return run.with(entries.stream().mapToLong(LogEntry::id).max().getAsLong());
});
}
/** Stores the given certificate as the tester certificate for this run, or throws if it's already set. */
public void storeTesterCertificate(RunId id, X509Certificate testerCertificate) {
locked(id, run -> run.with(testerCertificate));
}
/** Returns a list of all application which have registered. */
public List<ApplicationId> applications() {
return copyOf(controller.applications().asList().stream()
.filter(application -> application.deploymentJobs().deployedInternally())
.map(Application::id)
.iterator());
}
/** Returns all job types which have been run for the given application. */
public List<JobType> jobs(ApplicationId id) {
return copyOf(Stream.of(JobType.values())
.filter(type -> last(id, type).isPresent())
.iterator());
}
/** Returns an immutable map of all known runs for the given application and job type. */
public Map<RunId, Run> runs(ApplicationId id, JobType type) {
SortedMap<RunId, Run> runs = curator.readHistoricRuns(id, type);
last(id, type).ifPresent(run -> runs.put(run.id(), run));
return ImmutableMap.copyOf(runs);
}
/** Returns the run with the given id, if it exists. */
public Optional<Run> run(RunId id) {
return runs(id.application(), id.type()).values().stream()
.filter(run -> run.id().equals(id))
.findAny();
}
/** Returns the last run of the given type, for the given application, if one has been run. */
public Optional<Run> last(ApplicationId id, JobType type) {
return curator.readLastRun(id, type);
}
/** Returns the run with the given id, provided it is still active. */
public Optional<Run> active(RunId id) {
return last(id.application(), id.type())
.filter(run -> ! run.hasEnded())
.filter(run -> run.id().equals(id));
}
/** Returns a list of all active runs. */
public List<Run> active() {
return copyOf(applications().stream()
.flatMap(id -> Stream.of(JobType.values())
.map(type -> last(id, type))
.flatMap(Optional::stream)
.filter(run -> ! run.hasEnded()))
.iterator());
}
/** Changes the status of the given step, for the given run, provided it is still active. */
public void update(RunId id, RunStatus status, LockedStep step) {
locked(id, run -> run.with(status, step));
}
/** Changes the status of the given run to inactive, and stores it as a historic run. */
public void finish(RunId id) {
locked(id, run -> {
Run finishedRun = run.finished(controller.clock().instant());
locked(id.application(), id.type(), runs -> {
runs.put(run.id(), finishedRun);
long last = id.number();
var oldEntries = runs.entrySet().iterator();
for (var old = oldEntries.next();
old.getKey().number() <= last - historyLength
|| old.getValue().start().isBefore(controller.clock().instant().minus(maxHistoryAge));
old = oldEntries.next()) {
logs.delete(old.getKey());
oldEntries.remove();
}
});
logs.flush(id);
return finishedRun;
});
}
/** Marks the given run as aborted; no further normal steps will run, but run-always steps will try to succeed. */
public void abort(RunId id) {
locked(id, run -> run.aborted());
}
/**
* Accepts and stores a new application package and test jar pair under a generated application version key.
*/
public ApplicationVersion submit(ApplicationId id, SourceRevision revision, String authorEmail, long projectId,
ApplicationPackage applicationPackage, byte[] testPackageBytes) {
AtomicReference<ApplicationVersion> version = new AtomicReference<>();
controller.applications().lockOrThrow(id, application -> {
if ( ! application.get().deploymentJobs().deployedInternally())
application = registered(application);
long run = nextBuild(id);
if (applicationPackage.compileVersion().isPresent() && applicationPackage.buildTime().isPresent())
version.set(ApplicationVersion.from(revision, run, authorEmail,
applicationPackage.compileVersion().get(),
applicationPackage.buildTime().get()));
else
version.set(ApplicationVersion.from(revision, run, authorEmail));
controller.applications().applicationStore().put(id,
version.get(),
applicationPackage.zippedContent());
controller.applications().applicationStore().put(TesterId.of(id),
version.get(),
testPackageBytes);
prunePackages(id);
controller.applications().storeWithUpdatedConfig(application, applicationPackage);
controller.applications().deploymentTrigger().notifyOfCompletion(DeploymentJobs.JobReport.ofSubmission(id, projectId, version.get()));
});
return version.get();
}
/** Registers the given application, copying necessary application packages, and returns the modified version. */
private LockedApplication registered(LockedApplication application) {
application.get().productionDeployments().values().stream()
.map(Deployment::applicationVersion)
.distinct()
.forEach(appVersion -> {
byte[] content = controller.applications().artifacts().getApplicationPackage(application.get().id(), appVersion.id());
controller.applications().applicationStore().put(application.get().id(), appVersion, content);
});
return application.withChange(application.get().change().withoutPlatform().withoutApplication())
.withBuiltInternally(true);
}
/** Orders a run of the given type, or throws an IllegalStateException if that job type is already running. */
public void start(ApplicationId id, JobType type, Versions versions) {
if ( ! type.environment().isManuallyDeployed() && versions.targetApplication().isUnknown())
throw new IllegalArgumentException("Target application must be a valid reference.");
controller.applications().lockIfPresent(id, application -> {
if ( ! application.get().deploymentJobs().deployedInternally())
throw new IllegalArgumentException(id + " is not built here!");
locked(id, type, __ -> {
Optional<Run> last = last(id, type);
if (last.flatMap(run -> active(run.id())).isPresent())
throw new IllegalStateException("Can not start " + type + " for " + id + "; it is already running!");
RunId newId = new RunId(id, type, last.map(run -> run.id().number()).orElse(0L) + 1);
curator.writeLastRun(Run.initial(newId, versions, controller.clock().instant()));
});
});
}
/** Stores the given package and starts a deployment of it, after aborting any such ongoing deployment. */
public void deploy(ApplicationId id, JobType type, Optional<Version> platform, ApplicationPackage applicationPackage) {
controller.applications().lockOrThrow(id, application -> {
if ( ! application.get().deploymentJobs().deployedInternally())
controller.applications().store(registered(application));
});
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
last(id, type).filter(run -> ! run.hasEnded()).ifPresent(run -> abortAndWait(run.id()));
locked(id, type, __ -> {
controller.applications().applicationStore().putDev(id, type.zone(controller.system()), applicationPackage.zippedContent());
start(id, type, new Versions(platform.orElse(controller.systemVersion()),
ApplicationVersion.unknown,
Optional.empty(),
Optional.empty()));
runner.get().accept(last(id, type).get());
});
}
/** Aborts a run and waits for it complete. */
private void abortAndWait(RunId id) {
abort(id);
runner.get().accept(last(id.application(), id.type()).get());
while ( ! last(id.application(), id.type()).get().hasEnded()) {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}
/** Unregisters the given application and makes all associated data eligible for garbage collection. */
public void unregister(ApplicationId id) {
controller.applications().lockIfPresent(id, application -> {
controller.applications().store(application.withBuiltInternally(false));
jobs(id).forEach(type -> last(id, type).ifPresent(last -> abort(last.id())));
});
}
/** Deletes run data and tester deployments for applications which are unknown, or no longer built internally. */
public void collectGarbage() {
Set<ApplicationId> applicationsToBuild = new HashSet<>(applications());
curator.applicationsWithJobs().stream()
.filter(id -> ! applicationsToBuild.contains(id))
.forEach(id -> {
try {
TesterId tester = TesterId.of(id);
for (JobType type : jobs(id))
locked(id, type, deactivateTester, __ -> {
try (Lock ___ = curator.lock(id, type)) {
deactivateTester(tester, type);
curator.deleteRunData(id, type);
logs.delete(id);
}
});
}
catch (TimeoutException e) {
return;
}
curator.deleteRunData(id);
});
}
public void deactivateTester(TesterId id, JobType type) {
try {
controller.serviceRegistry().configServer().deactivate(new DeploymentId(id.id(), type.zone(controller.system())));
}
catch (NotFoundException ignored) {
}
}
/** Returns a URI which points at a badge showing historic status of given length for the given job type for the given application. */
public URI historicBadge(ApplicationId id, JobType type, int historyLength) {
List<Run> runs = new ArrayList<>(runs(id, type).values());
Run lastCompleted = null;
if (runs.size() > 0)
lastCompleted = runs.get(runs.size() - 1);
if (runs.size() > 1 && ! lastCompleted.hasEnded())
lastCompleted = runs.get(runs.size() - 2);
return badges.historic(id, Optional.ofNullable(lastCompleted), runs.subList(Math.max(0, runs.size() - historyLength), runs.size()));
}
/** Returns a URI which points at a badge showing current status for all jobs for the given application. */
public URI overviewBadge(ApplicationId id) {
DeploymentSteps steps = new DeploymentSteps(controller.applications().require(id).deploymentSpec(), controller::system);
return badges.overview(id,
steps.jobs().stream()
.map(type -> last(id, type))
.flatMap(Optional::stream)
.collect(toList()));
}
/** Returns a URI of the tester endpoint retrieved from the routing generator, provided it matches an expected form. */
/** Returns a set containing the zone of the deployment tested in the given run, and all production zones for the application. */
public Set<ZoneId> testedZoneAndProductionZones(ApplicationId id, JobType type) {
return Stream.concat(Stream.of(type.zone(controller.system())),
controller.applications().require(id).productionDeployments().keySet().stream())
.collect(Collectors.toSet());
}
private long nextBuild(ApplicationId id) {
return 1 + controller.applications().require(id).deploymentJobs()
.statusOf(JobType.component)
.flatMap(JobStatus::lastCompleted)
.map(JobStatus.JobRun::id)
.orElse(0L);
}
private void prunePackages(ApplicationId id) {
controller.applications().lockIfPresent(id, application -> {
application.get().productionDeployments().values().stream()
.map(Deployment::applicationVersion)
.min(Comparator.comparingLong(applicationVersion -> applicationVersion.buildNumber().getAsLong()))
.ifPresent(oldestDeployed -> {
controller.applications().applicationStore().prune(id, oldestDeployed);
controller.applications().applicationStore().prune(TesterId.of(id), oldestDeployed);
});
});
}
/** Locks all runs and modifies the list of historic runs for the given application and job type. */
private void locked(ApplicationId id, JobType type, Consumer<SortedMap<RunId, Run>> modifications) {
try (Lock __ = curator.lock(id, type)) {
SortedMap<RunId, Run> runs = curator.readHistoricRuns(id, type);
modifications.accept(runs);
curator.writeHistoricRuns(id, type, runs.values());
}
}
/** Locks and modifies the run with the given id, provided it is still active. */
public void locked(RunId id, UnaryOperator<Run> modifications) {
try (Lock __ = curator.lock(id.application(), id.type())) {
active(id).ifPresent(run -> {
run = modifications.apply(run);
curator.writeLastRun(run);
});
}
}
/** Locks the given step and checks none of its prerequisites are running, then performs the given actions. */
public void locked(ApplicationId id, JobType type, Step step, Consumer<LockedStep> action) throws TimeoutException {
try (Lock lock = curator.lock(id, type, step)) {
for (Step prerequisite : step.prerequisites())
try (Lock __ = curator.lock(id, type, prerequisite)) { ; }
action.accept(new LockedStep(lock, step));
}
}
} |
longer token sorts before shorter ? Reverse of normal alphabetical sorting ? | public int compareTo(SpecialToken other) {
if (this.token().length() < other.token().length()) return 1;
if (this.token().length() == other.token().length()) return 0;
return -1;
} | if (this.token().length() < other.token().length()) return 1; | public int compareTo(SpecialToken other) {
if (this.token().length() < other.token().length()) return 1;
if (this.token().length() == other.token().length()) return 0;
return -1;
} | class SpecialToken implements Comparable<SpecialToken> {
private String token;
private String replace;
public SpecialToken(String token, String replace) {
this.token = toLowerCase(token);
if (replace == null || replace.trim().equals("")) {
this.replace = this.token;
} else {
this.replace = toLowerCase(replace);
}
}
/** Returns the special token */
public String token() {
return token;
}
/** Returns the right replace value, never null or an empty string */
public String replace() {
return replace;
}
@Override
@Override
public boolean equals(Object other) {
if (other == this) return true;
if ( ! (other instanceof SpecialToken)) return false;
return Objects.equals(this.token, ((SpecialToken)other).token);
}
@Override
public int hashCode() { return token.hashCode(); }
public Token toToken(int start,String rawSource) {
return new Token(Token.Kind.WORD, replace(), true, new Substring(start, start + token.length(), rawSource));
}
} | class SpecialToken implements Comparable<SpecialToken> {
private String token;
private String replace;
public SpecialToken(String token, String replace) {
this.token = toLowerCase(token);
if (replace == null || replace.trim().equals("")) {
this.replace = this.token;
} else {
this.replace = toLowerCase(replace);
}
}
/** Returns the special token */
public String token() {
return token;
}
/** Returns the right replace value, never null or an empty string */
public String replace() {
return replace;
}
@Override
@Override
public boolean equals(Object other) {
if (other == this) return true;
if ( ! (other instanceof SpecialToken)) return false;
return Objects.equals(this.token, ((SpecialToken)other).token);
}
@Override
public int hashCode() { return token.hashCode(); }
public Token toToken(int start,String rawSource) {
return new Token(Token.Kind.WORD, replace(), true, new Substring(start, start + token.length(), rawSource));
}
} |
Yes, this is odd but I didn't want to change anything here (except in Relevance). | public int compareTo(SpecialToken other) {
if (this.token().length() < other.token().length()) return 1;
if (this.token().length() == other.token().length()) return 0;
return -1;
} | if (this.token().length() < other.token().length()) return 1; | public int compareTo(SpecialToken other) {
if (this.token().length() < other.token().length()) return 1;
if (this.token().length() == other.token().length()) return 0;
return -1;
} | class SpecialToken implements Comparable<SpecialToken> {
private String token;
private String replace;
public SpecialToken(String token, String replace) {
this.token = toLowerCase(token);
if (replace == null || replace.trim().equals("")) {
this.replace = this.token;
} else {
this.replace = toLowerCase(replace);
}
}
/** Returns the special token */
public String token() {
return token;
}
/** Returns the right replace value, never null or an empty string */
public String replace() {
return replace;
}
@Override
@Override
public boolean equals(Object other) {
if (other == this) return true;
if ( ! (other instanceof SpecialToken)) return false;
return Objects.equals(this.token, ((SpecialToken)other).token);
}
@Override
public int hashCode() { return token.hashCode(); }
public Token toToken(int start,String rawSource) {
return new Token(Token.Kind.WORD, replace(), true, new Substring(start, start + token.length(), rawSource));
}
} | class SpecialToken implements Comparable<SpecialToken> {
private String token;
private String replace;
public SpecialToken(String token, String replace) {
this.token = toLowerCase(token);
if (replace == null || replace.trim().equals("")) {
this.replace = this.token;
} else {
this.replace = toLowerCase(replace);
}
}
/** Returns the special token */
public String token() {
return token;
}
/** Returns the right replace value, never null or an empty string */
public String replace() {
return replace;
}
@Override
@Override
public boolean equals(Object other) {
if (other == this) return true;
if ( ! (other instanceof SpecialToken)) return false;
return Objects.equals(this.token, ((SpecialToken)other).token);
}
@Override
public int hashCode() { return token.hashCode(); }
public Token toToken(int start,String rawSource) {
return new Token(Token.Kind.WORD, replace(), true, new Substring(start, start + token.length(), rawSource));
}
} |
Btw, I think the longer tokens first thing is to prefer matching longer tokens. | public int compareTo(SpecialToken other) {
if (this.token().length() < other.token().length()) return 1;
if (this.token().length() == other.token().length()) return 0;
return -1;
} | if (this.token().length() < other.token().length()) return 1; | public int compareTo(SpecialToken other) {
if (this.token().length() < other.token().length()) return 1;
if (this.token().length() == other.token().length()) return 0;
return -1;
} | class SpecialToken implements Comparable<SpecialToken> {
private String token;
private String replace;
public SpecialToken(String token, String replace) {
this.token = toLowerCase(token);
if (replace == null || replace.trim().equals("")) {
this.replace = this.token;
} else {
this.replace = toLowerCase(replace);
}
}
/** Returns the special token */
public String token() {
return token;
}
/** Returns the right replace value, never null or an empty string */
public String replace() {
return replace;
}
@Override
@Override
public boolean equals(Object other) {
if (other == this) return true;
if ( ! (other instanceof SpecialToken)) return false;
return Objects.equals(this.token, ((SpecialToken)other).token);
}
@Override
public int hashCode() { return token.hashCode(); }
public Token toToken(int start,String rawSource) {
return new Token(Token.Kind.WORD, replace(), true, new Substring(start, start + token.length(), rawSource));
}
} | class SpecialToken implements Comparable<SpecialToken> {
private String token;
private String replace;
public SpecialToken(String token, String replace) {
this.token = toLowerCase(token);
if (replace == null || replace.trim().equals("")) {
this.replace = this.token;
} else {
this.replace = toLowerCase(replace);
}
}
/** Returns the special token */
public String token() {
return token;
}
/** Returns the right replace value, never null or an empty string */
public String replace() {
return replace;
}
@Override
@Override
public boolean equals(Object other) {
if (other == this) return true;
if ( ! (other instanceof SpecialToken)) return false;
return Objects.equals(this.token, ((SpecialToken)other).token);
}
@Override
public int hashCode() { return token.hashCode(); }
public Token toToken(int start,String rawSource) {
return new Token(Token.Kind.WORD, replace(), true, new Substring(start, start + token.length(), rawSource));
}
} |
Any are not better than one if this uses direct dispatch as that means the container is paired to a single local copy of the corpus, and presumably there are other copies which are fully available, to be called from other nodes. And this code path is only about that special case. | private void updateSufficientCoverage(Group group, boolean sufficientCoverage) {
boolean isInRotation = vipStatus.isInRotation();
boolean hasChanged = sufficientCoverage != group.hasSufficientCoverage();
boolean isDirectDispatchGroupAndChange = usesDirectDispatchTo(group) && hasChanged;
group.setHasSufficientCoverage(sufficientCoverage);
if ((!isInRotation || isDirectDispatchGroupAndChange) && sufficientCoverage) {
vipStatus.addToRotation(clusterId);
} else if (isDirectDispatchGroupAndChange) {
vipStatus.removeFromRotation(clusterId);
}
} | } else if (isDirectDispatchGroupAndChange) { | private void updateSufficientCoverage(Group group, boolean sufficientCoverage) {
boolean isInRotation = vipStatus.isInRotation();
boolean hasChanged = sufficientCoverage != group.hasSufficientCoverage();
boolean isDirectDispatchGroupAndChange = usesDirectDispatchTo(group) && hasChanged;
group.setHasSufficientCoverage(sufficientCoverage);
if ((!isInRotation || isDirectDispatchGroupAndChange) && sufficientCoverage) {
vipStatus.addToRotation(clusterId);
} else if (isDirectDispatchGroupAndChange) {
vipStatus.removeFromRotation(clusterId);
}
} | class SearchCluster implements NodeManager<Node> {
private static final Logger log = Logger.getLogger(SearchCluster.class.getName());
private final DispatchConfig dispatchConfig;
private final int size;
private final String clusterId;
private final ImmutableMap<Integer, Group> groups;
private final ImmutableMultimap<String, Node> nodesByHost;
private final ImmutableList<Group> orderedGroups;
private final ClusterMonitor<Node> clusterMonitor;
private final VipStatus vipStatus;
private PingFactory pingFactory;
/**
* A search node on this local machine having the entire corpus, which we therefore
* should prefer to dispatch directly to, or empty if there is no such local search node.
* If there is one, we also maintain the VIP status of this container based on the availability
* of the corpus on this local node (up + has coverage), such that this node is taken out of rotation
* if it only queries this cluster when the local node cannot be used, to avoid unnecessary
* cross-node network traffic.
*/
private final Optional<Node> directDispatchTarget;
public SearchCluster(String clusterId, DispatchConfig dispatchConfig, int containerClusterSize, VipStatus vipStatus) {
this.clusterId = clusterId;
this.dispatchConfig = dispatchConfig;
this.vipStatus = vipStatus;
List<Node> nodes = toNodes(dispatchConfig);
this.size = nodes.size();
ImmutableMap.Builder<Integer, Group> groupsBuilder = new ImmutableMap.Builder<>();
for (Map.Entry<Integer, List<Node>> group : nodes.stream().collect(Collectors.groupingBy(Node::group)).entrySet()) {
Group g = new Group(group.getKey(), group.getValue());
groupsBuilder.put(group.getKey(), g);
}
this.groups = groupsBuilder.build();
LinkedHashMap<Integer, Group> groupIntroductionOrder = new LinkedHashMap<>();
nodes.forEach(node -> groupIntroductionOrder.put(node.group(), groups.get(node.group)));
this.orderedGroups = ImmutableList.<Group>builder().addAll(groupIntroductionOrder.values()).build();
ImmutableMultimap.Builder<String, Node> nodesByHostBuilder = new ImmutableMultimap.Builder<>();
for (Node node : nodes)
nodesByHostBuilder.put(node.hostname(), node);
this.nodesByHost = nodesByHostBuilder.build();
this.directDispatchTarget = findDirectDispatchTarget(HostName.getLocalhost(), size, containerClusterSize,
nodesByHost, groups);
this.clusterMonitor = new ClusterMonitor<>(this);
}
public void startClusterMonitoring(PingFactory pingFactory) {
this.pingFactory = pingFactory;
for (var group : orderedGroups) {
for (var node : group.nodes()) {
working(node);
clusterMonitor.add(node, true);
}
}
}
private static Optional<Node> findDirectDispatchTarget(String selfHostname,
int searchClusterSize,
int containerClusterSize,
ImmutableMultimap<String, Node> nodesByHost,
ImmutableMap<Integer, Group> groups) {
ImmutableCollection<Node> localSearchNodes = nodesByHost.get(selfHostname);
if (localSearchNodes.size() != 1) return Optional.empty();
Node localSearchNode = localSearchNodes.iterator().next();
Group localSearchGroup = groups.get(localSearchNode.group());
if (localSearchGroup.nodes().size() != 1) return Optional.empty();
if (containerClusterSize < searchClusterSize) return Optional.empty();
return Optional.of(localSearchNode);
}
private static ImmutableList<Node> toNodes(DispatchConfig dispatchConfig) {
ImmutableList.Builder<Node> nodesBuilder = new ImmutableList.Builder<>();
Predicate<DispatchConfig.Node> filter;
if (dispatchConfig.useLocalNode()) {
final String hostName = HostName.getLocalhost();
filter = node -> node.host().equals(hostName);
} else {
filter = node -> true;
}
for (DispatchConfig.Node node : dispatchConfig.node()) {
if (filter.test(node)) {
nodesBuilder.add(new Node(node.key(), node.host(), node.fs4port(), node.group()));
}
}
return nodesBuilder.build();
}
public DispatchConfig dispatchConfig() {
return dispatchConfig;
}
/** Returns the number of nodes in this cluster (across all groups) */
public int size() { return size; }
/** Returns the groups of this cluster as an immutable map indexed by group id */
public ImmutableMap<Integer, Group> groups() { return groups; }
/** Returns the groups of this cluster as an immutable list in introduction order */
public ImmutableList<Group> orderedGroups() { return orderedGroups; }
/** Returns the n'th (zero-indexed) group in the cluster if possible */
public Optional<Group> group(int n) {
if (orderedGroups.size() > n) {
return Optional.of(orderedGroups.get(n));
} else {
return Optional.empty();
}
}
/** Returns the number of nodes per group - size()/groups.size() */
public int groupSize() {
if (groups.size() == 0) return size();
return size() / groups.size();
}
public int groupsWithSufficientCoverage() {
int covered = 0;
for (Group g : orderedGroups) {
if (g.hasSufficientCoverage()) {
covered++;
}
}
return covered;
}
/**
* Returns the recipient we should dispatch queries directly to (bypassing fdispatch),
* or empty if we should not dispatch directly.
*/
public Optional<Node> directDispatchTarget() {
if ( directDispatchTarget.isEmpty()) return Optional.empty();
Group localSearchGroup = groups.get(directDispatchTarget.get().group());
if ( ! localSearchGroup.hasSufficientCoverage()) return Optional.empty();
if ( ! directDispatchTarget.get().isWorking()) return Optional.empty();
return directDispatchTarget;
}
/** Used by the cluster monitor to manage node status */
@Override
public void working(Node node) {
node.setWorking(true);
if (usesDirectDispatchTo(node))
vipStatus.addToRotation(clusterId);
}
/** Used by the cluster monitor to manage node status */
@Override
public void failed(Node node) {
node.setWorking(false);
if (usesDirectDispatchTo(node))
vipStatus.removeFromRotation(clusterId);
}
private boolean usesDirectDispatchTo(Node node) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().equals(node);
}
private boolean usesDirectDispatchTo(Group group) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().group() == group.id();
}
/** Used by the cluster monitor to manage node status */
@Override
public void ping(Node node, Executor executor) {
if (pingFactory == null)
return;
FutureTask<Pong> futurePong = new FutureTask<>(pingFactory.createPinger(node, clusterMonitor));
executor.execute(futurePong);
Pong pong = getPong(futurePong, node);
futurePong.cancel(true);
if (pong.badResponse()) {
clusterMonitor.failed(node, pong.getError(0));
} else {
if (pong.activeDocuments().isPresent()) {
node.setActiveDocuments(pong.activeDocuments().get());
}
clusterMonitor.responded(node);
}
}
/**
* Update statistics after a round of issuing pings.
* Note that this doesn't wait for pings to return, so it will typically accumulate data from
* last rounds pinging, or potentially (although unlikely) some combination of new and old data.
*/
@Override
public void pingIterationCompleted() {
int numGroups = orderedGroups.size();
if (numGroups == 1) {
Group group = groups.values().iterator().next();
group.aggregateActiveDocuments();
updateSufficientCoverage(group, true);
boolean fullCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), group.getActiveDocuments(),
group.getActiveDocuments());
trackGroupCoverageChanges(0, group, fullCoverage, group.getActiveDocuments());
return;
}
long[] activeDocumentsInGroup = new long[numGroups];
long sumOfActiveDocuments = 0;
for(int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
group.aggregateActiveDocuments();
activeDocumentsInGroup[i] = group.getActiveDocuments();
sumOfActiveDocuments += activeDocumentsInGroup[i];
}
boolean anyGroupsSufficientCoverage = false;
for (int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
long activeDocuments = activeDocumentsInGroup[i];
long averageDocumentsInOtherGroups = (sumOfActiveDocuments - activeDocuments) / (numGroups - 1);
boolean sufficientCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), activeDocuments, averageDocumentsInOtherGroups);
anyGroupsSufficientCoverage = anyGroupsSufficientCoverage || sufficientCoverage;
updateSufficientCoverage(group, sufficientCoverage);
trackGroupCoverageChanges(i, group, sufficientCoverage, averageDocumentsInOtherGroups);
}
if ( ! anyGroupsSufficientCoverage && (sumOfActiveDocuments == 0)) {
vipStatus.removeFromRotation(clusterId);
}
}
private boolean isGroupCoverageSufficient(int workingNodes, int nodesInGroup, long activeDocuments, long averageDocumentsInOtherGroups) {
boolean sufficientCoverage = true;
if (averageDocumentsInOtherGroups > 0) {
double coverage = 100.0 * (double) activeDocuments / averageDocumentsInOtherGroups;
sufficientCoverage = coverage >= dispatchConfig.minActivedocsPercentage();
}
if (sufficientCoverage) {
sufficientCoverage = isGroupNodeCoverageSufficient(workingNodes, nodesInGroup);
}
return sufficientCoverage;
}
private boolean isGroupNodeCoverageSufficient(int workingNodes, int nodesInGroup) {
int nodesAllowedDown = dispatchConfig.maxNodesDownPerGroup()
+ (int) (((double) nodesInGroup * (100.0 - dispatchConfig.minGroupCoverage())) / 100.0);
return workingNodes + nodesAllowedDown >= nodesInGroup;
}
private Pong getPong(FutureTask<Pong> futurePong, Node node) {
try {
return futurePong.get(clusterMonitor.getConfiguration().getFailLimit(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Ping was interrupted: " + node));
} catch (ExecutionException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Execution was interrupted: " + node));
} catch (TimeoutException e) {
return new Pong(ErrorMessage.createNoAnswerWhenPingingNode("Ping thread timed out"));
}
}
/**
* Calculate whether a subset of nodes in a group has enough coverage
*/
public boolean isPartialGroupCoverageSufficient(OptionalInt knownGroupId, List<Node> nodes) {
if (orderedGroups.size() == 1) {
boolean sufficient = nodes.size() >= groupSize() - dispatchConfig.maxNodesDownPerGroup();
return sufficient;
}
if (knownGroupId.isEmpty()) {
return false;
}
int groupId = knownGroupId.getAsInt();
Group group = groups.get(groupId);
if (group == null) {
return false;
}
int nodesInGroup = group.nodes().size();
long sumOfActiveDocuments = 0;
int otherGroups = 0;
for (Group g : orderedGroups) {
if (g.id() != groupId) {
sumOfActiveDocuments += g.getActiveDocuments();
otherGroups++;
}
}
long activeDocuments = 0;
for (Node n : nodes) {
activeDocuments += n.getActiveDocuments();
}
long averageDocumentsInOtherGroups = sumOfActiveDocuments / otherGroups;
boolean sufficient = isGroupCoverageSufficient(nodes.size(), nodesInGroup, activeDocuments, averageDocumentsInOtherGroups);
return sufficient;
}
private void trackGroupCoverageChanges(int index, Group group, boolean fullCoverage, long averageDocuments) {
boolean changed = group.isFullCoverageStatusChanged(fullCoverage);
if (changed) {
int requiredNodes = groupSize() - dispatchConfig.maxNodesDownPerGroup();
if (fullCoverage) {
log.info(() -> String.format("Group %d is now good again (%d/%d active docs, coverage %d/%d)", index,
group.getActiveDocuments(), averageDocuments, group.workingNodes(), groupSize()));
} else {
log.warning(() -> String.format("Coverage of group %d is only %d/%d (requires %d)", index, group.workingNodes(), groupSize(),
requiredNodes));
}
}
}
} | class SearchCluster implements NodeManager<Node> {
private static final Logger log = Logger.getLogger(SearchCluster.class.getName());
private final DispatchConfig dispatchConfig;
private final int size;
private final String clusterId;
private final ImmutableMap<Integer, Group> groups;
private final ImmutableMultimap<String, Node> nodesByHost;
private final ImmutableList<Group> orderedGroups;
private final ClusterMonitor<Node> clusterMonitor;
private final VipStatus vipStatus;
private PingFactory pingFactory;
/**
* A search node on this local machine having the entire corpus, which we therefore
* should prefer to dispatch directly to, or empty if there is no such local search node.
* If there is one, we also maintain the VIP status of this container based on the availability
* of the corpus on this local node (up + has coverage), such that this node is taken out of rotation
* if it only queries this cluster when the local node cannot be used, to avoid unnecessary
* cross-node network traffic.
*/
private final Optional<Node> directDispatchTarget;
public SearchCluster(String clusterId, DispatchConfig dispatchConfig, int containerClusterSize, VipStatus vipStatus) {
this.clusterId = clusterId;
this.dispatchConfig = dispatchConfig;
this.vipStatus = vipStatus;
List<Node> nodes = toNodes(dispatchConfig);
this.size = nodes.size();
ImmutableMap.Builder<Integer, Group> groupsBuilder = new ImmutableMap.Builder<>();
for (Map.Entry<Integer, List<Node>> group : nodes.stream().collect(Collectors.groupingBy(Node::group)).entrySet()) {
Group g = new Group(group.getKey(), group.getValue());
groupsBuilder.put(group.getKey(), g);
}
this.groups = groupsBuilder.build();
LinkedHashMap<Integer, Group> groupIntroductionOrder = new LinkedHashMap<>();
nodes.forEach(node -> groupIntroductionOrder.put(node.group(), groups.get(node.group)));
this.orderedGroups = ImmutableList.<Group>builder().addAll(groupIntroductionOrder.values()).build();
ImmutableMultimap.Builder<String, Node> nodesByHostBuilder = new ImmutableMultimap.Builder<>();
for (Node node : nodes)
nodesByHostBuilder.put(node.hostname(), node);
this.nodesByHost = nodesByHostBuilder.build();
this.directDispatchTarget = findDirectDispatchTarget(HostName.getLocalhost(), size, containerClusterSize,
nodesByHost, groups);
this.clusterMonitor = new ClusterMonitor<>(this);
}
public void startClusterMonitoring(PingFactory pingFactory) {
this.pingFactory = pingFactory;
for (var group : orderedGroups) {
for (var node : group.nodes()) {
working(node);
clusterMonitor.add(node, true);
}
}
}
private static Optional<Node> findDirectDispatchTarget(String selfHostname,
int searchClusterSize,
int containerClusterSize,
ImmutableMultimap<String, Node> nodesByHost,
ImmutableMap<Integer, Group> groups) {
ImmutableCollection<Node> localSearchNodes = nodesByHost.get(selfHostname);
if (localSearchNodes.size() != 1) return Optional.empty();
Node localSearchNode = localSearchNodes.iterator().next();
Group localSearchGroup = groups.get(localSearchNode.group());
if (localSearchGroup.nodes().size() != 1) return Optional.empty();
if (containerClusterSize < searchClusterSize) return Optional.empty();
return Optional.of(localSearchNode);
}
private static ImmutableList<Node> toNodes(DispatchConfig dispatchConfig) {
ImmutableList.Builder<Node> nodesBuilder = new ImmutableList.Builder<>();
Predicate<DispatchConfig.Node> filter;
if (dispatchConfig.useLocalNode()) {
final String hostName = HostName.getLocalhost();
filter = node -> node.host().equals(hostName);
} else {
filter = node -> true;
}
for (DispatchConfig.Node node : dispatchConfig.node()) {
if (filter.test(node)) {
nodesBuilder.add(new Node(node.key(), node.host(), node.fs4port(), node.group()));
}
}
return nodesBuilder.build();
}
public DispatchConfig dispatchConfig() {
return dispatchConfig;
}
/** Returns the number of nodes in this cluster (across all groups) */
public int size() { return size; }
/** Returns the groups of this cluster as an immutable map indexed by group id */
public ImmutableMap<Integer, Group> groups() { return groups; }
/** Returns the groups of this cluster as an immutable list in introduction order */
public ImmutableList<Group> orderedGroups() { return orderedGroups; }
/** Returns the n'th (zero-indexed) group in the cluster if possible */
public Optional<Group> group(int n) {
if (orderedGroups.size() > n) {
return Optional.of(orderedGroups.get(n));
} else {
return Optional.empty();
}
}
/** Returns the number of nodes per group - size()/groups.size() */
public int groupSize() {
if (groups.size() == 0) return size();
return size() / groups.size();
}
public int groupsWithSufficientCoverage() {
int covered = 0;
for (Group g : orderedGroups) {
if (g.hasSufficientCoverage()) {
covered++;
}
}
return covered;
}
/**
* Returns the recipient we should dispatch queries directly to (bypassing fdispatch),
* or empty if we should not dispatch directly.
*/
public Optional<Node> directDispatchTarget() {
if ( directDispatchTarget.isEmpty()) return Optional.empty();
Group localSearchGroup = groups.get(directDispatchTarget.get().group());
if ( ! localSearchGroup.hasSufficientCoverage()) return Optional.empty();
if ( ! directDispatchTarget.get().isWorking()) return Optional.empty();
return directDispatchTarget;
}
/** Used by the cluster monitor to manage node status */
@Override
public void working(Node node) {
node.setWorking(true);
if (usesDirectDispatchTo(node))
vipStatus.addToRotation(clusterId);
}
/** Used by the cluster monitor to manage node status */
@Override
public void failed(Node node) {
node.setWorking(false);
if (usesDirectDispatchTo(node))
vipStatus.removeFromRotation(clusterId);
}
private boolean usesDirectDispatchTo(Node node) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().equals(node);
}
private boolean usesDirectDispatchTo(Group group) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().group() == group.id();
}
/** Used by the cluster monitor to manage node status */
@Override
public void ping(Node node, Executor executor) {
if (pingFactory == null)
return;
FutureTask<Pong> futurePong = new FutureTask<>(pingFactory.createPinger(node, clusterMonitor));
executor.execute(futurePong);
Pong pong = getPong(futurePong, node);
futurePong.cancel(true);
if (pong.badResponse()) {
clusterMonitor.failed(node, pong.getError(0));
} else {
if (pong.activeDocuments().isPresent()) {
node.setActiveDocuments(pong.activeDocuments().get());
}
clusterMonitor.responded(node);
}
}
/**
* Update statistics after a round of issuing pings.
* Note that this doesn't wait for pings to return, so it will typically accumulate data from
* last rounds pinging, or potentially (although unlikely) some combination of new and old data.
*/
@Override
public void pingIterationCompleted() {
int numGroups = orderedGroups.size();
if (numGroups == 1) {
Group group = groups.values().iterator().next();
group.aggregateActiveDocuments();
updateSufficientCoverage(group, true);
boolean fullCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), group.getActiveDocuments(),
group.getActiveDocuments());
trackGroupCoverageChanges(0, group, fullCoverage, group.getActiveDocuments());
return;
}
long[] activeDocumentsInGroup = new long[numGroups];
long sumOfActiveDocuments = 0;
for(int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
group.aggregateActiveDocuments();
activeDocumentsInGroup[i] = group.getActiveDocuments();
sumOfActiveDocuments += activeDocumentsInGroup[i];
}
boolean anyGroupsSufficientCoverage = false;
for (int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
long activeDocuments = activeDocumentsInGroup[i];
long averageDocumentsInOtherGroups = (sumOfActiveDocuments - activeDocuments) / (numGroups - 1);
boolean sufficientCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), activeDocuments, averageDocumentsInOtherGroups);
anyGroupsSufficientCoverage = anyGroupsSufficientCoverage || sufficientCoverage;
updateSufficientCoverage(group, sufficientCoverage);
trackGroupCoverageChanges(i, group, sufficientCoverage, averageDocumentsInOtherGroups);
}
if ( ! anyGroupsSufficientCoverage && (sumOfActiveDocuments == 0)) {
vipStatus.removeFromRotation(clusterId);
}
}
private boolean isGroupCoverageSufficient(int workingNodes, int nodesInGroup, long activeDocuments, long averageDocumentsInOtherGroups) {
boolean sufficientCoverage = true;
if (averageDocumentsInOtherGroups > 0) {
double coverage = 100.0 * (double) activeDocuments / averageDocumentsInOtherGroups;
sufficientCoverage = coverage >= dispatchConfig.minActivedocsPercentage();
}
if (sufficientCoverage) {
sufficientCoverage = isGroupNodeCoverageSufficient(workingNodes, nodesInGroup);
}
return sufficientCoverage;
}
private boolean isGroupNodeCoverageSufficient(int workingNodes, int nodesInGroup) {
int nodesAllowedDown = dispatchConfig.maxNodesDownPerGroup()
+ (int) (((double) nodesInGroup * (100.0 - dispatchConfig.minGroupCoverage())) / 100.0);
return workingNodes + nodesAllowedDown >= nodesInGroup;
}
private Pong getPong(FutureTask<Pong> futurePong, Node node) {
try {
return futurePong.get(clusterMonitor.getConfiguration().getFailLimit(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Ping was interrupted: " + node));
} catch (ExecutionException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Execution was interrupted: " + node));
} catch (TimeoutException e) {
return new Pong(ErrorMessage.createNoAnswerWhenPingingNode("Ping thread timed out"));
}
}
/**
* Calculate whether a subset of nodes in a group has enough coverage
*/
public boolean isPartialGroupCoverageSufficient(OptionalInt knownGroupId, List<Node> nodes) {
if (orderedGroups.size() == 1) {
boolean sufficient = nodes.size() >= groupSize() - dispatchConfig.maxNodesDownPerGroup();
return sufficient;
}
if (knownGroupId.isEmpty()) {
return false;
}
int groupId = knownGroupId.getAsInt();
Group group = groups.get(groupId);
if (group == null) {
return false;
}
int nodesInGroup = group.nodes().size();
long sumOfActiveDocuments = 0;
int otherGroups = 0;
for (Group g : orderedGroups) {
if (g.id() != groupId) {
sumOfActiveDocuments += g.getActiveDocuments();
otherGroups++;
}
}
long activeDocuments = 0;
for (Node n : nodes) {
activeDocuments += n.getActiveDocuments();
}
long averageDocumentsInOtherGroups = sumOfActiveDocuments / otherGroups;
boolean sufficient = isGroupCoverageSufficient(nodes.size(), nodesInGroup, activeDocuments, averageDocumentsInOtherGroups);
return sufficient;
}
private void trackGroupCoverageChanges(int index, Group group, boolean fullCoverage, long averageDocuments) {
boolean changed = group.isFullCoverageStatusChanged(fullCoverage);
if (changed) {
int requiredNodes = groupSize() - dispatchConfig.maxNodesDownPerGroup();
if (fullCoverage) {
log.info(() -> String.format("Group %d is now good again (%d/%d active docs, coverage %d/%d)", index,
group.getActiveDocuments(), averageDocuments, group.workingNodes(), groupSize()));
} else {
log.warning(() -> String.format("Coverage of group %d is only %d/%d (requires %d)", index, group.workingNodes(), groupSize(),
requiredNodes));
}
}
}
} |
I casn't follow this, why did you change this logic? It used to be quite clean and symmetric and now I'm confused. | public void pingIterationCompleted() {
int numGroups = orderedGroups.size();
if (numGroups == 1) {
Group group = groups.values().iterator().next();
group.aggregateActiveDocuments();
updateSufficientCoverage(group, true);
boolean fullCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), group.getActiveDocuments(),
group.getActiveDocuments());
trackGroupCoverageChanges(0, group, fullCoverage, group.getActiveDocuments());
return;
}
long[] activeDocumentsInGroup = new long[numGroups];
long sumOfActiveDocuments = 0;
for(int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
group.aggregateActiveDocuments();
activeDocumentsInGroup[i] = group.getActiveDocuments();
sumOfActiveDocuments += activeDocumentsInGroup[i];
}
boolean anyGroupsSufficientCoverage = false;
for (int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
long activeDocuments = activeDocumentsInGroup[i];
long averageDocumentsInOtherGroups = (sumOfActiveDocuments - activeDocuments) / (numGroups - 1);
boolean sufficientCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), activeDocuments, averageDocumentsInOtherGroups);
anyGroupsSufficientCoverage = anyGroupsSufficientCoverage || sufficientCoverage;
updateSufficientCoverage(group, sufficientCoverage);
trackGroupCoverageChanges(i, group, sufficientCoverage, averageDocumentsInOtherGroups);
}
if ( ! anyGroupsSufficientCoverage && (sumOfActiveDocuments == 0)) {
vipStatus.removeFromRotation(clusterId);
}
} | vipStatus.removeFromRotation(clusterId); | public void pingIterationCompleted() {
int numGroups = orderedGroups.size();
if (numGroups == 1) {
Group group = groups.values().iterator().next();
group.aggregateActiveDocuments();
updateSufficientCoverage(group, true);
boolean fullCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), group.getActiveDocuments(),
group.getActiveDocuments());
trackGroupCoverageChanges(0, group, fullCoverage, group.getActiveDocuments());
return;
}
long[] activeDocumentsInGroup = new long[numGroups];
long sumOfActiveDocuments = 0;
for(int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
group.aggregateActiveDocuments();
activeDocumentsInGroup[i] = group.getActiveDocuments();
sumOfActiveDocuments += activeDocumentsInGroup[i];
}
boolean anyGroupsSufficientCoverage = false;
for (int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
long activeDocuments = activeDocumentsInGroup[i];
long averageDocumentsInOtherGroups = (sumOfActiveDocuments - activeDocuments) / (numGroups - 1);
boolean sufficientCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), activeDocuments, averageDocumentsInOtherGroups);
anyGroupsSufficientCoverage = anyGroupsSufficientCoverage || sufficientCoverage;
updateSufficientCoverage(group, sufficientCoverage);
trackGroupCoverageChanges(i, group, sufficientCoverage, averageDocumentsInOtherGroups);
}
if ( ! anyGroupsSufficientCoverage && (sumOfActiveDocuments == 0)) {
vipStatus.removeFromRotation(clusterId);
}
} | class SearchCluster implements NodeManager<Node> {
private static final Logger log = Logger.getLogger(SearchCluster.class.getName());
private final DispatchConfig dispatchConfig;
private final int size;
private final String clusterId;
private final ImmutableMap<Integer, Group> groups;
private final ImmutableMultimap<String, Node> nodesByHost;
private final ImmutableList<Group> orderedGroups;
private final ClusterMonitor<Node> clusterMonitor;
private final VipStatus vipStatus;
private PingFactory pingFactory;
/**
* A search node on this local machine having the entire corpus, which we therefore
* should prefer to dispatch directly to, or empty if there is no such local search node.
* If there is one, we also maintain the VIP status of this container based on the availability
* of the corpus on this local node (up + has coverage), such that this node is taken out of rotation
* if it only queries this cluster when the local node cannot be used, to avoid unnecessary
* cross-node network traffic.
*/
private final Optional<Node> directDispatchTarget;
public SearchCluster(String clusterId, DispatchConfig dispatchConfig, int containerClusterSize, VipStatus vipStatus) {
this.clusterId = clusterId;
this.dispatchConfig = dispatchConfig;
this.vipStatus = vipStatus;
List<Node> nodes = toNodes(dispatchConfig);
this.size = nodes.size();
ImmutableMap.Builder<Integer, Group> groupsBuilder = new ImmutableMap.Builder<>();
for (Map.Entry<Integer, List<Node>> group : nodes.stream().collect(Collectors.groupingBy(Node::group)).entrySet()) {
Group g = new Group(group.getKey(), group.getValue());
groupsBuilder.put(group.getKey(), g);
}
this.groups = groupsBuilder.build();
LinkedHashMap<Integer, Group> groupIntroductionOrder = new LinkedHashMap<>();
nodes.forEach(node -> groupIntroductionOrder.put(node.group(), groups.get(node.group)));
this.orderedGroups = ImmutableList.<Group>builder().addAll(groupIntroductionOrder.values()).build();
ImmutableMultimap.Builder<String, Node> nodesByHostBuilder = new ImmutableMultimap.Builder<>();
for (Node node : nodes)
nodesByHostBuilder.put(node.hostname(), node);
this.nodesByHost = nodesByHostBuilder.build();
this.directDispatchTarget = findDirectDispatchTarget(HostName.getLocalhost(), size, containerClusterSize,
nodesByHost, groups);
this.clusterMonitor = new ClusterMonitor<>(this);
}
public void startClusterMonitoring(PingFactory pingFactory) {
this.pingFactory = pingFactory;
for (var group : orderedGroups) {
for (var node : group.nodes()) {
working(node);
clusterMonitor.add(node, true);
}
}
}
private static Optional<Node> findDirectDispatchTarget(String selfHostname,
int searchClusterSize,
int containerClusterSize,
ImmutableMultimap<String, Node> nodesByHost,
ImmutableMap<Integer, Group> groups) {
ImmutableCollection<Node> localSearchNodes = nodesByHost.get(selfHostname);
if (localSearchNodes.size() != 1) return Optional.empty();
Node localSearchNode = localSearchNodes.iterator().next();
Group localSearchGroup = groups.get(localSearchNode.group());
if (localSearchGroup.nodes().size() != 1) return Optional.empty();
if (containerClusterSize < searchClusterSize) return Optional.empty();
return Optional.of(localSearchNode);
}
private static ImmutableList<Node> toNodes(DispatchConfig dispatchConfig) {
ImmutableList.Builder<Node> nodesBuilder = new ImmutableList.Builder<>();
Predicate<DispatchConfig.Node> filter;
if (dispatchConfig.useLocalNode()) {
final String hostName = HostName.getLocalhost();
filter = node -> node.host().equals(hostName);
} else {
filter = node -> true;
}
for (DispatchConfig.Node node : dispatchConfig.node()) {
if (filter.test(node)) {
nodesBuilder.add(new Node(node.key(), node.host(), node.fs4port(), node.group()));
}
}
return nodesBuilder.build();
}
public DispatchConfig dispatchConfig() {
return dispatchConfig;
}
/** Returns the number of nodes in this cluster (across all groups) */
public int size() { return size; }
/** Returns the groups of this cluster as an immutable map indexed by group id */
public ImmutableMap<Integer, Group> groups() { return groups; }
/** Returns the groups of this cluster as an immutable list in introduction order */
public ImmutableList<Group> orderedGroups() { return orderedGroups; }
/** Returns the n'th (zero-indexed) group in the cluster if possible */
public Optional<Group> group(int n) {
if (orderedGroups.size() > n) {
return Optional.of(orderedGroups.get(n));
} else {
return Optional.empty();
}
}
/** Returns the number of nodes per group - size()/groups.size() */
public int groupSize() {
if (groups.size() == 0) return size();
return size() / groups.size();
}
public int groupsWithSufficientCoverage() {
int covered = 0;
for (Group g : orderedGroups) {
if (g.hasSufficientCoverage()) {
covered++;
}
}
return covered;
}
/**
* Returns the recipient we should dispatch queries directly to (bypassing fdispatch),
* or empty if we should not dispatch directly.
*/
public Optional<Node> directDispatchTarget() {
if ( directDispatchTarget.isEmpty()) return Optional.empty();
Group localSearchGroup = groups.get(directDispatchTarget.get().group());
if ( ! localSearchGroup.hasSufficientCoverage()) return Optional.empty();
if ( ! directDispatchTarget.get().isWorking()) return Optional.empty();
return directDispatchTarget;
}
/** Used by the cluster monitor to manage node status */
@Override
public void working(Node node) {
node.setWorking(true);
if (usesDirectDispatchTo(node))
vipStatus.addToRotation(clusterId);
}
/** Used by the cluster monitor to manage node status */
@Override
public void failed(Node node) {
node.setWorking(false);
if (usesDirectDispatchTo(node))
vipStatus.removeFromRotation(clusterId);
}
private void updateSufficientCoverage(Group group, boolean sufficientCoverage) {
boolean isInRotation = vipStatus.isInRotation();
boolean hasChanged = sufficientCoverage != group.hasSufficientCoverage();
boolean isDirectDispatchGroupAndChange = usesDirectDispatchTo(group) && hasChanged;
group.setHasSufficientCoverage(sufficientCoverage);
if ((!isInRotation || isDirectDispatchGroupAndChange) && sufficientCoverage) {
vipStatus.addToRotation(clusterId);
} else if (isDirectDispatchGroupAndChange) {
vipStatus.removeFromRotation(clusterId);
}
}
private boolean usesDirectDispatchTo(Node node) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().equals(node);
}
private boolean usesDirectDispatchTo(Group group) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().group() == group.id();
}
/** Used by the cluster monitor to manage node status */
@Override
public void ping(Node node, Executor executor) {
if (pingFactory == null)
return;
FutureTask<Pong> futurePong = new FutureTask<>(pingFactory.createPinger(node, clusterMonitor));
executor.execute(futurePong);
Pong pong = getPong(futurePong, node);
futurePong.cancel(true);
if (pong.badResponse()) {
clusterMonitor.failed(node, pong.getError(0));
} else {
if (pong.activeDocuments().isPresent()) {
node.setActiveDocuments(pong.activeDocuments().get());
}
clusterMonitor.responded(node);
}
}
/**
* Update statistics after a round of issuing pings.
* Note that this doesn't wait for pings to return, so it will typically accumulate data from
* last rounds pinging, or potentially (although unlikely) some combination of new and old data.
*/
@Override
private boolean isGroupCoverageSufficient(int workingNodes, int nodesInGroup, long activeDocuments, long averageDocumentsInOtherGroups) {
boolean sufficientCoverage = true;
if (averageDocumentsInOtherGroups > 0) {
double coverage = 100.0 * (double) activeDocuments / averageDocumentsInOtherGroups;
sufficientCoverage = coverage >= dispatchConfig.minActivedocsPercentage();
}
if (sufficientCoverage) {
sufficientCoverage = isGroupNodeCoverageSufficient(workingNodes, nodesInGroup);
}
return sufficientCoverage;
}
private boolean isGroupNodeCoverageSufficient(int workingNodes, int nodesInGroup) {
int nodesAllowedDown = dispatchConfig.maxNodesDownPerGroup()
+ (int) (((double) nodesInGroup * (100.0 - dispatchConfig.minGroupCoverage())) / 100.0);
return workingNodes + nodesAllowedDown >= nodesInGroup;
}
private Pong getPong(FutureTask<Pong> futurePong, Node node) {
try {
return futurePong.get(clusterMonitor.getConfiguration().getFailLimit(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Ping was interrupted: " + node));
} catch (ExecutionException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Execution was interrupted: " + node));
} catch (TimeoutException e) {
return new Pong(ErrorMessage.createNoAnswerWhenPingingNode("Ping thread timed out"));
}
}
/**
* Calculate whether a subset of nodes in a group has enough coverage
*/
public boolean isPartialGroupCoverageSufficient(OptionalInt knownGroupId, List<Node> nodes) {
if (orderedGroups.size() == 1) {
boolean sufficient = nodes.size() >= groupSize() - dispatchConfig.maxNodesDownPerGroup();
return sufficient;
}
if (knownGroupId.isEmpty()) {
return false;
}
int groupId = knownGroupId.getAsInt();
Group group = groups.get(groupId);
if (group == null) {
return false;
}
int nodesInGroup = group.nodes().size();
long sumOfActiveDocuments = 0;
int otherGroups = 0;
for (Group g : orderedGroups) {
if (g.id() != groupId) {
sumOfActiveDocuments += g.getActiveDocuments();
otherGroups++;
}
}
long activeDocuments = 0;
for (Node n : nodes) {
activeDocuments += n.getActiveDocuments();
}
long averageDocumentsInOtherGroups = sumOfActiveDocuments / otherGroups;
boolean sufficient = isGroupCoverageSufficient(nodes.size(), nodesInGroup, activeDocuments, averageDocumentsInOtherGroups);
return sufficient;
}
private void trackGroupCoverageChanges(int index, Group group, boolean fullCoverage, long averageDocuments) {
boolean changed = group.isFullCoverageStatusChanged(fullCoverage);
if (changed) {
int requiredNodes = groupSize() - dispatchConfig.maxNodesDownPerGroup();
if (fullCoverage) {
log.info(() -> String.format("Group %d is now good again (%d/%d active docs, coverage %d/%d)", index,
group.getActiveDocuments(), averageDocuments, group.workingNodes(), groupSize()));
} else {
log.warning(() -> String.format("Coverage of group %d is only %d/%d (requires %d)", index, group.workingNodes(), groupSize(),
requiredNodes));
}
}
}
} | class SearchCluster implements NodeManager<Node> {
private static final Logger log = Logger.getLogger(SearchCluster.class.getName());
private final DispatchConfig dispatchConfig;
private final int size;
private final String clusterId;
private final ImmutableMap<Integer, Group> groups;
private final ImmutableMultimap<String, Node> nodesByHost;
private final ImmutableList<Group> orderedGroups;
private final ClusterMonitor<Node> clusterMonitor;
private final VipStatus vipStatus;
private PingFactory pingFactory;
/**
* A search node on this local machine having the entire corpus, which we therefore
* should prefer to dispatch directly to, or empty if there is no such local search node.
* If there is one, we also maintain the VIP status of this container based on the availability
* of the corpus on this local node (up + has coverage), such that this node is taken out of rotation
* if it only queries this cluster when the local node cannot be used, to avoid unnecessary
* cross-node network traffic.
*/
private final Optional<Node> directDispatchTarget;
public SearchCluster(String clusterId, DispatchConfig dispatchConfig, int containerClusterSize, VipStatus vipStatus) {
this.clusterId = clusterId;
this.dispatchConfig = dispatchConfig;
this.vipStatus = vipStatus;
List<Node> nodes = toNodes(dispatchConfig);
this.size = nodes.size();
ImmutableMap.Builder<Integer, Group> groupsBuilder = new ImmutableMap.Builder<>();
for (Map.Entry<Integer, List<Node>> group : nodes.stream().collect(Collectors.groupingBy(Node::group)).entrySet()) {
Group g = new Group(group.getKey(), group.getValue());
groupsBuilder.put(group.getKey(), g);
}
this.groups = groupsBuilder.build();
LinkedHashMap<Integer, Group> groupIntroductionOrder = new LinkedHashMap<>();
nodes.forEach(node -> groupIntroductionOrder.put(node.group(), groups.get(node.group)));
this.orderedGroups = ImmutableList.<Group>builder().addAll(groupIntroductionOrder.values()).build();
ImmutableMultimap.Builder<String, Node> nodesByHostBuilder = new ImmutableMultimap.Builder<>();
for (Node node : nodes)
nodesByHostBuilder.put(node.hostname(), node);
this.nodesByHost = nodesByHostBuilder.build();
this.directDispatchTarget = findDirectDispatchTarget(HostName.getLocalhost(), size, containerClusterSize,
nodesByHost, groups);
this.clusterMonitor = new ClusterMonitor<>(this);
}
public void startClusterMonitoring(PingFactory pingFactory) {
this.pingFactory = pingFactory;
for (var group : orderedGroups) {
for (var node : group.nodes()) {
working(node);
clusterMonitor.add(node, true);
}
}
}
private static Optional<Node> findDirectDispatchTarget(String selfHostname,
int searchClusterSize,
int containerClusterSize,
ImmutableMultimap<String, Node> nodesByHost,
ImmutableMap<Integer, Group> groups) {
ImmutableCollection<Node> localSearchNodes = nodesByHost.get(selfHostname);
if (localSearchNodes.size() != 1) return Optional.empty();
Node localSearchNode = localSearchNodes.iterator().next();
Group localSearchGroup = groups.get(localSearchNode.group());
if (localSearchGroup.nodes().size() != 1) return Optional.empty();
if (containerClusterSize < searchClusterSize) return Optional.empty();
return Optional.of(localSearchNode);
}
private static ImmutableList<Node> toNodes(DispatchConfig dispatchConfig) {
ImmutableList.Builder<Node> nodesBuilder = new ImmutableList.Builder<>();
Predicate<DispatchConfig.Node> filter;
if (dispatchConfig.useLocalNode()) {
final String hostName = HostName.getLocalhost();
filter = node -> node.host().equals(hostName);
} else {
filter = node -> true;
}
for (DispatchConfig.Node node : dispatchConfig.node()) {
if (filter.test(node)) {
nodesBuilder.add(new Node(node.key(), node.host(), node.fs4port(), node.group()));
}
}
return nodesBuilder.build();
}
public DispatchConfig dispatchConfig() {
return dispatchConfig;
}
/** Returns the number of nodes in this cluster (across all groups) */
public int size() { return size; }
/** Returns the groups of this cluster as an immutable map indexed by group id */
public ImmutableMap<Integer, Group> groups() { return groups; }
/** Returns the groups of this cluster as an immutable list in introduction order */
public ImmutableList<Group> orderedGroups() { return orderedGroups; }
/** Returns the n'th (zero-indexed) group in the cluster if possible */
public Optional<Group> group(int n) {
if (orderedGroups.size() > n) {
return Optional.of(orderedGroups.get(n));
} else {
return Optional.empty();
}
}
/** Returns the number of nodes per group - size()/groups.size() */
public int groupSize() {
if (groups.size() == 0) return size();
return size() / groups.size();
}
public int groupsWithSufficientCoverage() {
int covered = 0;
for (Group g : orderedGroups) {
if (g.hasSufficientCoverage()) {
covered++;
}
}
return covered;
}
/**
* Returns the recipient we should dispatch queries directly to (bypassing fdispatch),
* or empty if we should not dispatch directly.
*/
public Optional<Node> directDispatchTarget() {
if ( directDispatchTarget.isEmpty()) return Optional.empty();
Group localSearchGroup = groups.get(directDispatchTarget.get().group());
if ( ! localSearchGroup.hasSufficientCoverage()) return Optional.empty();
if ( ! directDispatchTarget.get().isWorking()) return Optional.empty();
return directDispatchTarget;
}
/** Used by the cluster monitor to manage node status */
@Override
public void working(Node node) {
node.setWorking(true);
if (usesDirectDispatchTo(node))
vipStatus.addToRotation(clusterId);
}
/** Used by the cluster monitor to manage node status */
@Override
public void failed(Node node) {
node.setWorking(false);
if (usesDirectDispatchTo(node))
vipStatus.removeFromRotation(clusterId);
}
private void updateSufficientCoverage(Group group, boolean sufficientCoverage) {
boolean isInRotation = vipStatus.isInRotation();
boolean hasChanged = sufficientCoverage != group.hasSufficientCoverage();
boolean isDirectDispatchGroupAndChange = usesDirectDispatchTo(group) && hasChanged;
group.setHasSufficientCoverage(sufficientCoverage);
if ((!isInRotation || isDirectDispatchGroupAndChange) && sufficientCoverage) {
vipStatus.addToRotation(clusterId);
} else if (isDirectDispatchGroupAndChange) {
vipStatus.removeFromRotation(clusterId);
}
}
private boolean usesDirectDispatchTo(Node node) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().equals(node);
}
private boolean usesDirectDispatchTo(Group group) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().group() == group.id();
}
/** Used by the cluster monitor to manage node status */
@Override
public void ping(Node node, Executor executor) {
if (pingFactory == null)
return;
FutureTask<Pong> futurePong = new FutureTask<>(pingFactory.createPinger(node, clusterMonitor));
executor.execute(futurePong);
Pong pong = getPong(futurePong, node);
futurePong.cancel(true);
if (pong.badResponse()) {
clusterMonitor.failed(node, pong.getError(0));
} else {
if (pong.activeDocuments().isPresent()) {
node.setActiveDocuments(pong.activeDocuments().get());
}
clusterMonitor.responded(node);
}
}
/**
* Update statistics after a round of issuing pings.
* Note that this doesn't wait for pings to return, so it will typically accumulate data from
* last rounds pinging, or potentially (although unlikely) some combination of new and old data.
*/
@Override
private boolean isGroupCoverageSufficient(int workingNodes, int nodesInGroup, long activeDocuments, long averageDocumentsInOtherGroups) {
boolean sufficientCoverage = true;
if (averageDocumentsInOtherGroups > 0) {
double coverage = 100.0 * (double) activeDocuments / averageDocumentsInOtherGroups;
sufficientCoverage = coverage >= dispatchConfig.minActivedocsPercentage();
}
if (sufficientCoverage) {
sufficientCoverage = isGroupNodeCoverageSufficient(workingNodes, nodesInGroup);
}
return sufficientCoverage;
}
private boolean isGroupNodeCoverageSufficient(int workingNodes, int nodesInGroup) {
int nodesAllowedDown = dispatchConfig.maxNodesDownPerGroup()
+ (int) (((double) nodesInGroup * (100.0 - dispatchConfig.minGroupCoverage())) / 100.0);
return workingNodes + nodesAllowedDown >= nodesInGroup;
}
private Pong getPong(FutureTask<Pong> futurePong, Node node) {
try {
return futurePong.get(clusterMonitor.getConfiguration().getFailLimit(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Ping was interrupted: " + node));
} catch (ExecutionException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Execution was interrupted: " + node));
} catch (TimeoutException e) {
return new Pong(ErrorMessage.createNoAnswerWhenPingingNode("Ping thread timed out"));
}
}
/**
* Calculate whether a subset of nodes in a group has enough coverage
*/
public boolean isPartialGroupCoverageSufficient(OptionalInt knownGroupId, List<Node> nodes) {
if (orderedGroups.size() == 1) {
boolean sufficient = nodes.size() >= groupSize() - dispatchConfig.maxNodesDownPerGroup();
return sufficient;
}
if (knownGroupId.isEmpty()) {
return false;
}
int groupId = knownGroupId.getAsInt();
Group group = groups.get(groupId);
if (group == null) {
return false;
}
int nodesInGroup = group.nodes().size();
long sumOfActiveDocuments = 0;
int otherGroups = 0;
for (Group g : orderedGroups) {
if (g.id() != groupId) {
sumOfActiveDocuments += g.getActiveDocuments();
otherGroups++;
}
}
long activeDocuments = 0;
for (Node n : nodes) {
activeDocuments += n.getActiveDocuments();
}
long averageDocumentsInOtherGroups = sumOfActiveDocuments / otherGroups;
boolean sufficient = isGroupCoverageSufficient(nodes.size(), nodesInGroup, activeDocuments, averageDocumentsInOtherGroups);
return sufficient;
}
private void trackGroupCoverageChanges(int index, Group group, boolean fullCoverage, long averageDocuments) {
boolean changed = group.isFullCoverageStatusChanged(fullCoverage);
if (changed) {
int requiredNodes = groupSize() - dispatchConfig.maxNodesDownPerGroup();
if (fullCoverage) {
log.info(() -> String.format("Group %d is now good again (%d/%d active docs, coverage %d/%d)", index,
group.getActiveDocuments(), averageDocuments, group.workingNodes(), groupSize()));
} else {
log.warning(() -> String.format("Coverage of group %d is only %d/%d (requires %d)", index, group.workingNodes(), groupSize(),
requiredNodes));
}
}
}
} |
I have added some clarifying comments to the code. But in essence this will remove it from rotation when no groups have sufficient coverage and there are no documents to be served. In essence this is when all nodes in all groups are down. | public void pingIterationCompleted() {
int numGroups = orderedGroups.size();
if (numGroups == 1) {
Group group = groups.values().iterator().next();
group.aggregateActiveDocuments();
updateSufficientCoverage(group, true);
boolean fullCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), group.getActiveDocuments(),
group.getActiveDocuments());
trackGroupCoverageChanges(0, group, fullCoverage, group.getActiveDocuments());
return;
}
long[] activeDocumentsInGroup = new long[numGroups];
long sumOfActiveDocuments = 0;
for(int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
group.aggregateActiveDocuments();
activeDocumentsInGroup[i] = group.getActiveDocuments();
sumOfActiveDocuments += activeDocumentsInGroup[i];
}
boolean anyGroupsSufficientCoverage = false;
for (int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
long activeDocuments = activeDocumentsInGroup[i];
long averageDocumentsInOtherGroups = (sumOfActiveDocuments - activeDocuments) / (numGroups - 1);
boolean sufficientCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), activeDocuments, averageDocumentsInOtherGroups);
anyGroupsSufficientCoverage = anyGroupsSufficientCoverage || sufficientCoverage;
updateSufficientCoverage(group, sufficientCoverage);
trackGroupCoverageChanges(i, group, sufficientCoverage, averageDocumentsInOtherGroups);
}
if ( ! anyGroupsSufficientCoverage && (sumOfActiveDocuments == 0)) {
vipStatus.removeFromRotation(clusterId);
}
} | vipStatus.removeFromRotation(clusterId); | public void pingIterationCompleted() {
int numGroups = orderedGroups.size();
if (numGroups == 1) {
Group group = groups.values().iterator().next();
group.aggregateActiveDocuments();
updateSufficientCoverage(group, true);
boolean fullCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), group.getActiveDocuments(),
group.getActiveDocuments());
trackGroupCoverageChanges(0, group, fullCoverage, group.getActiveDocuments());
return;
}
long[] activeDocumentsInGroup = new long[numGroups];
long sumOfActiveDocuments = 0;
for(int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
group.aggregateActiveDocuments();
activeDocumentsInGroup[i] = group.getActiveDocuments();
sumOfActiveDocuments += activeDocumentsInGroup[i];
}
boolean anyGroupsSufficientCoverage = false;
for (int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
long activeDocuments = activeDocumentsInGroup[i];
long averageDocumentsInOtherGroups = (sumOfActiveDocuments - activeDocuments) / (numGroups - 1);
boolean sufficientCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), activeDocuments, averageDocumentsInOtherGroups);
anyGroupsSufficientCoverage = anyGroupsSufficientCoverage || sufficientCoverage;
updateSufficientCoverage(group, sufficientCoverage);
trackGroupCoverageChanges(i, group, sufficientCoverage, averageDocumentsInOtherGroups);
}
if ( ! anyGroupsSufficientCoverage && (sumOfActiveDocuments == 0)) {
vipStatus.removeFromRotation(clusterId);
}
} | class SearchCluster implements NodeManager<Node> {
private static final Logger log = Logger.getLogger(SearchCluster.class.getName());
private final DispatchConfig dispatchConfig;
private final int size;
private final String clusterId;
private final ImmutableMap<Integer, Group> groups;
private final ImmutableMultimap<String, Node> nodesByHost;
private final ImmutableList<Group> orderedGroups;
private final ClusterMonitor<Node> clusterMonitor;
private final VipStatus vipStatus;
private PingFactory pingFactory;
/**
* A search node on this local machine having the entire corpus, which we therefore
* should prefer to dispatch directly to, or empty if there is no such local search node.
* If there is one, we also maintain the VIP status of this container based on the availability
* of the corpus on this local node (up + has coverage), such that this node is taken out of rotation
* if it only queries this cluster when the local node cannot be used, to avoid unnecessary
* cross-node network traffic.
*/
private final Optional<Node> directDispatchTarget;
public SearchCluster(String clusterId, DispatchConfig dispatchConfig, int containerClusterSize, VipStatus vipStatus) {
this.clusterId = clusterId;
this.dispatchConfig = dispatchConfig;
this.vipStatus = vipStatus;
List<Node> nodes = toNodes(dispatchConfig);
this.size = nodes.size();
ImmutableMap.Builder<Integer, Group> groupsBuilder = new ImmutableMap.Builder<>();
for (Map.Entry<Integer, List<Node>> group : nodes.stream().collect(Collectors.groupingBy(Node::group)).entrySet()) {
Group g = new Group(group.getKey(), group.getValue());
groupsBuilder.put(group.getKey(), g);
}
this.groups = groupsBuilder.build();
LinkedHashMap<Integer, Group> groupIntroductionOrder = new LinkedHashMap<>();
nodes.forEach(node -> groupIntroductionOrder.put(node.group(), groups.get(node.group)));
this.orderedGroups = ImmutableList.<Group>builder().addAll(groupIntroductionOrder.values()).build();
ImmutableMultimap.Builder<String, Node> nodesByHostBuilder = new ImmutableMultimap.Builder<>();
for (Node node : nodes)
nodesByHostBuilder.put(node.hostname(), node);
this.nodesByHost = nodesByHostBuilder.build();
this.directDispatchTarget = findDirectDispatchTarget(HostName.getLocalhost(), size, containerClusterSize,
nodesByHost, groups);
this.clusterMonitor = new ClusterMonitor<>(this);
}
public void startClusterMonitoring(PingFactory pingFactory) {
this.pingFactory = pingFactory;
for (var group : orderedGroups) {
for (var node : group.nodes()) {
working(node);
clusterMonitor.add(node, true);
}
}
}
private static Optional<Node> findDirectDispatchTarget(String selfHostname,
int searchClusterSize,
int containerClusterSize,
ImmutableMultimap<String, Node> nodesByHost,
ImmutableMap<Integer, Group> groups) {
ImmutableCollection<Node> localSearchNodes = nodesByHost.get(selfHostname);
if (localSearchNodes.size() != 1) return Optional.empty();
Node localSearchNode = localSearchNodes.iterator().next();
Group localSearchGroup = groups.get(localSearchNode.group());
if (localSearchGroup.nodes().size() != 1) return Optional.empty();
if (containerClusterSize < searchClusterSize) return Optional.empty();
return Optional.of(localSearchNode);
}
private static ImmutableList<Node> toNodes(DispatchConfig dispatchConfig) {
ImmutableList.Builder<Node> nodesBuilder = new ImmutableList.Builder<>();
Predicate<DispatchConfig.Node> filter;
if (dispatchConfig.useLocalNode()) {
final String hostName = HostName.getLocalhost();
filter = node -> node.host().equals(hostName);
} else {
filter = node -> true;
}
for (DispatchConfig.Node node : dispatchConfig.node()) {
if (filter.test(node)) {
nodesBuilder.add(new Node(node.key(), node.host(), node.fs4port(), node.group()));
}
}
return nodesBuilder.build();
}
public DispatchConfig dispatchConfig() {
return dispatchConfig;
}
/** Returns the number of nodes in this cluster (across all groups) */
public int size() { return size; }
/** Returns the groups of this cluster as an immutable map indexed by group id */
public ImmutableMap<Integer, Group> groups() { return groups; }
/** Returns the groups of this cluster as an immutable list in introduction order */
public ImmutableList<Group> orderedGroups() { return orderedGroups; }
/** Returns the n'th (zero-indexed) group in the cluster if possible */
public Optional<Group> group(int n) {
if (orderedGroups.size() > n) {
return Optional.of(orderedGroups.get(n));
} else {
return Optional.empty();
}
}
/** Returns the number of nodes per group - size()/groups.size() */
public int groupSize() {
if (groups.size() == 0) return size();
return size() / groups.size();
}
public int groupsWithSufficientCoverage() {
int covered = 0;
for (Group g : orderedGroups) {
if (g.hasSufficientCoverage()) {
covered++;
}
}
return covered;
}
/**
* Returns the recipient we should dispatch queries directly to (bypassing fdispatch),
* or empty if we should not dispatch directly.
*/
public Optional<Node> directDispatchTarget() {
if ( directDispatchTarget.isEmpty()) return Optional.empty();
Group localSearchGroup = groups.get(directDispatchTarget.get().group());
if ( ! localSearchGroup.hasSufficientCoverage()) return Optional.empty();
if ( ! directDispatchTarget.get().isWorking()) return Optional.empty();
return directDispatchTarget;
}
/** Used by the cluster monitor to manage node status */
@Override
public void working(Node node) {
node.setWorking(true);
if (usesDirectDispatchTo(node))
vipStatus.addToRotation(clusterId);
}
/** Used by the cluster monitor to manage node status */
@Override
public void failed(Node node) {
node.setWorking(false);
if (usesDirectDispatchTo(node))
vipStatus.removeFromRotation(clusterId);
}
private void updateSufficientCoverage(Group group, boolean sufficientCoverage) {
boolean isInRotation = vipStatus.isInRotation();
boolean hasChanged = sufficientCoverage != group.hasSufficientCoverage();
boolean isDirectDispatchGroupAndChange = usesDirectDispatchTo(group) && hasChanged;
group.setHasSufficientCoverage(sufficientCoverage);
if ((!isInRotation || isDirectDispatchGroupAndChange) && sufficientCoverage) {
vipStatus.addToRotation(clusterId);
} else if (isDirectDispatchGroupAndChange) {
vipStatus.removeFromRotation(clusterId);
}
}
private boolean usesDirectDispatchTo(Node node) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().equals(node);
}
private boolean usesDirectDispatchTo(Group group) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().group() == group.id();
}
/** Used by the cluster monitor to manage node status */
@Override
public void ping(Node node, Executor executor) {
if (pingFactory == null)
return;
FutureTask<Pong> futurePong = new FutureTask<>(pingFactory.createPinger(node, clusterMonitor));
executor.execute(futurePong);
Pong pong = getPong(futurePong, node);
futurePong.cancel(true);
if (pong.badResponse()) {
clusterMonitor.failed(node, pong.getError(0));
} else {
if (pong.activeDocuments().isPresent()) {
node.setActiveDocuments(pong.activeDocuments().get());
}
clusterMonitor.responded(node);
}
}
/**
* Update statistics after a round of issuing pings.
* Note that this doesn't wait for pings to return, so it will typically accumulate data from
* last rounds pinging, or potentially (although unlikely) some combination of new and old data.
*/
@Override
private boolean isGroupCoverageSufficient(int workingNodes, int nodesInGroup, long activeDocuments, long averageDocumentsInOtherGroups) {
boolean sufficientCoverage = true;
if (averageDocumentsInOtherGroups > 0) {
double coverage = 100.0 * (double) activeDocuments / averageDocumentsInOtherGroups;
sufficientCoverage = coverage >= dispatchConfig.minActivedocsPercentage();
}
if (sufficientCoverage) {
sufficientCoverage = isGroupNodeCoverageSufficient(workingNodes, nodesInGroup);
}
return sufficientCoverage;
}
private boolean isGroupNodeCoverageSufficient(int workingNodes, int nodesInGroup) {
int nodesAllowedDown = dispatchConfig.maxNodesDownPerGroup()
+ (int) (((double) nodesInGroup * (100.0 - dispatchConfig.minGroupCoverage())) / 100.0);
return workingNodes + nodesAllowedDown >= nodesInGroup;
}
private Pong getPong(FutureTask<Pong> futurePong, Node node) {
try {
return futurePong.get(clusterMonitor.getConfiguration().getFailLimit(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Ping was interrupted: " + node));
} catch (ExecutionException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Execution was interrupted: " + node));
} catch (TimeoutException e) {
return new Pong(ErrorMessage.createNoAnswerWhenPingingNode("Ping thread timed out"));
}
}
/**
* Calculate whether a subset of nodes in a group has enough coverage
*/
public boolean isPartialGroupCoverageSufficient(OptionalInt knownGroupId, List<Node> nodes) {
if (orderedGroups.size() == 1) {
boolean sufficient = nodes.size() >= groupSize() - dispatchConfig.maxNodesDownPerGroup();
return sufficient;
}
if (knownGroupId.isEmpty()) {
return false;
}
int groupId = knownGroupId.getAsInt();
Group group = groups.get(groupId);
if (group == null) {
return false;
}
int nodesInGroup = group.nodes().size();
long sumOfActiveDocuments = 0;
int otherGroups = 0;
for (Group g : orderedGroups) {
if (g.id() != groupId) {
sumOfActiveDocuments += g.getActiveDocuments();
otherGroups++;
}
}
long activeDocuments = 0;
for (Node n : nodes) {
activeDocuments += n.getActiveDocuments();
}
long averageDocumentsInOtherGroups = sumOfActiveDocuments / otherGroups;
boolean sufficient = isGroupCoverageSufficient(nodes.size(), nodesInGroup, activeDocuments, averageDocumentsInOtherGroups);
return sufficient;
}
private void trackGroupCoverageChanges(int index, Group group, boolean fullCoverage, long averageDocuments) {
boolean changed = group.isFullCoverageStatusChanged(fullCoverage);
if (changed) {
int requiredNodes = groupSize() - dispatchConfig.maxNodesDownPerGroup();
if (fullCoverage) {
log.info(() -> String.format("Group %d is now good again (%d/%d active docs, coverage %d/%d)", index,
group.getActiveDocuments(), averageDocuments, group.workingNodes(), groupSize()));
} else {
log.warning(() -> String.format("Coverage of group %d is only %d/%d (requires %d)", index, group.workingNodes(), groupSize(),
requiredNodes));
}
}
}
} | class SearchCluster implements NodeManager<Node> {
private static final Logger log = Logger.getLogger(SearchCluster.class.getName());
private final DispatchConfig dispatchConfig;
private final int size;
private final String clusterId;
private final ImmutableMap<Integer, Group> groups;
private final ImmutableMultimap<String, Node> nodesByHost;
private final ImmutableList<Group> orderedGroups;
private final ClusterMonitor<Node> clusterMonitor;
private final VipStatus vipStatus;
private PingFactory pingFactory;
/**
* A search node on this local machine having the entire corpus, which we therefore
* should prefer to dispatch directly to, or empty if there is no such local search node.
* If there is one, we also maintain the VIP status of this container based on the availability
* of the corpus on this local node (up + has coverage), such that this node is taken out of rotation
* if it only queries this cluster when the local node cannot be used, to avoid unnecessary
* cross-node network traffic.
*/
private final Optional<Node> directDispatchTarget;
public SearchCluster(String clusterId, DispatchConfig dispatchConfig, int containerClusterSize, VipStatus vipStatus) {
this.clusterId = clusterId;
this.dispatchConfig = dispatchConfig;
this.vipStatus = vipStatus;
List<Node> nodes = toNodes(dispatchConfig);
this.size = nodes.size();
ImmutableMap.Builder<Integer, Group> groupsBuilder = new ImmutableMap.Builder<>();
for (Map.Entry<Integer, List<Node>> group : nodes.stream().collect(Collectors.groupingBy(Node::group)).entrySet()) {
Group g = new Group(group.getKey(), group.getValue());
groupsBuilder.put(group.getKey(), g);
}
this.groups = groupsBuilder.build();
LinkedHashMap<Integer, Group> groupIntroductionOrder = new LinkedHashMap<>();
nodes.forEach(node -> groupIntroductionOrder.put(node.group(), groups.get(node.group)));
this.orderedGroups = ImmutableList.<Group>builder().addAll(groupIntroductionOrder.values()).build();
ImmutableMultimap.Builder<String, Node> nodesByHostBuilder = new ImmutableMultimap.Builder<>();
for (Node node : nodes)
nodesByHostBuilder.put(node.hostname(), node);
this.nodesByHost = nodesByHostBuilder.build();
this.directDispatchTarget = findDirectDispatchTarget(HostName.getLocalhost(), size, containerClusterSize,
nodesByHost, groups);
this.clusterMonitor = new ClusterMonitor<>(this);
}
public void startClusterMonitoring(PingFactory pingFactory) {
this.pingFactory = pingFactory;
for (var group : orderedGroups) {
for (var node : group.nodes()) {
working(node);
clusterMonitor.add(node, true);
}
}
}
private static Optional<Node> findDirectDispatchTarget(String selfHostname,
int searchClusterSize,
int containerClusterSize,
ImmutableMultimap<String, Node> nodesByHost,
ImmutableMap<Integer, Group> groups) {
ImmutableCollection<Node> localSearchNodes = nodesByHost.get(selfHostname);
if (localSearchNodes.size() != 1) return Optional.empty();
Node localSearchNode = localSearchNodes.iterator().next();
Group localSearchGroup = groups.get(localSearchNode.group());
if (localSearchGroup.nodes().size() != 1) return Optional.empty();
if (containerClusterSize < searchClusterSize) return Optional.empty();
return Optional.of(localSearchNode);
}
private static ImmutableList<Node> toNodes(DispatchConfig dispatchConfig) {
ImmutableList.Builder<Node> nodesBuilder = new ImmutableList.Builder<>();
Predicate<DispatchConfig.Node> filter;
if (dispatchConfig.useLocalNode()) {
final String hostName = HostName.getLocalhost();
filter = node -> node.host().equals(hostName);
} else {
filter = node -> true;
}
for (DispatchConfig.Node node : dispatchConfig.node()) {
if (filter.test(node)) {
nodesBuilder.add(new Node(node.key(), node.host(), node.fs4port(), node.group()));
}
}
return nodesBuilder.build();
}
public DispatchConfig dispatchConfig() {
return dispatchConfig;
}
/** Returns the number of nodes in this cluster (across all groups) */
public int size() { return size; }
/** Returns the groups of this cluster as an immutable map indexed by group id */
public ImmutableMap<Integer, Group> groups() { return groups; }
/** Returns the groups of this cluster as an immutable list in introduction order */
public ImmutableList<Group> orderedGroups() { return orderedGroups; }
/** Returns the n'th (zero-indexed) group in the cluster if possible */
public Optional<Group> group(int n) {
if (orderedGroups.size() > n) {
return Optional.of(orderedGroups.get(n));
} else {
return Optional.empty();
}
}
/** Returns the number of nodes per group - size()/groups.size() */
public int groupSize() {
if (groups.size() == 0) return size();
return size() / groups.size();
}
public int groupsWithSufficientCoverage() {
int covered = 0;
for (Group g : orderedGroups) {
if (g.hasSufficientCoverage()) {
covered++;
}
}
return covered;
}
/**
* Returns the recipient we should dispatch queries directly to (bypassing fdispatch),
* or empty if we should not dispatch directly.
*/
public Optional<Node> directDispatchTarget() {
if ( directDispatchTarget.isEmpty()) return Optional.empty();
Group localSearchGroup = groups.get(directDispatchTarget.get().group());
if ( ! localSearchGroup.hasSufficientCoverage()) return Optional.empty();
if ( ! directDispatchTarget.get().isWorking()) return Optional.empty();
return directDispatchTarget;
}
/** Used by the cluster monitor to manage node status */
@Override
public void working(Node node) {
node.setWorking(true);
if (usesDirectDispatchTo(node))
vipStatus.addToRotation(clusterId);
}
/** Used by the cluster monitor to manage node status */
@Override
public void failed(Node node) {
node.setWorking(false);
if (usesDirectDispatchTo(node))
vipStatus.removeFromRotation(clusterId);
}
private void updateSufficientCoverage(Group group, boolean sufficientCoverage) {
boolean isInRotation = vipStatus.isInRotation();
boolean hasChanged = sufficientCoverage != group.hasSufficientCoverage();
boolean isDirectDispatchGroupAndChange = usesDirectDispatchTo(group) && hasChanged;
group.setHasSufficientCoverage(sufficientCoverage);
if ((!isInRotation || isDirectDispatchGroupAndChange) && sufficientCoverage) {
vipStatus.addToRotation(clusterId);
} else if (isDirectDispatchGroupAndChange) {
vipStatus.removeFromRotation(clusterId);
}
}
private boolean usesDirectDispatchTo(Node node) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().equals(node);
}
private boolean usesDirectDispatchTo(Group group) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().group() == group.id();
}
/** Used by the cluster monitor to manage node status */
@Override
public void ping(Node node, Executor executor) {
if (pingFactory == null)
return;
FutureTask<Pong> futurePong = new FutureTask<>(pingFactory.createPinger(node, clusterMonitor));
executor.execute(futurePong);
Pong pong = getPong(futurePong, node);
futurePong.cancel(true);
if (pong.badResponse()) {
clusterMonitor.failed(node, pong.getError(0));
} else {
if (pong.activeDocuments().isPresent()) {
node.setActiveDocuments(pong.activeDocuments().get());
}
clusterMonitor.responded(node);
}
}
/**
* Update statistics after a round of issuing pings.
* Note that this doesn't wait for pings to return, so it will typically accumulate data from
* last rounds pinging, or potentially (although unlikely) some combination of new and old data.
*/
@Override
private boolean isGroupCoverageSufficient(int workingNodes, int nodesInGroup, long activeDocuments, long averageDocumentsInOtherGroups) {
boolean sufficientCoverage = true;
if (averageDocumentsInOtherGroups > 0) {
double coverage = 100.0 * (double) activeDocuments / averageDocumentsInOtherGroups;
sufficientCoverage = coverage >= dispatchConfig.minActivedocsPercentage();
}
if (sufficientCoverage) {
sufficientCoverage = isGroupNodeCoverageSufficient(workingNodes, nodesInGroup);
}
return sufficientCoverage;
}
private boolean isGroupNodeCoverageSufficient(int workingNodes, int nodesInGroup) {
int nodesAllowedDown = dispatchConfig.maxNodesDownPerGroup()
+ (int) (((double) nodesInGroup * (100.0 - dispatchConfig.minGroupCoverage())) / 100.0);
return workingNodes + nodesAllowedDown >= nodesInGroup;
}
private Pong getPong(FutureTask<Pong> futurePong, Node node) {
try {
return futurePong.get(clusterMonitor.getConfiguration().getFailLimit(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Ping was interrupted: " + node));
} catch (ExecutionException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Execution was interrupted: " + node));
} catch (TimeoutException e) {
return new Pong(ErrorMessage.createNoAnswerWhenPingingNode("Ping thread timed out"));
}
}
/**
* Calculate whether a subset of nodes in a group has enough coverage
*/
public boolean isPartialGroupCoverageSufficient(OptionalInt knownGroupId, List<Node> nodes) {
if (orderedGroups.size() == 1) {
boolean sufficient = nodes.size() >= groupSize() - dispatchConfig.maxNodesDownPerGroup();
return sufficient;
}
if (knownGroupId.isEmpty()) {
return false;
}
int groupId = knownGroupId.getAsInt();
Group group = groups.get(groupId);
if (group == null) {
return false;
}
int nodesInGroup = group.nodes().size();
long sumOfActiveDocuments = 0;
int otherGroups = 0;
for (Group g : orderedGroups) {
if (g.id() != groupId) {
sumOfActiveDocuments += g.getActiveDocuments();
otherGroups++;
}
}
long activeDocuments = 0;
for (Node n : nodes) {
activeDocuments += n.getActiveDocuments();
}
long averageDocumentsInOtherGroups = sumOfActiveDocuments / otherGroups;
boolean sufficient = isGroupCoverageSufficient(nodes.size(), nodesInGroup, activeDocuments, averageDocumentsInOtherGroups);
return sufficient;
}
private void trackGroupCoverageChanges(int index, Group group, boolean fullCoverage, long averageDocuments) {
boolean changed = group.isFullCoverageStatusChanged(fullCoverage);
if (changed) {
int requiredNodes = groupSize() - dispatchConfig.maxNodesDownPerGroup();
if (fullCoverage) {
log.info(() -> String.format("Group %d is now good again (%d/%d active docs, coverage %d/%d)", index,
group.getActiveDocuments(), averageDocuments, group.workingNodes(), groupSize()));
} else {
log.warning(() -> String.format("Coverage of group %d is only %d/%d (requires %d)", index, group.workingNodes(), groupSize(),
requiredNodes));
}
}
}
} |
Not sure if I follow. Is this with respect to readability, or correctness ? The rewrite here was to enable it put it in rotation if it was not also when it is not a direct dispatch group. If not status would never be 'green'. | private void updateSufficientCoverage(Group group, boolean sufficientCoverage) {
boolean isInRotation = vipStatus.isInRotation();
boolean hasChanged = sufficientCoverage != group.hasSufficientCoverage();
boolean isDirectDispatchGroupAndChange = usesDirectDispatchTo(group) && hasChanged;
group.setHasSufficientCoverage(sufficientCoverage);
if ((!isInRotation || isDirectDispatchGroupAndChange) && sufficientCoverage) {
vipStatus.addToRotation(clusterId);
} else if (isDirectDispatchGroupAndChange) {
vipStatus.removeFromRotation(clusterId);
}
} | } else if (isDirectDispatchGroupAndChange) { | private void updateSufficientCoverage(Group group, boolean sufficientCoverage) {
boolean isInRotation = vipStatus.isInRotation();
boolean hasChanged = sufficientCoverage != group.hasSufficientCoverage();
boolean isDirectDispatchGroupAndChange = usesDirectDispatchTo(group) && hasChanged;
group.setHasSufficientCoverage(sufficientCoverage);
if ((!isInRotation || isDirectDispatchGroupAndChange) && sufficientCoverage) {
vipStatus.addToRotation(clusterId);
} else if (isDirectDispatchGroupAndChange) {
vipStatus.removeFromRotation(clusterId);
}
} | class SearchCluster implements NodeManager<Node> {
private static final Logger log = Logger.getLogger(SearchCluster.class.getName());
private final DispatchConfig dispatchConfig;
private final int size;
private final String clusterId;
private final ImmutableMap<Integer, Group> groups;
private final ImmutableMultimap<String, Node> nodesByHost;
private final ImmutableList<Group> orderedGroups;
private final ClusterMonitor<Node> clusterMonitor;
private final VipStatus vipStatus;
private PingFactory pingFactory;
/**
* A search node on this local machine having the entire corpus, which we therefore
* should prefer to dispatch directly to, or empty if there is no such local search node.
* If there is one, we also maintain the VIP status of this container based on the availability
* of the corpus on this local node (up + has coverage), such that this node is taken out of rotation
* if it only queries this cluster when the local node cannot be used, to avoid unnecessary
* cross-node network traffic.
*/
private final Optional<Node> directDispatchTarget;
public SearchCluster(String clusterId, DispatchConfig dispatchConfig, int containerClusterSize, VipStatus vipStatus) {
this.clusterId = clusterId;
this.dispatchConfig = dispatchConfig;
this.vipStatus = vipStatus;
List<Node> nodes = toNodes(dispatchConfig);
this.size = nodes.size();
ImmutableMap.Builder<Integer, Group> groupsBuilder = new ImmutableMap.Builder<>();
for (Map.Entry<Integer, List<Node>> group : nodes.stream().collect(Collectors.groupingBy(Node::group)).entrySet()) {
Group g = new Group(group.getKey(), group.getValue());
groupsBuilder.put(group.getKey(), g);
}
this.groups = groupsBuilder.build();
LinkedHashMap<Integer, Group> groupIntroductionOrder = new LinkedHashMap<>();
nodes.forEach(node -> groupIntroductionOrder.put(node.group(), groups.get(node.group)));
this.orderedGroups = ImmutableList.<Group>builder().addAll(groupIntroductionOrder.values()).build();
ImmutableMultimap.Builder<String, Node> nodesByHostBuilder = new ImmutableMultimap.Builder<>();
for (Node node : nodes)
nodesByHostBuilder.put(node.hostname(), node);
this.nodesByHost = nodesByHostBuilder.build();
this.directDispatchTarget = findDirectDispatchTarget(HostName.getLocalhost(), size, containerClusterSize,
nodesByHost, groups);
this.clusterMonitor = new ClusterMonitor<>(this);
}
public void startClusterMonitoring(PingFactory pingFactory) {
this.pingFactory = pingFactory;
for (var group : orderedGroups) {
for (var node : group.nodes()) {
working(node);
clusterMonitor.add(node, true);
}
}
}
private static Optional<Node> findDirectDispatchTarget(String selfHostname,
int searchClusterSize,
int containerClusterSize,
ImmutableMultimap<String, Node> nodesByHost,
ImmutableMap<Integer, Group> groups) {
ImmutableCollection<Node> localSearchNodes = nodesByHost.get(selfHostname);
if (localSearchNodes.size() != 1) return Optional.empty();
Node localSearchNode = localSearchNodes.iterator().next();
Group localSearchGroup = groups.get(localSearchNode.group());
if (localSearchGroup.nodes().size() != 1) return Optional.empty();
if (containerClusterSize < searchClusterSize) return Optional.empty();
return Optional.of(localSearchNode);
}
private static ImmutableList<Node> toNodes(DispatchConfig dispatchConfig) {
ImmutableList.Builder<Node> nodesBuilder = new ImmutableList.Builder<>();
Predicate<DispatchConfig.Node> filter;
if (dispatchConfig.useLocalNode()) {
final String hostName = HostName.getLocalhost();
filter = node -> node.host().equals(hostName);
} else {
filter = node -> true;
}
for (DispatchConfig.Node node : dispatchConfig.node()) {
if (filter.test(node)) {
nodesBuilder.add(new Node(node.key(), node.host(), node.fs4port(), node.group()));
}
}
return nodesBuilder.build();
}
public DispatchConfig dispatchConfig() {
return dispatchConfig;
}
/** Returns the number of nodes in this cluster (across all groups) */
public int size() { return size; }
/** Returns the groups of this cluster as an immutable map indexed by group id */
public ImmutableMap<Integer, Group> groups() { return groups; }
/** Returns the groups of this cluster as an immutable list in introduction order */
public ImmutableList<Group> orderedGroups() { return orderedGroups; }
/** Returns the n'th (zero-indexed) group in the cluster if possible */
public Optional<Group> group(int n) {
if (orderedGroups.size() > n) {
return Optional.of(orderedGroups.get(n));
} else {
return Optional.empty();
}
}
/** Returns the number of nodes per group - size()/groups.size() */
public int groupSize() {
if (groups.size() == 0) return size();
return size() / groups.size();
}
public int groupsWithSufficientCoverage() {
int covered = 0;
for (Group g : orderedGroups) {
if (g.hasSufficientCoverage()) {
covered++;
}
}
return covered;
}
/**
* Returns the recipient we should dispatch queries directly to (bypassing fdispatch),
* or empty if we should not dispatch directly.
*/
public Optional<Node> directDispatchTarget() {
if ( directDispatchTarget.isEmpty()) return Optional.empty();
Group localSearchGroup = groups.get(directDispatchTarget.get().group());
if ( ! localSearchGroup.hasSufficientCoverage()) return Optional.empty();
if ( ! directDispatchTarget.get().isWorking()) return Optional.empty();
return directDispatchTarget;
}
/** Used by the cluster monitor to manage node status */
@Override
public void working(Node node) {
node.setWorking(true);
if (usesDirectDispatchTo(node))
vipStatus.addToRotation(clusterId);
}
/** Used by the cluster monitor to manage node status */
@Override
public void failed(Node node) {
node.setWorking(false);
if (usesDirectDispatchTo(node))
vipStatus.removeFromRotation(clusterId);
}
private boolean usesDirectDispatchTo(Node node) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().equals(node);
}
private boolean usesDirectDispatchTo(Group group) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().group() == group.id();
}
/** Used by the cluster monitor to manage node status */
@Override
public void ping(Node node, Executor executor) {
if (pingFactory == null)
return;
FutureTask<Pong> futurePong = new FutureTask<>(pingFactory.createPinger(node, clusterMonitor));
executor.execute(futurePong);
Pong pong = getPong(futurePong, node);
futurePong.cancel(true);
if (pong.badResponse()) {
clusterMonitor.failed(node, pong.getError(0));
} else {
if (pong.activeDocuments().isPresent()) {
node.setActiveDocuments(pong.activeDocuments().get());
}
clusterMonitor.responded(node);
}
}
/**
* Update statistics after a round of issuing pings.
* Note that this doesn't wait for pings to return, so it will typically accumulate data from
* last rounds pinging, or potentially (although unlikely) some combination of new and old data.
*/
@Override
public void pingIterationCompleted() {
int numGroups = orderedGroups.size();
if (numGroups == 1) {
Group group = groups.values().iterator().next();
group.aggregateActiveDocuments();
updateSufficientCoverage(group, true);
boolean fullCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), group.getActiveDocuments(),
group.getActiveDocuments());
trackGroupCoverageChanges(0, group, fullCoverage, group.getActiveDocuments());
return;
}
long[] activeDocumentsInGroup = new long[numGroups];
long sumOfActiveDocuments = 0;
for(int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
group.aggregateActiveDocuments();
activeDocumentsInGroup[i] = group.getActiveDocuments();
sumOfActiveDocuments += activeDocumentsInGroup[i];
}
boolean anyGroupsSufficientCoverage = false;
for (int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
long activeDocuments = activeDocumentsInGroup[i];
long averageDocumentsInOtherGroups = (sumOfActiveDocuments - activeDocuments) / (numGroups - 1);
boolean sufficientCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), activeDocuments, averageDocumentsInOtherGroups);
anyGroupsSufficientCoverage = anyGroupsSufficientCoverage || sufficientCoverage;
updateSufficientCoverage(group, sufficientCoverage);
trackGroupCoverageChanges(i, group, sufficientCoverage, averageDocumentsInOtherGroups);
}
if ( ! anyGroupsSufficientCoverage && (sumOfActiveDocuments == 0)) {
vipStatus.removeFromRotation(clusterId);
}
}
private boolean isGroupCoverageSufficient(int workingNodes, int nodesInGroup, long activeDocuments, long averageDocumentsInOtherGroups) {
boolean sufficientCoverage = true;
if (averageDocumentsInOtherGroups > 0) {
double coverage = 100.0 * (double) activeDocuments / averageDocumentsInOtherGroups;
sufficientCoverage = coverage >= dispatchConfig.minActivedocsPercentage();
}
if (sufficientCoverage) {
sufficientCoverage = isGroupNodeCoverageSufficient(workingNodes, nodesInGroup);
}
return sufficientCoverage;
}
private boolean isGroupNodeCoverageSufficient(int workingNodes, int nodesInGroup) {
int nodesAllowedDown = dispatchConfig.maxNodesDownPerGroup()
+ (int) (((double) nodesInGroup * (100.0 - dispatchConfig.minGroupCoverage())) / 100.0);
return workingNodes + nodesAllowedDown >= nodesInGroup;
}
private Pong getPong(FutureTask<Pong> futurePong, Node node) {
try {
return futurePong.get(clusterMonitor.getConfiguration().getFailLimit(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Ping was interrupted: " + node));
} catch (ExecutionException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Execution was interrupted: " + node));
} catch (TimeoutException e) {
return new Pong(ErrorMessage.createNoAnswerWhenPingingNode("Ping thread timed out"));
}
}
/**
* Calculate whether a subset of nodes in a group has enough coverage
*/
public boolean isPartialGroupCoverageSufficient(OptionalInt knownGroupId, List<Node> nodes) {
if (orderedGroups.size() == 1) {
boolean sufficient = nodes.size() >= groupSize() - dispatchConfig.maxNodesDownPerGroup();
return sufficient;
}
if (knownGroupId.isEmpty()) {
return false;
}
int groupId = knownGroupId.getAsInt();
Group group = groups.get(groupId);
if (group == null) {
return false;
}
int nodesInGroup = group.nodes().size();
long sumOfActiveDocuments = 0;
int otherGroups = 0;
for (Group g : orderedGroups) {
if (g.id() != groupId) {
sumOfActiveDocuments += g.getActiveDocuments();
otherGroups++;
}
}
long activeDocuments = 0;
for (Node n : nodes) {
activeDocuments += n.getActiveDocuments();
}
long averageDocumentsInOtherGroups = sumOfActiveDocuments / otherGroups;
boolean sufficient = isGroupCoverageSufficient(nodes.size(), nodesInGroup, activeDocuments, averageDocumentsInOtherGroups);
return sufficient;
}
private void trackGroupCoverageChanges(int index, Group group, boolean fullCoverage, long averageDocuments) {
boolean changed = group.isFullCoverageStatusChanged(fullCoverage);
if (changed) {
int requiredNodes = groupSize() - dispatchConfig.maxNodesDownPerGroup();
if (fullCoverage) {
log.info(() -> String.format("Group %d is now good again (%d/%d active docs, coverage %d/%d)", index,
group.getActiveDocuments(), averageDocuments, group.workingNodes(), groupSize()));
} else {
log.warning(() -> String.format("Coverage of group %d is only %d/%d (requires %d)", index, group.workingNodes(), groupSize(),
requiredNodes));
}
}
}
} | class SearchCluster implements NodeManager<Node> {
private static final Logger log = Logger.getLogger(SearchCluster.class.getName());
private final DispatchConfig dispatchConfig;
private final int size;
private final String clusterId;
private final ImmutableMap<Integer, Group> groups;
private final ImmutableMultimap<String, Node> nodesByHost;
private final ImmutableList<Group> orderedGroups;
private final ClusterMonitor<Node> clusterMonitor;
private final VipStatus vipStatus;
private PingFactory pingFactory;
/**
* A search node on this local machine having the entire corpus, which we therefore
* should prefer to dispatch directly to, or empty if there is no such local search node.
* If there is one, we also maintain the VIP status of this container based on the availability
* of the corpus on this local node (up + has coverage), such that this node is taken out of rotation
* if it only queries this cluster when the local node cannot be used, to avoid unnecessary
* cross-node network traffic.
*/
private final Optional<Node> directDispatchTarget;
public SearchCluster(String clusterId, DispatchConfig dispatchConfig, int containerClusterSize, VipStatus vipStatus) {
this.clusterId = clusterId;
this.dispatchConfig = dispatchConfig;
this.vipStatus = vipStatus;
List<Node> nodes = toNodes(dispatchConfig);
this.size = nodes.size();
ImmutableMap.Builder<Integer, Group> groupsBuilder = new ImmutableMap.Builder<>();
for (Map.Entry<Integer, List<Node>> group : nodes.stream().collect(Collectors.groupingBy(Node::group)).entrySet()) {
Group g = new Group(group.getKey(), group.getValue());
groupsBuilder.put(group.getKey(), g);
}
this.groups = groupsBuilder.build();
LinkedHashMap<Integer, Group> groupIntroductionOrder = new LinkedHashMap<>();
nodes.forEach(node -> groupIntroductionOrder.put(node.group(), groups.get(node.group)));
this.orderedGroups = ImmutableList.<Group>builder().addAll(groupIntroductionOrder.values()).build();
ImmutableMultimap.Builder<String, Node> nodesByHostBuilder = new ImmutableMultimap.Builder<>();
for (Node node : nodes)
nodesByHostBuilder.put(node.hostname(), node);
this.nodesByHost = nodesByHostBuilder.build();
this.directDispatchTarget = findDirectDispatchTarget(HostName.getLocalhost(), size, containerClusterSize,
nodesByHost, groups);
this.clusterMonitor = new ClusterMonitor<>(this);
}
public void startClusterMonitoring(PingFactory pingFactory) {
this.pingFactory = pingFactory;
for (var group : orderedGroups) {
for (var node : group.nodes()) {
working(node);
clusterMonitor.add(node, true);
}
}
}
private static Optional<Node> findDirectDispatchTarget(String selfHostname,
int searchClusterSize,
int containerClusterSize,
ImmutableMultimap<String, Node> nodesByHost,
ImmutableMap<Integer, Group> groups) {
ImmutableCollection<Node> localSearchNodes = nodesByHost.get(selfHostname);
if (localSearchNodes.size() != 1) return Optional.empty();
Node localSearchNode = localSearchNodes.iterator().next();
Group localSearchGroup = groups.get(localSearchNode.group());
if (localSearchGroup.nodes().size() != 1) return Optional.empty();
if (containerClusterSize < searchClusterSize) return Optional.empty();
return Optional.of(localSearchNode);
}
private static ImmutableList<Node> toNodes(DispatchConfig dispatchConfig) {
ImmutableList.Builder<Node> nodesBuilder = new ImmutableList.Builder<>();
Predicate<DispatchConfig.Node> filter;
if (dispatchConfig.useLocalNode()) {
final String hostName = HostName.getLocalhost();
filter = node -> node.host().equals(hostName);
} else {
filter = node -> true;
}
for (DispatchConfig.Node node : dispatchConfig.node()) {
if (filter.test(node)) {
nodesBuilder.add(new Node(node.key(), node.host(), node.fs4port(), node.group()));
}
}
return nodesBuilder.build();
}
public DispatchConfig dispatchConfig() {
return dispatchConfig;
}
/** Returns the number of nodes in this cluster (across all groups) */
public int size() { return size; }
/** Returns the groups of this cluster as an immutable map indexed by group id */
public ImmutableMap<Integer, Group> groups() { return groups; }
/** Returns the groups of this cluster as an immutable list in introduction order */
public ImmutableList<Group> orderedGroups() { return orderedGroups; }
/** Returns the n'th (zero-indexed) group in the cluster if possible */
public Optional<Group> group(int n) {
if (orderedGroups.size() > n) {
return Optional.of(orderedGroups.get(n));
} else {
return Optional.empty();
}
}
/** Returns the number of nodes per group - size()/groups.size() */
public int groupSize() {
if (groups.size() == 0) return size();
return size() / groups.size();
}
public int groupsWithSufficientCoverage() {
int covered = 0;
for (Group g : orderedGroups) {
if (g.hasSufficientCoverage()) {
covered++;
}
}
return covered;
}
/**
* Returns the recipient we should dispatch queries directly to (bypassing fdispatch),
* or empty if we should not dispatch directly.
*/
public Optional<Node> directDispatchTarget() {
if ( directDispatchTarget.isEmpty()) return Optional.empty();
Group localSearchGroup = groups.get(directDispatchTarget.get().group());
if ( ! localSearchGroup.hasSufficientCoverage()) return Optional.empty();
if ( ! directDispatchTarget.get().isWorking()) return Optional.empty();
return directDispatchTarget;
}
/** Used by the cluster monitor to manage node status */
@Override
public void working(Node node) {
node.setWorking(true);
if (usesDirectDispatchTo(node))
vipStatus.addToRotation(clusterId);
}
/** Used by the cluster monitor to manage node status */
@Override
public void failed(Node node) {
node.setWorking(false);
if (usesDirectDispatchTo(node))
vipStatus.removeFromRotation(clusterId);
}
private boolean usesDirectDispatchTo(Node node) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().equals(node);
}
private boolean usesDirectDispatchTo(Group group) {
return directDispatchTarget.isPresent() && directDispatchTarget.get().group() == group.id();
}
/** Used by the cluster monitor to manage node status */
@Override
public void ping(Node node, Executor executor) {
if (pingFactory == null)
return;
FutureTask<Pong> futurePong = new FutureTask<>(pingFactory.createPinger(node, clusterMonitor));
executor.execute(futurePong);
Pong pong = getPong(futurePong, node);
futurePong.cancel(true);
if (pong.badResponse()) {
clusterMonitor.failed(node, pong.getError(0));
} else {
if (pong.activeDocuments().isPresent()) {
node.setActiveDocuments(pong.activeDocuments().get());
}
clusterMonitor.responded(node);
}
}
/**
* Update statistics after a round of issuing pings.
* Note that this doesn't wait for pings to return, so it will typically accumulate data from
* last rounds pinging, or potentially (although unlikely) some combination of new and old data.
*/
@Override
public void pingIterationCompleted() {
int numGroups = orderedGroups.size();
if (numGroups == 1) {
Group group = groups.values().iterator().next();
group.aggregateActiveDocuments();
updateSufficientCoverage(group, true);
boolean fullCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), group.getActiveDocuments(),
group.getActiveDocuments());
trackGroupCoverageChanges(0, group, fullCoverage, group.getActiveDocuments());
return;
}
long[] activeDocumentsInGroup = new long[numGroups];
long sumOfActiveDocuments = 0;
for(int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
group.aggregateActiveDocuments();
activeDocumentsInGroup[i] = group.getActiveDocuments();
sumOfActiveDocuments += activeDocumentsInGroup[i];
}
boolean anyGroupsSufficientCoverage = false;
for (int i = 0; i < numGroups; i++) {
Group group = orderedGroups.get(i);
long activeDocuments = activeDocumentsInGroup[i];
long averageDocumentsInOtherGroups = (sumOfActiveDocuments - activeDocuments) / (numGroups - 1);
boolean sufficientCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), activeDocuments, averageDocumentsInOtherGroups);
anyGroupsSufficientCoverage = anyGroupsSufficientCoverage || sufficientCoverage;
updateSufficientCoverage(group, sufficientCoverage);
trackGroupCoverageChanges(i, group, sufficientCoverage, averageDocumentsInOtherGroups);
}
if ( ! anyGroupsSufficientCoverage && (sumOfActiveDocuments == 0)) {
vipStatus.removeFromRotation(clusterId);
}
}
private boolean isGroupCoverageSufficient(int workingNodes, int nodesInGroup, long activeDocuments, long averageDocumentsInOtherGroups) {
boolean sufficientCoverage = true;
if (averageDocumentsInOtherGroups > 0) {
double coverage = 100.0 * (double) activeDocuments / averageDocumentsInOtherGroups;
sufficientCoverage = coverage >= dispatchConfig.minActivedocsPercentage();
}
if (sufficientCoverage) {
sufficientCoverage = isGroupNodeCoverageSufficient(workingNodes, nodesInGroup);
}
return sufficientCoverage;
}
private boolean isGroupNodeCoverageSufficient(int workingNodes, int nodesInGroup) {
int nodesAllowedDown = dispatchConfig.maxNodesDownPerGroup()
+ (int) (((double) nodesInGroup * (100.0 - dispatchConfig.minGroupCoverage())) / 100.0);
return workingNodes + nodesAllowedDown >= nodesInGroup;
}
private Pong getPong(FutureTask<Pong> futurePong, Node node) {
try {
return futurePong.get(clusterMonitor.getConfiguration().getFailLimit(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Ping was interrupted: " + node));
} catch (ExecutionException e) {
log.log(Level.WARNING, "Exception pinging " + node, e);
return new Pong(ErrorMessage.createUnspecifiedError("Execution was interrupted: " + node));
} catch (TimeoutException e) {
return new Pong(ErrorMessage.createNoAnswerWhenPingingNode("Ping thread timed out"));
}
}
/**
* Calculate whether a subset of nodes in a group has enough coverage
*/
public boolean isPartialGroupCoverageSufficient(OptionalInt knownGroupId, List<Node> nodes) {
if (orderedGroups.size() == 1) {
boolean sufficient = nodes.size() >= groupSize() - dispatchConfig.maxNodesDownPerGroup();
return sufficient;
}
if (knownGroupId.isEmpty()) {
return false;
}
int groupId = knownGroupId.getAsInt();
Group group = groups.get(groupId);
if (group == null) {
return false;
}
int nodesInGroup = group.nodes().size();
long sumOfActiveDocuments = 0;
int otherGroups = 0;
for (Group g : orderedGroups) {
if (g.id() != groupId) {
sumOfActiveDocuments += g.getActiveDocuments();
otherGroups++;
}
}
long activeDocuments = 0;
for (Node n : nodes) {
activeDocuments += n.getActiveDocuments();
}
long averageDocumentsInOtherGroups = sumOfActiveDocuments / otherGroups;
boolean sufficient = isGroupCoverageSufficient(nodes.size(), nodesInGroup, activeDocuments, averageDocumentsInOtherGroups);
return sufficient;
}
private void trackGroupCoverageChanges(int index, Group group, boolean fullCoverage, long averageDocuments) {
boolean changed = group.isFullCoverageStatusChanged(fullCoverage);
if (changed) {
int requiredNodes = groupSize() - dispatchConfig.maxNodesDownPerGroup();
if (fullCoverage) {
log.info(() -> String.format("Group %d is now good again (%d/%d active docs, coverage %d/%d)", index,
group.getActiveDocuments(), averageDocuments, group.workingNodes(), groupSize()));
} else {
log.warning(() -> String.format("Coverage of group %d is only %d/%d (requires %d)", index, group.workingNodes(), groupSize(),
requiredNodes));
}
}
}
} |
Copy active state from `oldTarget` if present? | public void setTarget(NodeType nodeType, Version newTarget, boolean force) {
require(nodeType);
if (newTarget.isEmpty()) {
throw new IllegalArgumentException("Invalid target version: " + newTarget.toFullString());
}
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
Optional<OsVersion> oldTarget = Optional.ofNullable(osVersions.get(nodeType));
if (oldTarget.filter(v -> v.version().equals(newTarget)).isPresent()) {
return;
}
if (!force && oldTarget.filter(v -> v.version().isAfter(newTarget)).isPresent()) {
throw new IllegalArgumentException("Cannot set target OS version to " + newTarget +
" without setting 'force', as it's lower than the current version: "
+ oldTarget.get().version());
}
osVersions.put(nodeType, new OsVersion(newTarget, false));
db.writeOsVersions(osVersions);
createCache();
log.info("Set OS target version for " + nodeType + " nodes to " + newTarget.toFullString());
}
} | osVersions.put(nodeType, new OsVersion(newTarget, false)); | public void setTarget(NodeType nodeType, Version newTarget, boolean force) {
require(nodeType);
if (newTarget.isEmpty()) {
throw new IllegalArgumentException("Invalid target version: " + newTarget.toFullString());
}
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
Optional<OsVersion> oldTarget = Optional.ofNullable(osVersions.get(nodeType));
if (oldTarget.filter(v -> v.version().equals(newTarget)).isPresent()) {
return;
}
if (!force && oldTarget.filter(v -> v.version().isAfter(newTarget)).isPresent()) {
throw new IllegalArgumentException("Cannot set target OS version to " + newTarget +
" without setting 'force', as it's lower than the current version: "
+ oldTarget.get().version());
}
osVersions.put(nodeType, new OsVersion(newTarget, false));
db.writeOsVersions(osVersions);
createCache();
log.info("Set OS target version for " + nodeType + " nodes to " + newTarget.toFullString());
}
} | class OsVersions {
private static final Duration defaultCacheTtl = Duration.ofMinutes(1);
private static final Logger log = Logger.getLogger(OsVersions.class.getName());
private final CuratorDatabaseClient db;
private final Duration cacheTtl;
/**
* Target OS version is read on every request to /nodes/v2/node/[fqdn]. Cache current targets to avoid
* unnecessary ZK reads. When targets change, some nodes may need to wait for TTL until they see the new target,
* this is fine.
*/
private volatile Supplier<Map<NodeType, OsVersion>> currentTargets;
public OsVersions(CuratorDatabaseClient db) {
this(db, defaultCacheTtl);
}
OsVersions(CuratorDatabaseClient db, Duration cacheTtl) {
this.db = db;
this.cacheTtl = cacheTtl;
createCache();
try (var lock = db.lockOsVersions()) {
db.writeOsVersions(db.readOsVersions());
}
}
private void createCache() {
this.currentTargets = Suppliers.memoizeWithExpiration(() -> ImmutableMap.copyOf(db.readOsVersions()),
cacheTtl.toMillis(), TimeUnit.MILLISECONDS);
}
/** Returns the current target versions for each node type */
public Map<NodeType, OsVersion> targets() {
return currentTargets.get();
}
/** Returns the current target version for given node type, if any */
public Optional<OsVersion> targetFor(NodeType type) {
return Optional.ofNullable(targets().get(type));
}
/** Remove OS target for given node type. Nodes of this type will stop receiving wanted OS version in their
* node object */
public void removeTarget(NodeType nodeType) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
osVersions.remove(nodeType);
db.writeOsVersions(osVersions);
createCache();
log.info("Cleared OS target version for " + nodeType);
}
}
/** Set the target OS version for nodes of given type */
/** Activate or deactivate target for given node type. This is used for resuming or pausing an OS upgrade. */
public void setActive(NodeType nodeType, boolean active) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
var osVersions = db.readOsVersions();
var currentVersion = osVersions.get(nodeType);
if (currentVersion == null) return;
if (currentVersion.active() == active) return;
osVersions.put(nodeType, new OsVersion(currentVersion.version(), active));
db.writeOsVersions(osVersions);
createCache();
log.info((active ? "Activated" : "Deactivated") + " OS target version for " + nodeType + " nodes");
}
}
private static void require(NodeType nodeType) {
if (!nodeType.isDockerHost()) {
throw new IllegalArgumentException("Node type '" + nodeType + "' does not support OS upgrades");
}
}
} | class OsVersions {
private static final Duration defaultCacheTtl = Duration.ofMinutes(1);
private static final Logger log = Logger.getLogger(OsVersions.class.getName());
private final CuratorDatabaseClient db;
private final Duration cacheTtl;
/**
* Target OS version is read on every request to /nodes/v2/node/[fqdn]. Cache current targets to avoid
* unnecessary ZK reads. When targets change, some nodes may need to wait for TTL until they see the new target,
* this is fine.
*/
private volatile Supplier<Map<NodeType, OsVersion>> currentTargets;
public OsVersions(CuratorDatabaseClient db) {
this(db, defaultCacheTtl);
}
OsVersions(CuratorDatabaseClient db, Duration cacheTtl) {
this.db = db;
this.cacheTtl = cacheTtl;
createCache();
try (var lock = db.lockOsVersions()) {
db.writeOsVersions(db.readOsVersions());
}
}
private void createCache() {
this.currentTargets = Suppliers.memoizeWithExpiration(() -> ImmutableMap.copyOf(db.readOsVersions()),
cacheTtl.toMillis(), TimeUnit.MILLISECONDS);
}
/** Returns the current target versions for each node type */
public Map<NodeType, OsVersion> targets() {
return currentTargets.get();
}
/** Returns the current target version for given node type, if any */
public Optional<OsVersion> targetFor(NodeType type) {
return Optional.ofNullable(targets().get(type));
}
/** Remove OS target for given node type. Nodes of this type will stop receiving wanted OS version in their
* node object */
public void removeTarget(NodeType nodeType) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
osVersions.remove(nodeType);
db.writeOsVersions(osVersions);
createCache();
log.info("Cleared OS target version for " + nodeType);
}
}
/** Set the target OS version for nodes of given type */
/** Activate or deactivate target for given node type. This is used for resuming or pausing an OS upgrade. */
public void setActive(NodeType nodeType, boolean active) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
var osVersions = db.readOsVersions();
var currentVersion = osVersions.get(nodeType);
if (currentVersion == null) return;
if (currentVersion.active() == active) return;
osVersions.put(nodeType, new OsVersion(currentVersion.version(), active));
db.writeOsVersions(osVersions);
createCache();
log.info((active ? "Activated" : "Deactivated") + " OS target version for " + nodeType + " nodes");
}
}
private static void require(NodeType nodeType) {
if (!nodeType.isDockerHost()) {
throw new IllegalArgumentException("Node type '" + nodeType + "' does not support OS upgrades");
}
}
} |
Setting the same version is a no-op (checked earlier in this method), but I can add a test for this case. | public void setTarget(NodeType nodeType, Version newTarget, boolean force) {
require(nodeType);
if (newTarget.isEmpty()) {
throw new IllegalArgumentException("Invalid target version: " + newTarget.toFullString());
}
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
Optional<OsVersion> oldTarget = Optional.ofNullable(osVersions.get(nodeType));
if (oldTarget.filter(v -> v.version().equals(newTarget)).isPresent()) {
return;
}
if (!force && oldTarget.filter(v -> v.version().isAfter(newTarget)).isPresent()) {
throw new IllegalArgumentException("Cannot set target OS version to " + newTarget +
" without setting 'force', as it's lower than the current version: "
+ oldTarget.get().version());
}
osVersions.put(nodeType, new OsVersion(newTarget, false));
db.writeOsVersions(osVersions);
createCache();
log.info("Set OS target version for " + nodeType + " nodes to " + newTarget.toFullString());
}
} | osVersions.put(nodeType, new OsVersion(newTarget, false)); | public void setTarget(NodeType nodeType, Version newTarget, boolean force) {
require(nodeType);
if (newTarget.isEmpty()) {
throw new IllegalArgumentException("Invalid target version: " + newTarget.toFullString());
}
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
Optional<OsVersion> oldTarget = Optional.ofNullable(osVersions.get(nodeType));
if (oldTarget.filter(v -> v.version().equals(newTarget)).isPresent()) {
return;
}
if (!force && oldTarget.filter(v -> v.version().isAfter(newTarget)).isPresent()) {
throw new IllegalArgumentException("Cannot set target OS version to " + newTarget +
" without setting 'force', as it's lower than the current version: "
+ oldTarget.get().version());
}
osVersions.put(nodeType, new OsVersion(newTarget, false));
db.writeOsVersions(osVersions);
createCache();
log.info("Set OS target version for " + nodeType + " nodes to " + newTarget.toFullString());
}
} | class OsVersions {
private static final Duration defaultCacheTtl = Duration.ofMinutes(1);
private static final Logger log = Logger.getLogger(OsVersions.class.getName());
private final CuratorDatabaseClient db;
private final Duration cacheTtl;
/**
* Target OS version is read on every request to /nodes/v2/node/[fqdn]. Cache current targets to avoid
* unnecessary ZK reads. When targets change, some nodes may need to wait for TTL until they see the new target,
* this is fine.
*/
private volatile Supplier<Map<NodeType, OsVersion>> currentTargets;
public OsVersions(CuratorDatabaseClient db) {
this(db, defaultCacheTtl);
}
OsVersions(CuratorDatabaseClient db, Duration cacheTtl) {
this.db = db;
this.cacheTtl = cacheTtl;
createCache();
try (var lock = db.lockOsVersions()) {
db.writeOsVersions(db.readOsVersions());
}
}
private void createCache() {
this.currentTargets = Suppliers.memoizeWithExpiration(() -> ImmutableMap.copyOf(db.readOsVersions()),
cacheTtl.toMillis(), TimeUnit.MILLISECONDS);
}
/** Returns the current target versions for each node type */
public Map<NodeType, OsVersion> targets() {
return currentTargets.get();
}
/** Returns the current target version for given node type, if any */
public Optional<OsVersion> targetFor(NodeType type) {
return Optional.ofNullable(targets().get(type));
}
/** Remove OS target for given node type. Nodes of this type will stop receiving wanted OS version in their
* node object */
public void removeTarget(NodeType nodeType) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
osVersions.remove(nodeType);
db.writeOsVersions(osVersions);
createCache();
log.info("Cleared OS target version for " + nodeType);
}
}
/** Set the target OS version for nodes of given type */
/** Activate or deactivate target for given node type. This is used for resuming or pausing an OS upgrade. */
public void setActive(NodeType nodeType, boolean active) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
var osVersions = db.readOsVersions();
var currentVersion = osVersions.get(nodeType);
if (currentVersion == null) return;
if (currentVersion.active() == active) return;
osVersions.put(nodeType, new OsVersion(currentVersion.version(), active));
db.writeOsVersions(osVersions);
createCache();
log.info((active ? "Activated" : "Deactivated") + " OS target version for " + nodeType + " nodes");
}
}
private static void require(NodeType nodeType) {
if (!nodeType.isDockerHost()) {
throw new IllegalArgumentException("Node type '" + nodeType + "' does not support OS upgrades");
}
}
} | class OsVersions {
private static final Duration defaultCacheTtl = Duration.ofMinutes(1);
private static final Logger log = Logger.getLogger(OsVersions.class.getName());
private final CuratorDatabaseClient db;
private final Duration cacheTtl;
/**
* Target OS version is read on every request to /nodes/v2/node/[fqdn]. Cache current targets to avoid
* unnecessary ZK reads. When targets change, some nodes may need to wait for TTL until they see the new target,
* this is fine.
*/
private volatile Supplier<Map<NodeType, OsVersion>> currentTargets;
public OsVersions(CuratorDatabaseClient db) {
this(db, defaultCacheTtl);
}
OsVersions(CuratorDatabaseClient db, Duration cacheTtl) {
this.db = db;
this.cacheTtl = cacheTtl;
createCache();
try (var lock = db.lockOsVersions()) {
db.writeOsVersions(db.readOsVersions());
}
}
private void createCache() {
this.currentTargets = Suppliers.memoizeWithExpiration(() -> ImmutableMap.copyOf(db.readOsVersions()),
cacheTtl.toMillis(), TimeUnit.MILLISECONDS);
}
/** Returns the current target versions for each node type */
public Map<NodeType, OsVersion> targets() {
return currentTargets.get();
}
/** Returns the current target version for given node type, if any */
public Optional<OsVersion> targetFor(NodeType type) {
return Optional.ofNullable(targets().get(type));
}
/** Remove OS target for given node type. Nodes of this type will stop receiving wanted OS version in their
* node object */
public void removeTarget(NodeType nodeType) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
osVersions.remove(nodeType);
db.writeOsVersions(osVersions);
createCache();
log.info("Cleared OS target version for " + nodeType);
}
}
/** Set the target OS version for nodes of given type */
/** Activate or deactivate target for given node type. This is used for resuming or pausing an OS upgrade. */
public void setActive(NodeType nodeType, boolean active) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
var osVersions = db.readOsVersions();
var currentVersion = osVersions.get(nodeType);
if (currentVersion == null) return;
if (currentVersion.active() == active) return;
osVersions.put(nodeType, new OsVersion(currentVersion.version(), active));
db.writeOsVersions(osVersions);
createCache();
log.info((active ? "Activated" : "Deactivated") + " OS target version for " + nodeType + " nodes");
}
}
private static void require(NodeType nodeType) {
if (!nodeType.isDockerHost()) {
throw new IllegalArgumentException("Node type '" + nodeType + "' does not support OS upgrades");
}
}
} |
I meant to copy the active state, not the version? I.e. if we were upgrading to X and it was `active`, then upgrading to `y` should also be `active`? No need to set to false and wait for the next iteration of the maintainer to set back to `active`? | public void setTarget(NodeType nodeType, Version newTarget, boolean force) {
require(nodeType);
if (newTarget.isEmpty()) {
throw new IllegalArgumentException("Invalid target version: " + newTarget.toFullString());
}
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
Optional<OsVersion> oldTarget = Optional.ofNullable(osVersions.get(nodeType));
if (oldTarget.filter(v -> v.version().equals(newTarget)).isPresent()) {
return;
}
if (!force && oldTarget.filter(v -> v.version().isAfter(newTarget)).isPresent()) {
throw new IllegalArgumentException("Cannot set target OS version to " + newTarget +
" without setting 'force', as it's lower than the current version: "
+ oldTarget.get().version());
}
osVersions.put(nodeType, new OsVersion(newTarget, false));
db.writeOsVersions(osVersions);
createCache();
log.info("Set OS target version for " + nodeType + " nodes to " + newTarget.toFullString());
}
} | osVersions.put(nodeType, new OsVersion(newTarget, false)); | public void setTarget(NodeType nodeType, Version newTarget, boolean force) {
require(nodeType);
if (newTarget.isEmpty()) {
throw new IllegalArgumentException("Invalid target version: " + newTarget.toFullString());
}
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
Optional<OsVersion> oldTarget = Optional.ofNullable(osVersions.get(nodeType));
if (oldTarget.filter(v -> v.version().equals(newTarget)).isPresent()) {
return;
}
if (!force && oldTarget.filter(v -> v.version().isAfter(newTarget)).isPresent()) {
throw new IllegalArgumentException("Cannot set target OS version to " + newTarget +
" without setting 'force', as it's lower than the current version: "
+ oldTarget.get().version());
}
osVersions.put(nodeType, new OsVersion(newTarget, false));
db.writeOsVersions(osVersions);
createCache();
log.info("Set OS target version for " + nodeType + " nodes to " + newTarget.toFullString());
}
} | class OsVersions {
private static final Duration defaultCacheTtl = Duration.ofMinutes(1);
private static final Logger log = Logger.getLogger(OsVersions.class.getName());
private final CuratorDatabaseClient db;
private final Duration cacheTtl;
/**
* Target OS version is read on every request to /nodes/v2/node/[fqdn]. Cache current targets to avoid
* unnecessary ZK reads. When targets change, some nodes may need to wait for TTL until they see the new target,
* this is fine.
*/
private volatile Supplier<Map<NodeType, OsVersion>> currentTargets;
public OsVersions(CuratorDatabaseClient db) {
this(db, defaultCacheTtl);
}
OsVersions(CuratorDatabaseClient db, Duration cacheTtl) {
this.db = db;
this.cacheTtl = cacheTtl;
createCache();
try (var lock = db.lockOsVersions()) {
db.writeOsVersions(db.readOsVersions());
}
}
private void createCache() {
this.currentTargets = Suppliers.memoizeWithExpiration(() -> ImmutableMap.copyOf(db.readOsVersions()),
cacheTtl.toMillis(), TimeUnit.MILLISECONDS);
}
/** Returns the current target versions for each node type */
public Map<NodeType, OsVersion> targets() {
return currentTargets.get();
}
/** Returns the current target version for given node type, if any */
public Optional<OsVersion> targetFor(NodeType type) {
return Optional.ofNullable(targets().get(type));
}
/** Remove OS target for given node type. Nodes of this type will stop receiving wanted OS version in their
* node object */
public void removeTarget(NodeType nodeType) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
osVersions.remove(nodeType);
db.writeOsVersions(osVersions);
createCache();
log.info("Cleared OS target version for " + nodeType);
}
}
/** Set the target OS version for nodes of given type */
/** Activate or deactivate target for given node type. This is used for resuming or pausing an OS upgrade. */
public void setActive(NodeType nodeType, boolean active) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
var osVersions = db.readOsVersions();
var currentVersion = osVersions.get(nodeType);
if (currentVersion == null) return;
if (currentVersion.active() == active) return;
osVersions.put(nodeType, new OsVersion(currentVersion.version(), active));
db.writeOsVersions(osVersions);
createCache();
log.info((active ? "Activated" : "Deactivated") + " OS target version for " + nodeType + " nodes");
}
}
private static void require(NodeType nodeType) {
if (!nodeType.isDockerHost()) {
throw new IllegalArgumentException("Node type '" + nodeType + "' does not support OS upgrades");
}
}
} | class OsVersions {
private static final Duration defaultCacheTtl = Duration.ofMinutes(1);
private static final Logger log = Logger.getLogger(OsVersions.class.getName());
private final CuratorDatabaseClient db;
private final Duration cacheTtl;
/**
* Target OS version is read on every request to /nodes/v2/node/[fqdn]. Cache current targets to avoid
* unnecessary ZK reads. When targets change, some nodes may need to wait for TTL until they see the new target,
* this is fine.
*/
private volatile Supplier<Map<NodeType, OsVersion>> currentTargets;
public OsVersions(CuratorDatabaseClient db) {
this(db, defaultCacheTtl);
}
OsVersions(CuratorDatabaseClient db, Duration cacheTtl) {
this.db = db;
this.cacheTtl = cacheTtl;
createCache();
try (var lock = db.lockOsVersions()) {
db.writeOsVersions(db.readOsVersions());
}
}
private void createCache() {
this.currentTargets = Suppliers.memoizeWithExpiration(() -> ImmutableMap.copyOf(db.readOsVersions()),
cacheTtl.toMillis(), TimeUnit.MILLISECONDS);
}
/** Returns the current target versions for each node type */
public Map<NodeType, OsVersion> targets() {
return currentTargets.get();
}
/** Returns the current target version for given node type, if any */
public Optional<OsVersion> targetFor(NodeType type) {
return Optional.ofNullable(targets().get(type));
}
/** Remove OS target for given node type. Nodes of this type will stop receiving wanted OS version in their
* node object */
public void removeTarget(NodeType nodeType) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
osVersions.remove(nodeType);
db.writeOsVersions(osVersions);
createCache();
log.info("Cleared OS target version for " + nodeType);
}
}
/** Set the target OS version for nodes of given type */
/** Activate or deactivate target for given node type. This is used for resuming or pausing an OS upgrade. */
public void setActive(NodeType nodeType, boolean active) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
var osVersions = db.readOsVersions();
var currentVersion = osVersions.get(nodeType);
if (currentVersion == null) return;
if (currentVersion.active() == active) return;
osVersions.put(nodeType, new OsVersion(currentVersion.version(), active));
db.writeOsVersions(osVersions);
createCache();
log.info((active ? "Activated" : "Deactivated") + " OS target version for " + nodeType + " nodes");
}
}
private static void require(NodeType nodeType) {
if (!nodeType.isDockerHost()) {
throw new IllegalArgumentException("Node type '" + nodeType + "' does not support OS upgrades");
}
}
} |
```suggestion osVersions.put(nodeType, new OsVersion(newTarget, oldTarget.map(OsVersion::active).orElse(false))); ``` | public void setTarget(NodeType nodeType, Version newTarget, boolean force) {
require(nodeType);
if (newTarget.isEmpty()) {
throw new IllegalArgumentException("Invalid target version: " + newTarget.toFullString());
}
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
Optional<OsVersion> oldTarget = Optional.ofNullable(osVersions.get(nodeType));
if (oldTarget.filter(v -> v.version().equals(newTarget)).isPresent()) {
return;
}
if (!force && oldTarget.filter(v -> v.version().isAfter(newTarget)).isPresent()) {
throw new IllegalArgumentException("Cannot set target OS version to " + newTarget +
" without setting 'force', as it's lower than the current version: "
+ oldTarget.get().version());
}
osVersions.put(nodeType, new OsVersion(newTarget, false));
db.writeOsVersions(osVersions);
createCache();
log.info("Set OS target version for " + nodeType + " nodes to " + newTarget.toFullString());
}
} | osVersions.put(nodeType, new OsVersion(newTarget, false)); | public void setTarget(NodeType nodeType, Version newTarget, boolean force) {
require(nodeType);
if (newTarget.isEmpty()) {
throw new IllegalArgumentException("Invalid target version: " + newTarget.toFullString());
}
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
Optional<OsVersion> oldTarget = Optional.ofNullable(osVersions.get(nodeType));
if (oldTarget.filter(v -> v.version().equals(newTarget)).isPresent()) {
return;
}
if (!force && oldTarget.filter(v -> v.version().isAfter(newTarget)).isPresent()) {
throw new IllegalArgumentException("Cannot set target OS version to " + newTarget +
" without setting 'force', as it's lower than the current version: "
+ oldTarget.get().version());
}
osVersions.put(nodeType, new OsVersion(newTarget, false));
db.writeOsVersions(osVersions);
createCache();
log.info("Set OS target version for " + nodeType + " nodes to " + newTarget.toFullString());
}
} | class OsVersions {
private static final Duration defaultCacheTtl = Duration.ofMinutes(1);
private static final Logger log = Logger.getLogger(OsVersions.class.getName());
private final CuratorDatabaseClient db;
private final Duration cacheTtl;
/**
* Target OS version is read on every request to /nodes/v2/node/[fqdn]. Cache current targets to avoid
* unnecessary ZK reads. When targets change, some nodes may need to wait for TTL until they see the new target,
* this is fine.
*/
private volatile Supplier<Map<NodeType, OsVersion>> currentTargets;
public OsVersions(CuratorDatabaseClient db) {
this(db, defaultCacheTtl);
}
OsVersions(CuratorDatabaseClient db, Duration cacheTtl) {
this.db = db;
this.cacheTtl = cacheTtl;
createCache();
try (var lock = db.lockOsVersions()) {
db.writeOsVersions(db.readOsVersions());
}
}
private void createCache() {
this.currentTargets = Suppliers.memoizeWithExpiration(() -> ImmutableMap.copyOf(db.readOsVersions()),
cacheTtl.toMillis(), TimeUnit.MILLISECONDS);
}
/** Returns the current target versions for each node type */
public Map<NodeType, OsVersion> targets() {
return currentTargets.get();
}
/** Returns the current target version for given node type, if any */
public Optional<OsVersion> targetFor(NodeType type) {
return Optional.ofNullable(targets().get(type));
}
/** Remove OS target for given node type. Nodes of this type will stop receiving wanted OS version in their
* node object */
public void removeTarget(NodeType nodeType) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
osVersions.remove(nodeType);
db.writeOsVersions(osVersions);
createCache();
log.info("Cleared OS target version for " + nodeType);
}
}
/** Set the target OS version for nodes of given type */
/** Activate or deactivate target for given node type. This is used for resuming or pausing an OS upgrade. */
public void setActive(NodeType nodeType, boolean active) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
var osVersions = db.readOsVersions();
var currentVersion = osVersions.get(nodeType);
if (currentVersion == null) return;
if (currentVersion.active() == active) return;
osVersions.put(nodeType, new OsVersion(currentVersion.version(), active));
db.writeOsVersions(osVersions);
createCache();
log.info((active ? "Activated" : "Deactivated") + " OS target version for " + nodeType + " nodes");
}
}
private static void require(NodeType nodeType) {
if (!nodeType.isDockerHost()) {
throw new IllegalArgumentException("Node type '" + nodeType + "' does not support OS upgrades");
}
}
} | class OsVersions {
private static final Duration defaultCacheTtl = Duration.ofMinutes(1);
private static final Logger log = Logger.getLogger(OsVersions.class.getName());
private final CuratorDatabaseClient db;
private final Duration cacheTtl;
/**
* Target OS version is read on every request to /nodes/v2/node/[fqdn]. Cache current targets to avoid
* unnecessary ZK reads. When targets change, some nodes may need to wait for TTL until they see the new target,
* this is fine.
*/
private volatile Supplier<Map<NodeType, OsVersion>> currentTargets;
public OsVersions(CuratorDatabaseClient db) {
this(db, defaultCacheTtl);
}
OsVersions(CuratorDatabaseClient db, Duration cacheTtl) {
this.db = db;
this.cacheTtl = cacheTtl;
createCache();
try (var lock = db.lockOsVersions()) {
db.writeOsVersions(db.readOsVersions());
}
}
private void createCache() {
this.currentTargets = Suppliers.memoizeWithExpiration(() -> ImmutableMap.copyOf(db.readOsVersions()),
cacheTtl.toMillis(), TimeUnit.MILLISECONDS);
}
/** Returns the current target versions for each node type */
public Map<NodeType, OsVersion> targets() {
return currentTargets.get();
}
/** Returns the current target version for given node type, if any */
public Optional<OsVersion> targetFor(NodeType type) {
return Optional.ofNullable(targets().get(type));
}
/** Remove OS target for given node type. Nodes of this type will stop receiving wanted OS version in their
* node object */
public void removeTarget(NodeType nodeType) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
osVersions.remove(nodeType);
db.writeOsVersions(osVersions);
createCache();
log.info("Cleared OS target version for " + nodeType);
}
}
/** Set the target OS version for nodes of given type */
/** Activate or deactivate target for given node type. This is used for resuming or pausing an OS upgrade. */
public void setActive(NodeType nodeType, boolean active) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
var osVersions = db.readOsVersions();
var currentVersion = osVersions.get(nodeType);
if (currentVersion == null) return;
if (currentVersion.active() == active) return;
osVersions.put(nodeType, new OsVersion(currentVersion.version(), active));
db.writeOsVersions(osVersions);
createCache();
log.info((active ? "Activated" : "Deactivated") + " OS target version for " + nodeType + " nodes");
}
}
private static void require(NodeType nodeType) {
if (!nodeType.isDockerHost()) {
throw new IllegalArgumentException("Node type '" + nodeType + "' does not support OS upgrades");
}
}
} |
True, I realised that posting my comment. We can do that, although I don't think it matters much in practice. | public void setTarget(NodeType nodeType, Version newTarget, boolean force) {
require(nodeType);
if (newTarget.isEmpty()) {
throw new IllegalArgumentException("Invalid target version: " + newTarget.toFullString());
}
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
Optional<OsVersion> oldTarget = Optional.ofNullable(osVersions.get(nodeType));
if (oldTarget.filter(v -> v.version().equals(newTarget)).isPresent()) {
return;
}
if (!force && oldTarget.filter(v -> v.version().isAfter(newTarget)).isPresent()) {
throw new IllegalArgumentException("Cannot set target OS version to " + newTarget +
" without setting 'force', as it's lower than the current version: "
+ oldTarget.get().version());
}
osVersions.put(nodeType, new OsVersion(newTarget, false));
db.writeOsVersions(osVersions);
createCache();
log.info("Set OS target version for " + nodeType + " nodes to " + newTarget.toFullString());
}
} | osVersions.put(nodeType, new OsVersion(newTarget, false)); | public void setTarget(NodeType nodeType, Version newTarget, boolean force) {
require(nodeType);
if (newTarget.isEmpty()) {
throw new IllegalArgumentException("Invalid target version: " + newTarget.toFullString());
}
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
Optional<OsVersion> oldTarget = Optional.ofNullable(osVersions.get(nodeType));
if (oldTarget.filter(v -> v.version().equals(newTarget)).isPresent()) {
return;
}
if (!force && oldTarget.filter(v -> v.version().isAfter(newTarget)).isPresent()) {
throw new IllegalArgumentException("Cannot set target OS version to " + newTarget +
" without setting 'force', as it's lower than the current version: "
+ oldTarget.get().version());
}
osVersions.put(nodeType, new OsVersion(newTarget, false));
db.writeOsVersions(osVersions);
createCache();
log.info("Set OS target version for " + nodeType + " nodes to " + newTarget.toFullString());
}
} | class OsVersions {
private static final Duration defaultCacheTtl = Duration.ofMinutes(1);
private static final Logger log = Logger.getLogger(OsVersions.class.getName());
private final CuratorDatabaseClient db;
private final Duration cacheTtl;
/**
* Target OS version is read on every request to /nodes/v2/node/[fqdn]. Cache current targets to avoid
* unnecessary ZK reads. When targets change, some nodes may need to wait for TTL until they see the new target,
* this is fine.
*/
private volatile Supplier<Map<NodeType, OsVersion>> currentTargets;
public OsVersions(CuratorDatabaseClient db) {
this(db, defaultCacheTtl);
}
OsVersions(CuratorDatabaseClient db, Duration cacheTtl) {
this.db = db;
this.cacheTtl = cacheTtl;
createCache();
try (var lock = db.lockOsVersions()) {
db.writeOsVersions(db.readOsVersions());
}
}
private void createCache() {
this.currentTargets = Suppliers.memoizeWithExpiration(() -> ImmutableMap.copyOf(db.readOsVersions()),
cacheTtl.toMillis(), TimeUnit.MILLISECONDS);
}
/** Returns the current target versions for each node type */
public Map<NodeType, OsVersion> targets() {
return currentTargets.get();
}
/** Returns the current target version for given node type, if any */
public Optional<OsVersion> targetFor(NodeType type) {
return Optional.ofNullable(targets().get(type));
}
/** Remove OS target for given node type. Nodes of this type will stop receiving wanted OS version in their
* node object */
public void removeTarget(NodeType nodeType) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
osVersions.remove(nodeType);
db.writeOsVersions(osVersions);
createCache();
log.info("Cleared OS target version for " + nodeType);
}
}
/** Set the target OS version for nodes of given type */
/** Activate or deactivate target for given node type. This is used for resuming or pausing an OS upgrade. */
public void setActive(NodeType nodeType, boolean active) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
var osVersions = db.readOsVersions();
var currentVersion = osVersions.get(nodeType);
if (currentVersion == null) return;
if (currentVersion.active() == active) return;
osVersions.put(nodeType, new OsVersion(currentVersion.version(), active));
db.writeOsVersions(osVersions);
createCache();
log.info((active ? "Activated" : "Deactivated") + " OS target version for " + nodeType + " nodes");
}
}
private static void require(NodeType nodeType) {
if (!nodeType.isDockerHost()) {
throw new IllegalArgumentException("Node type '" + nodeType + "' does not support OS upgrades");
}
}
} | class OsVersions {
private static final Duration defaultCacheTtl = Duration.ofMinutes(1);
private static final Logger log = Logger.getLogger(OsVersions.class.getName());
private final CuratorDatabaseClient db;
private final Duration cacheTtl;
/**
* Target OS version is read on every request to /nodes/v2/node/[fqdn]. Cache current targets to avoid
* unnecessary ZK reads. When targets change, some nodes may need to wait for TTL until they see the new target,
* this is fine.
*/
private volatile Supplier<Map<NodeType, OsVersion>> currentTargets;
public OsVersions(CuratorDatabaseClient db) {
this(db, defaultCacheTtl);
}
OsVersions(CuratorDatabaseClient db, Duration cacheTtl) {
this.db = db;
this.cacheTtl = cacheTtl;
createCache();
try (var lock = db.lockOsVersions()) {
db.writeOsVersions(db.readOsVersions());
}
}
private void createCache() {
this.currentTargets = Suppliers.memoizeWithExpiration(() -> ImmutableMap.copyOf(db.readOsVersions()),
cacheTtl.toMillis(), TimeUnit.MILLISECONDS);
}
/** Returns the current target versions for each node type */
public Map<NodeType, OsVersion> targets() {
return currentTargets.get();
}
/** Returns the current target version for given node type, if any */
public Optional<OsVersion> targetFor(NodeType type) {
return Optional.ofNullable(targets().get(type));
}
/** Remove OS target for given node type. Nodes of this type will stop receiving wanted OS version in their
* node object */
public void removeTarget(NodeType nodeType) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
osVersions.remove(nodeType);
db.writeOsVersions(osVersions);
createCache();
log.info("Cleared OS target version for " + nodeType);
}
}
/** Set the target OS version for nodes of given type */
/** Activate or deactivate target for given node type. This is used for resuming or pausing an OS upgrade. */
public void setActive(NodeType nodeType, boolean active) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
var osVersions = db.readOsVersions();
var currentVersion = osVersions.get(nodeType);
if (currentVersion == null) return;
if (currentVersion.active() == active) return;
osVersions.put(nodeType, new OsVersion(currentVersion.version(), active));
db.writeOsVersions(osVersions);
createCache();
log.info((active ? "Activated" : "Deactivated") + " OS target version for " + nodeType + " nodes");
}
}
private static void require(NodeType nodeType) {
if (!nodeType.isDockerHost()) {
throw new IllegalArgumentException("Node type '" + nodeType + "' does not support OS upgrades");
}
}
} |
Actually, let's leave it as-is. I think it's more clean to let `OsUpgradeActivator` be the sole thing that activates versions (as stated in javadoc). | public void setTarget(NodeType nodeType, Version newTarget, boolean force) {
require(nodeType);
if (newTarget.isEmpty()) {
throw new IllegalArgumentException("Invalid target version: " + newTarget.toFullString());
}
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
Optional<OsVersion> oldTarget = Optional.ofNullable(osVersions.get(nodeType));
if (oldTarget.filter(v -> v.version().equals(newTarget)).isPresent()) {
return;
}
if (!force && oldTarget.filter(v -> v.version().isAfter(newTarget)).isPresent()) {
throw new IllegalArgumentException("Cannot set target OS version to " + newTarget +
" without setting 'force', as it's lower than the current version: "
+ oldTarget.get().version());
}
osVersions.put(nodeType, new OsVersion(newTarget, false));
db.writeOsVersions(osVersions);
createCache();
log.info("Set OS target version for " + nodeType + " nodes to " + newTarget.toFullString());
}
} | osVersions.put(nodeType, new OsVersion(newTarget, false)); | public void setTarget(NodeType nodeType, Version newTarget, boolean force) {
require(nodeType);
if (newTarget.isEmpty()) {
throw new IllegalArgumentException("Invalid target version: " + newTarget.toFullString());
}
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
Optional<OsVersion> oldTarget = Optional.ofNullable(osVersions.get(nodeType));
if (oldTarget.filter(v -> v.version().equals(newTarget)).isPresent()) {
return;
}
if (!force && oldTarget.filter(v -> v.version().isAfter(newTarget)).isPresent()) {
throw new IllegalArgumentException("Cannot set target OS version to " + newTarget +
" without setting 'force', as it's lower than the current version: "
+ oldTarget.get().version());
}
osVersions.put(nodeType, new OsVersion(newTarget, false));
db.writeOsVersions(osVersions);
createCache();
log.info("Set OS target version for " + nodeType + " nodes to " + newTarget.toFullString());
}
} | class OsVersions {
private static final Duration defaultCacheTtl = Duration.ofMinutes(1);
private static final Logger log = Logger.getLogger(OsVersions.class.getName());
private final CuratorDatabaseClient db;
private final Duration cacheTtl;
/**
* Target OS version is read on every request to /nodes/v2/node/[fqdn]. Cache current targets to avoid
* unnecessary ZK reads. When targets change, some nodes may need to wait for TTL until they see the new target,
* this is fine.
*/
private volatile Supplier<Map<NodeType, OsVersion>> currentTargets;
public OsVersions(CuratorDatabaseClient db) {
this(db, defaultCacheTtl);
}
OsVersions(CuratorDatabaseClient db, Duration cacheTtl) {
this.db = db;
this.cacheTtl = cacheTtl;
createCache();
try (var lock = db.lockOsVersions()) {
db.writeOsVersions(db.readOsVersions());
}
}
private void createCache() {
this.currentTargets = Suppliers.memoizeWithExpiration(() -> ImmutableMap.copyOf(db.readOsVersions()),
cacheTtl.toMillis(), TimeUnit.MILLISECONDS);
}
/** Returns the current target versions for each node type */
public Map<NodeType, OsVersion> targets() {
return currentTargets.get();
}
/** Returns the current target version for given node type, if any */
public Optional<OsVersion> targetFor(NodeType type) {
return Optional.ofNullable(targets().get(type));
}
/** Remove OS target for given node type. Nodes of this type will stop receiving wanted OS version in their
* node object */
public void removeTarget(NodeType nodeType) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
osVersions.remove(nodeType);
db.writeOsVersions(osVersions);
createCache();
log.info("Cleared OS target version for " + nodeType);
}
}
/** Set the target OS version for nodes of given type */
/** Activate or deactivate target for given node type. This is used for resuming or pausing an OS upgrade. */
public void setActive(NodeType nodeType, boolean active) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
var osVersions = db.readOsVersions();
var currentVersion = osVersions.get(nodeType);
if (currentVersion == null) return;
if (currentVersion.active() == active) return;
osVersions.put(nodeType, new OsVersion(currentVersion.version(), active));
db.writeOsVersions(osVersions);
createCache();
log.info((active ? "Activated" : "Deactivated") + " OS target version for " + nodeType + " nodes");
}
}
private static void require(NodeType nodeType) {
if (!nodeType.isDockerHost()) {
throw new IllegalArgumentException("Node type '" + nodeType + "' does not support OS upgrades");
}
}
} | class OsVersions {
private static final Duration defaultCacheTtl = Duration.ofMinutes(1);
private static final Logger log = Logger.getLogger(OsVersions.class.getName());
private final CuratorDatabaseClient db;
private final Duration cacheTtl;
/**
* Target OS version is read on every request to /nodes/v2/node/[fqdn]. Cache current targets to avoid
* unnecessary ZK reads. When targets change, some nodes may need to wait for TTL until they see the new target,
* this is fine.
*/
private volatile Supplier<Map<NodeType, OsVersion>> currentTargets;
public OsVersions(CuratorDatabaseClient db) {
this(db, defaultCacheTtl);
}
OsVersions(CuratorDatabaseClient db, Duration cacheTtl) {
this.db = db;
this.cacheTtl = cacheTtl;
createCache();
try (var lock = db.lockOsVersions()) {
db.writeOsVersions(db.readOsVersions());
}
}
private void createCache() {
this.currentTargets = Suppliers.memoizeWithExpiration(() -> ImmutableMap.copyOf(db.readOsVersions()),
cacheTtl.toMillis(), TimeUnit.MILLISECONDS);
}
/** Returns the current target versions for each node type */
public Map<NodeType, OsVersion> targets() {
return currentTargets.get();
}
/** Returns the current target version for given node type, if any */
public Optional<OsVersion> targetFor(NodeType type) {
return Optional.ofNullable(targets().get(type));
}
/** Remove OS target for given node type. Nodes of this type will stop receiving wanted OS version in their
* node object */
public void removeTarget(NodeType nodeType) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
Map<NodeType, OsVersion> osVersions = db.readOsVersions();
osVersions.remove(nodeType);
db.writeOsVersions(osVersions);
createCache();
log.info("Cleared OS target version for " + nodeType);
}
}
/** Set the target OS version for nodes of given type */
/** Activate or deactivate target for given node type. This is used for resuming or pausing an OS upgrade. */
public void setActive(NodeType nodeType, boolean active) {
require(nodeType);
try (Lock lock = db.lockOsVersions()) {
var osVersions = db.readOsVersions();
var currentVersion = osVersions.get(nodeType);
if (currentVersion == null) return;
if (currentVersion.active() == active) return;
osVersions.put(nodeType, new OsVersion(currentVersion.version(), active));
db.writeOsVersions(osVersions);
createCache();
log.info((active ? "Activated" : "Deactivated") + " OS target version for " + nodeType + " nodes");
}
}
private static void require(NodeType nodeType) {
if (!nodeType.isDockerHost()) {
throw new IllegalArgumentException("Node type '" + nodeType + "' does not support OS upgrades");
}
}
} |
This is a bug waiting to happen ... perhaps put a big fat warning comment here? | public void removeInstance(ApplicationId id) {
curator.delete(applicationPath(id));
curator.delete(instancePath(id));
} | curator.delete(applicationPath(id)); | public void removeInstance(ApplicationId id) {
curator.delete(applicationPath(id));
curator.delete(instancePath(id));
} | class CuratorDb {
private static final Logger log = Logger.getLogger(CuratorDb.class.getName());
private static final Duration deployLockTimeout = Duration.ofMinutes(30);
private static final Duration defaultLockTimeout = Duration.ofMinutes(5);
private static final Duration defaultTryLockTimeout = Duration.ofSeconds(1);
private static final Path root = Path.fromString("/controller/v1");
private static final Path lockRoot = root.append("locks");
private static final Path tenantRoot = root.append("tenants");
private static final Path applicationRoot = root.append("applications");
private static final Path instanceRoot = root.append("instances");
private static final Path jobRoot = root.append("jobs");
private static final Path controllerRoot = root.append("controllers");
private static final Path routingPoliciesRoot = root.append("routingPolicies");
private static final Path applicationCertificateRoot = root.append("applicationCertificates");
private final StringSetSerializer stringSetSerializer = new StringSetSerializer();
private final VersionStatusSerializer versionStatusSerializer = new VersionStatusSerializer();
private final ControllerVersionSerializer controllerVersionSerializer = new ControllerVersionSerializer();
private final ConfidenceOverrideSerializer confidenceOverrideSerializer = new ConfidenceOverrideSerializer();
private final TenantSerializer tenantSerializer = new TenantSerializer();
private final InstanceSerializer instanceSerializer = new InstanceSerializer();
private final RunSerializer runSerializer = new RunSerializer();
private final OsVersionSerializer osVersionSerializer = new OsVersionSerializer();
private final OsVersionStatusSerializer osVersionStatusSerializer = new OsVersionStatusSerializer(osVersionSerializer);
private final RoutingPolicySerializer routingPolicySerializer = new RoutingPolicySerializer();
private final AuditLogSerializer auditLogSerializer = new AuditLogSerializer();
private final NameServiceQueueSerializer nameServiceQueueSerializer = new NameServiceQueueSerializer();
private final Curator curator;
private final Duration tryLockTimeout;
/**
* All keys, to allow reentrancy.
* This will grow forever, but this should be too slow to be a problem.
*/
private final ConcurrentHashMap<Path, Lock> locks = new ConcurrentHashMap<>();
@Inject
public CuratorDb(Curator curator) {
this(curator, defaultTryLockTimeout);
}
CuratorDb(Curator curator, Duration tryLockTimeout) {
this.curator = curator;
this.tryLockTimeout = tryLockTimeout;
}
/** Returns all hosts configured to be part of this ZooKeeper cluster */
public List<HostName> cluster() {
return Arrays.stream(curator.zooKeeperEnsembleConnectionSpec().split(","))
.filter(hostAndPort -> !hostAndPort.isEmpty())
.map(hostAndPort -> hostAndPort.split(":")[0])
.map(HostName::from)
.collect(Collectors.toList());
}
/** Creates a reentrant lock */
private Lock lock(Path path, Duration timeout) {
curator.create(path);
Lock lock = locks.computeIfAbsent(path, (pathArg) -> new Lock(pathArg.getAbsolute(), curator));
lock.acquire(timeout);
return lock;
}
public Lock lock(TenantName name) {
return lock(lockPath(name), defaultLockTimeout.multipliedBy(2));
}
public Lock lock(ApplicationId id) {
return lock(lockPath(id), defaultLockTimeout.multipliedBy(2));
}
public Lock lockForDeployment(ApplicationId id, ZoneId zone) {
return lock(lockPath(id, zone), deployLockTimeout);
}
public Lock lock(ApplicationId id, JobType type) {
return lock(lockPath(id, type), defaultLockTimeout);
}
public Lock lock(ApplicationId id, JobType type, Step step) throws TimeoutException {
return tryLock(lockPath(id, type, step));
}
public Lock lockRotations() {
return lock(lockRoot.append("rotations"), defaultLockTimeout);
}
public Lock lockConfidenceOverrides() {
return lock(lockRoot.append("confidenceOverrides"), defaultLockTimeout);
}
public Lock lockInactiveJobs() {
return lock(lockRoot.append("inactiveJobsLock"), defaultLockTimeout);
}
public Lock lockMaintenanceJob(String jobName) throws TimeoutException {
return tryLock(lockRoot.append("maintenanceJobLocks").append(jobName));
}
@SuppressWarnings("unused")
public Lock lockProvisionState(String provisionStateId) {
return lock(lockPath(provisionStateId), Duration.ofSeconds(1));
}
public Lock lockOsVersions() {
return lock(lockRoot.append("osTargetVersion"), defaultLockTimeout);
}
public Lock lockOsVersionStatus() {
return lock(lockRoot.append("osVersionStatus"), defaultLockTimeout);
}
public Lock lockRoutingPolicies() {
return lock(lockRoot.append("routingPolicies"), defaultLockTimeout);
}
public Lock lockAuditLog() {
return lock(lockRoot.append("auditLog"), defaultLockTimeout);
}
public Lock lockNameServiceQueue() {
return lock(lockRoot.append("nameServiceQueue"), defaultLockTimeout);
}
/** Try locking with a low timeout, meaning it is OK to fail lock acquisition.
*
* Useful for maintenance jobs, where there is no point in running the jobs back to back.
*/
private Lock tryLock(Path path) throws TimeoutException {
try {
return lock(path, tryLockTimeout);
}
catch (UncheckedTimeoutException e) {
throw new TimeoutException(e.getMessage());
}
}
private <T> Optional<T> read(Path path, Function<byte[], T> mapper) {
return curator.getData(path).filter(data -> data.length > 0).map(mapper);
}
private Optional<Slime> readSlime(Path path) {
return read(path, SlimeUtils::jsonToSlime);
}
private static byte[] asJson(Slime slime) {
try {
return SlimeUtils.toJsonBytes(slime);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public Set<String> readInactiveJobs() {
try {
return readSlime(inactiveJobsPath()).map(stringSetSerializer::fromSlime).orElseGet(HashSet::new);
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Error reading inactive jobs, deleting inactive state");
writeInactiveJobs(Collections.emptySet());
return new HashSet<>();
}
}
public void writeInactiveJobs(Set<String> inactiveJobs) {
curator.set(inactiveJobsPath(), stringSetSerializer.toJson(inactiveJobs));
}
public double readUpgradesPerMinute() {
return read(upgradesPerMinutePath(), ByteBuffer::wrap).map(ByteBuffer::getDouble).orElse(0.125);
}
public void writeUpgradesPerMinute(double n) {
curator.set(upgradesPerMinutePath(), ByteBuffer.allocate(Double.BYTES).putDouble(n).array());
}
public Optional<Integer> readTargetMajorVersion() {
return read(targetMajorVersionPath(), ByteBuffer::wrap).map(ByteBuffer::getInt);
}
public void writeTargetMajorVersion(Optional<Integer> targetMajorVersion) {
if (targetMajorVersion.isPresent())
curator.set(targetMajorVersionPath(), ByteBuffer.allocate(Integer.BYTES).putInt(targetMajorVersion.get()).array());
else
curator.delete(targetMajorVersionPath());
}
public void writeVersionStatus(VersionStatus status) {
curator.set(versionStatusPath(), asJson(versionStatusSerializer.toSlime(status)));
}
public VersionStatus readVersionStatus() {
return readSlime(versionStatusPath()).map(versionStatusSerializer::fromSlime).orElseGet(VersionStatus::empty);
}
public void writeConfidenceOverrides(Map<Version, VespaVersion.Confidence> overrides) {
curator.set(confidenceOverridesPath(), asJson(confidenceOverrideSerializer.toSlime(overrides)));
}
public Map<Version, VespaVersion.Confidence> readConfidenceOverrides() {
return readSlime(confidenceOverridesPath()).map(confidenceOverrideSerializer::fromSlime)
.orElseGet(Collections::emptyMap);
}
public void writeControllerVersion(HostName hostname, ControllerVersion version) {
curator.set(controllerPath(hostname.value()), asJson(controllerVersionSerializer.toSlime(version)));
}
public ControllerVersion readControllerVersion(HostName hostname) {
return readSlime(controllerPath(hostname.value()))
.map(controllerVersionSerializer::fromSlime)
.orElse(ControllerVersion.CURRENT);
}
public void writeOsVersions(Set<OsVersion> versions) {
curator.set(osTargetVersionPath(), asJson(osVersionSerializer.toSlime(versions)));
}
public Set<OsVersion> readOsVersions() {
return readSlime(osTargetVersionPath()).map(osVersionSerializer::fromSlime).orElseGet(Collections::emptySet);
}
public void writeOsVersionStatus(OsVersionStatus status) {
curator.set(osVersionStatusPath(), asJson(osVersionStatusSerializer.toSlime(status)));
}
public OsVersionStatus readOsVersionStatus() {
return readSlime(osVersionStatusPath()).map(osVersionStatusSerializer::fromSlime).orElse(OsVersionStatus.empty);
}
public void writeTenant(Tenant tenant) {
curator.set(tenantPath(tenant.name()), asJson(tenantSerializer.toSlime(tenant)));
}
public Optional<Tenant> readTenant(TenantName name) {
return readSlime(tenantPath(name)).map(tenantSerializer::tenantFrom);
}
public List<Tenant> readTenants() {
return readTenantNames().stream()
.map(this::readTenant)
.flatMap(Optional::stream)
.collect(collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
}
public List<TenantName> readTenantNames() {
return curator.getChildren(tenantRoot).stream()
.map(TenantName::from)
.collect(Collectors.toList());
}
public void removeTenant(TenantName name) {
curator.delete(tenantPath(name));
}
public void writeInstance(Instance instance) {
curator.set(applicationPath(instance.id()), asJson(instanceSerializer.toSlime(instance)));
curator.set(instancePath(instance.id()), asJson(instanceSerializer.toSlime(instance)));
}
public Optional<Instance> readInstance(ApplicationId application) {
return readSlime(instancePath(application)).or(() -> readSlime(applicationPath(application)))
.map(instanceSerializer::fromSlime);
}
public List<Instance> readInstances() {
return readInstances(ignored -> true);
}
public List<Instance> readInstances(TenantName name) {
return readInstances(application -> application.tenant().equals(name));
}
private Stream<ApplicationId> readInstanceIds() {
return Stream.concat(curator.getChildren(applicationRoot).stream()
.filter(id -> id.split(":").length == 3),
curator.getChildren(instanceRoot).stream())
.distinct()
.map(ApplicationId::fromSerializedForm);
}
private List<Instance> readInstances(Predicate<ApplicationId> instanceFilter) {
return readInstanceIds().filter(instanceFilter)
.map(this::readInstance)
.flatMap(Optional::stream)
.collect(Collectors.toUnmodifiableList());
}
public void writeLastRun(Run run) {
curator.set(lastRunPath(run.id().application(), run.id().type()), asJson(runSerializer.toSlime(run)));
}
public void writeHistoricRuns(ApplicationId id, JobType type, Iterable<Run> runs) {
curator.set(runsPath(id, type), asJson(runSerializer.toSlime(runs)));
}
public Optional<Run> readLastRun(ApplicationId id, JobType type) {
return readSlime(lastRunPath(id, type)).map(runSerializer::runFromSlime);
}
public SortedMap<RunId, Run> readHistoricRuns(ApplicationId id, JobType type) {
return readSlime(runsPath(id, type)).map(runSerializer::runsFromSlime).orElse(new TreeMap<>(comparing(RunId::number)));
}
public void deleteRunData(ApplicationId id, JobType type) {
curator.delete(runsPath(id, type));
curator.delete(lastRunPath(id, type));
}
public void deleteRunData(ApplicationId id) {
curator.delete(jobRoot.append(id.serializedForm()));
}
public List<ApplicationId> applicationsWithJobs() {
return curator.getChildren(jobRoot).stream()
.map(ApplicationId::fromSerializedForm)
.collect(Collectors.toList());
}
public Optional<byte[]> readLog(ApplicationId id, JobType type, long chunkId) {
return curator.getData(logPath(id, type, chunkId));
}
public void writeLog(ApplicationId id, JobType type, long chunkId, byte[] log) {
curator.set(logPath(id, type, chunkId), log);
}
public void deleteLog(ApplicationId id, JobType type) {
curator.delete(runsPath(id, type).append("logs"));
}
public Optional<Long> readLastLogEntryId(ApplicationId id, JobType type) {
return curator.getData(lastLogPath(id, type))
.map(String::new).map(Long::parseLong);
}
public void writeLastLogEntryId(ApplicationId id, JobType type, long lastId) {
curator.set(lastLogPath(id, type), Long.toString(lastId).getBytes());
}
public LongStream getLogChunkIds(ApplicationId id, JobType type) {
return curator.getChildren(runsPath(id, type).append("logs")).stream()
.mapToLong(Long::parseLong)
.sorted();
}
public AuditLog readAuditLog() {
return readSlime(auditLogPath()).map(auditLogSerializer::fromSlime)
.orElse(AuditLog.empty);
}
public void writeAuditLog(AuditLog log) {
curator.set(auditLogPath(), asJson(auditLogSerializer.toSlime(log)));
}
public NameServiceQueue readNameServiceQueue() {
return readSlime(nameServiceQueuePath()).map(nameServiceQueueSerializer::fromSlime)
.orElse(NameServiceQueue.EMPTY);
}
public void writeNameServiceQueue(NameServiceQueue queue) {
curator.set(nameServiceQueuePath(), asJson(nameServiceQueueSerializer.toSlime(queue)));
}
@SuppressWarnings("unused")
public Optional<byte[]> readProvisionState(String provisionId) {
return curator.getData(provisionStatePath(provisionId));
}
@SuppressWarnings("unused")
public void writeProvisionState(String provisionId, byte[] data) {
curator.set(provisionStatePath(provisionId), data);
}
@SuppressWarnings("unused")
public List<String> readProvisionStateIds() {
return curator.getChildren(provisionStatePath());
}
public void writeRoutingPolicies(ApplicationId application, Set<RoutingPolicy> policies) {
curator.set(routingPolicyPath(application), asJson(routingPolicySerializer.toSlime(policies)));
}
public Map<ApplicationId, Set<RoutingPolicy>> readRoutingPolicies() {
return curator.getChildren(routingPoliciesRoot).stream()
.map(ApplicationId::fromSerializedForm)
.collect(Collectors.toUnmodifiableMap(Function.identity(), this::readRoutingPolicies));
}
public Set<RoutingPolicy> readRoutingPolicies(ApplicationId application) {
return readSlime(routingPolicyPath(application)).map(slime -> routingPolicySerializer.fromSlime(application, slime))
.orElseGet(Collections::emptySet);
}
public void writeApplicationCertificate(ApplicationId applicationId, ApplicationCertificate applicationCertificate) {
curator.set(applicationCertificatePath(applicationId), applicationCertificate.secretsKeyNamePrefix().getBytes());
}
public Optional<ApplicationCertificate> readApplicationCertificate(ApplicationId applicationId) {
return curator.getData(applicationCertificatePath(applicationId)).map(String::new).map(ApplicationCertificate::new);
}
private Path lockPath(TenantName tenant) {
return lockRoot
.append(tenant.value());
}
private Path lockPath(ApplicationId application) {
return lockPath(application.tenant())
.append(application.application().value())
.append(application.instance().value());
}
private Path lockPath(ApplicationId application, ZoneId zone) {
return lockPath(application)
.append(zone.environment().value())
.append(zone.region().value());
}
private Path lockPath(ApplicationId application, JobType type) {
return lockPath(application)
.append(type.jobName());
}
private Path lockPath(ApplicationId application, JobType type, Step step) {
return lockPath(application, type)
.append(step.name());
}
private Path lockPath(String provisionId) {
return lockRoot
.append(provisionStatePath())
.append(provisionId);
}
private static Path inactiveJobsPath() {
return root.append("inactiveJobs");
}
private static Path upgradesPerMinutePath() {
return root.append("upgrader").append("upgradesPerMinute");
}
private static Path targetMajorVersionPath() {
return root.append("upgrader").append("targetMajorVersion");
}
private static Path confidenceOverridesPath() {
return root.append("upgrader").append("confidenceOverrides");
}
private static Path osTargetVersionPath() {
return root.append("osUpgrader").append("targetVersion");
}
private static Path osVersionStatusPath() {
return root.append("osVersionStatus");
}
private static Path versionStatusPath() {
return root.append("versionStatus");
}
private static Path routingPolicyPath(ApplicationId application) {
return routingPoliciesRoot.append(application.serializedForm());
}
private static Path nameServiceQueuePath() {
return root.append("nameServiceQueue");
}
private static Path auditLogPath() {
return root.append("auditLog");
}
private static Path provisionStatePath() {
return root.append("provisioning").append("states");
}
private static Path provisionStatePath(String provisionId) {
return provisionStatePath().append(provisionId);
}
private static Path tenantPath(TenantName name) {
return tenantRoot.append(name.value());
}
private static Path applicationPath(ApplicationId application) {
return applicationRoot.append(application.serializedForm());
}
private static Path instancePath(ApplicationId id) {
return instanceRoot.append(id.serializedForm());
}
private static Path runsPath(ApplicationId id, JobType type) {
return jobRoot.append(id.serializedForm()).append(type.jobName());
}
private static Path lastRunPath(ApplicationId id, JobType type) {
return runsPath(id, type).append("last");
}
private static Path logPath(ApplicationId id, JobType type, long first) {
return runsPath(id, type).append("logs").append(Long.toString(first));
}
private static Path lastLogPath(ApplicationId id, JobType type) {
return runsPath(id, type).append("logs");
}
private static Path controllerPath(String hostname) {
return controllerRoot.append(hostname);
}
private static Path applicationCertificatePath(ApplicationId id) {
return applicationCertificateRoot.append(id.serializedForm());
}
} | class CuratorDb {
private static final Logger log = Logger.getLogger(CuratorDb.class.getName());
private static final Duration deployLockTimeout = Duration.ofMinutes(30);
private static final Duration defaultLockTimeout = Duration.ofMinutes(5);
private static final Duration defaultTryLockTimeout = Duration.ofSeconds(1);
private static final Path root = Path.fromString("/controller/v1");
private static final Path lockRoot = root.append("locks");
private static final Path tenantRoot = root.append("tenants");
private static final Path applicationRoot = root.append("applications");
private static final Path instanceRoot = root.append("instances");
private static final Path jobRoot = root.append("jobs");
private static final Path controllerRoot = root.append("controllers");
private static final Path routingPoliciesRoot = root.append("routingPolicies");
private static final Path applicationCertificateRoot = root.append("applicationCertificates");
private final StringSetSerializer stringSetSerializer = new StringSetSerializer();
private final VersionStatusSerializer versionStatusSerializer = new VersionStatusSerializer();
private final ControllerVersionSerializer controllerVersionSerializer = new ControllerVersionSerializer();
private final ConfidenceOverrideSerializer confidenceOverrideSerializer = new ConfidenceOverrideSerializer();
private final TenantSerializer tenantSerializer = new TenantSerializer();
private final InstanceSerializer instanceSerializer = new InstanceSerializer();
private final RunSerializer runSerializer = new RunSerializer();
private final OsVersionSerializer osVersionSerializer = new OsVersionSerializer();
private final OsVersionStatusSerializer osVersionStatusSerializer = new OsVersionStatusSerializer(osVersionSerializer);
private final RoutingPolicySerializer routingPolicySerializer = new RoutingPolicySerializer();
private final AuditLogSerializer auditLogSerializer = new AuditLogSerializer();
private final NameServiceQueueSerializer nameServiceQueueSerializer = new NameServiceQueueSerializer();
private final Curator curator;
private final Duration tryLockTimeout;
/**
* All keys, to allow reentrancy.
* This will grow forever, but this should be too slow to be a problem.
*/
private final ConcurrentHashMap<Path, Lock> locks = new ConcurrentHashMap<>();
@Inject
public CuratorDb(Curator curator) {
this(curator, defaultTryLockTimeout);
}
CuratorDb(Curator curator, Duration tryLockTimeout) {
this.curator = curator;
this.tryLockTimeout = tryLockTimeout;
}
/** Returns all hosts configured to be part of this ZooKeeper cluster */
public List<HostName> cluster() {
return Arrays.stream(curator.zooKeeperEnsembleConnectionSpec().split(","))
.filter(hostAndPort -> !hostAndPort.isEmpty())
.map(hostAndPort -> hostAndPort.split(":")[0])
.map(HostName::from)
.collect(Collectors.toList());
}
/** Creates a reentrant lock */
private Lock lock(Path path, Duration timeout) {
curator.create(path);
Lock lock = locks.computeIfAbsent(path, (pathArg) -> new Lock(pathArg.getAbsolute(), curator));
lock.acquire(timeout);
return lock;
}
public Lock lock(TenantName name) {
return lock(lockPath(name), defaultLockTimeout.multipliedBy(2));
}
public Lock lock(ApplicationId id) {
return lock(lockPath(id), defaultLockTimeout.multipliedBy(2));
}
public Lock lockForDeployment(ApplicationId id, ZoneId zone) {
return lock(lockPath(id, zone), deployLockTimeout);
}
public Lock lock(ApplicationId id, JobType type) {
return lock(lockPath(id, type), defaultLockTimeout);
}
public Lock lock(ApplicationId id, JobType type, Step step) throws TimeoutException {
return tryLock(lockPath(id, type, step));
}
public Lock lockRotations() {
return lock(lockRoot.append("rotations"), defaultLockTimeout);
}
public Lock lockConfidenceOverrides() {
return lock(lockRoot.append("confidenceOverrides"), defaultLockTimeout);
}
public Lock lockInactiveJobs() {
return lock(lockRoot.append("inactiveJobsLock"), defaultLockTimeout);
}
public Lock lockMaintenanceJob(String jobName) throws TimeoutException {
return tryLock(lockRoot.append("maintenanceJobLocks").append(jobName));
}
@SuppressWarnings("unused")
public Lock lockProvisionState(String provisionStateId) {
return lock(lockPath(provisionStateId), Duration.ofSeconds(1));
}
public Lock lockOsVersions() {
return lock(lockRoot.append("osTargetVersion"), defaultLockTimeout);
}
public Lock lockOsVersionStatus() {
return lock(lockRoot.append("osVersionStatus"), defaultLockTimeout);
}
public Lock lockRoutingPolicies() {
return lock(lockRoot.append("routingPolicies"), defaultLockTimeout);
}
public Lock lockAuditLog() {
return lock(lockRoot.append("auditLog"), defaultLockTimeout);
}
public Lock lockNameServiceQueue() {
return lock(lockRoot.append("nameServiceQueue"), defaultLockTimeout);
}
/** Try locking with a low timeout, meaning it is OK to fail lock acquisition.
*
* Useful for maintenance jobs, where there is no point in running the jobs back to back.
*/
private Lock tryLock(Path path) throws TimeoutException {
try {
return lock(path, tryLockTimeout);
}
catch (UncheckedTimeoutException e) {
throw new TimeoutException(e.getMessage());
}
}
private <T> Optional<T> read(Path path, Function<byte[], T> mapper) {
return curator.getData(path).filter(data -> data.length > 0).map(mapper);
}
private Optional<Slime> readSlime(Path path) {
return read(path, SlimeUtils::jsonToSlime);
}
private static byte[] asJson(Slime slime) {
try {
return SlimeUtils.toJsonBytes(slime);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public Set<String> readInactiveJobs() {
try {
return readSlime(inactiveJobsPath()).map(stringSetSerializer::fromSlime).orElseGet(HashSet::new);
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Error reading inactive jobs, deleting inactive state");
writeInactiveJobs(Collections.emptySet());
return new HashSet<>();
}
}
public void writeInactiveJobs(Set<String> inactiveJobs) {
curator.set(inactiveJobsPath(), stringSetSerializer.toJson(inactiveJobs));
}
public double readUpgradesPerMinute() {
return read(upgradesPerMinutePath(), ByteBuffer::wrap).map(ByteBuffer::getDouble).orElse(0.125);
}
public void writeUpgradesPerMinute(double n) {
curator.set(upgradesPerMinutePath(), ByteBuffer.allocate(Double.BYTES).putDouble(n).array());
}
public Optional<Integer> readTargetMajorVersion() {
return read(targetMajorVersionPath(), ByteBuffer::wrap).map(ByteBuffer::getInt);
}
public void writeTargetMajorVersion(Optional<Integer> targetMajorVersion) {
if (targetMajorVersion.isPresent())
curator.set(targetMajorVersionPath(), ByteBuffer.allocate(Integer.BYTES).putInt(targetMajorVersion.get()).array());
else
curator.delete(targetMajorVersionPath());
}
public void writeVersionStatus(VersionStatus status) {
curator.set(versionStatusPath(), asJson(versionStatusSerializer.toSlime(status)));
}
public VersionStatus readVersionStatus() {
return readSlime(versionStatusPath()).map(versionStatusSerializer::fromSlime).orElseGet(VersionStatus::empty);
}
public void writeConfidenceOverrides(Map<Version, VespaVersion.Confidence> overrides) {
curator.set(confidenceOverridesPath(), asJson(confidenceOverrideSerializer.toSlime(overrides)));
}
public Map<Version, VespaVersion.Confidence> readConfidenceOverrides() {
return readSlime(confidenceOverridesPath()).map(confidenceOverrideSerializer::fromSlime)
.orElseGet(Collections::emptyMap);
}
public void writeControllerVersion(HostName hostname, ControllerVersion version) {
curator.set(controllerPath(hostname.value()), asJson(controllerVersionSerializer.toSlime(version)));
}
public ControllerVersion readControllerVersion(HostName hostname) {
return readSlime(controllerPath(hostname.value()))
.map(controllerVersionSerializer::fromSlime)
.orElse(ControllerVersion.CURRENT);
}
public void writeOsVersions(Set<OsVersion> versions) {
curator.set(osTargetVersionPath(), asJson(osVersionSerializer.toSlime(versions)));
}
public Set<OsVersion> readOsVersions() {
return readSlime(osTargetVersionPath()).map(osVersionSerializer::fromSlime).orElseGet(Collections::emptySet);
}
public void writeOsVersionStatus(OsVersionStatus status) {
curator.set(osVersionStatusPath(), asJson(osVersionStatusSerializer.toSlime(status)));
}
public OsVersionStatus readOsVersionStatus() {
return readSlime(osVersionStatusPath()).map(osVersionStatusSerializer::fromSlime).orElse(OsVersionStatus.empty);
}
public void writeTenant(Tenant tenant) {
curator.set(tenantPath(tenant.name()), asJson(tenantSerializer.toSlime(tenant)));
}
public Optional<Tenant> readTenant(TenantName name) {
return readSlime(tenantPath(name)).map(tenantSerializer::tenantFrom);
}
public List<Tenant> readTenants() {
return readTenantNames().stream()
.map(this::readTenant)
.flatMap(Optional::stream)
.collect(collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
}
public List<TenantName> readTenantNames() {
return curator.getChildren(tenantRoot).stream()
.map(TenantName::from)
.collect(Collectors.toList());
}
public void removeTenant(TenantName name) {
curator.delete(tenantPath(name));
}
public void writeInstance(Instance instance) {
curator.set(applicationPath(instance.id()), asJson(instanceSerializer.toSlime(instance)));
curator.set(instancePath(instance.id()), asJson(instanceSerializer.toSlime(instance)));
}
public Optional<Instance> readInstance(ApplicationId application) {
return readSlime(instancePath(application)).or(() -> readSlime(applicationPath(application)))
.map(instanceSerializer::fromSlime);
}
public List<Instance> readInstances() {
return readInstances(ignored -> true);
}
public List<Instance> readInstances(TenantName name) {
return readInstances(application -> application.tenant().equals(name));
}
private Stream<ApplicationId> readInstanceIds() {
return Stream.concat(curator.getChildren(applicationRoot).stream()
.filter(id -> id.split(":").length == 3),
curator.getChildren(instanceRoot).stream())
.distinct()
.map(ApplicationId::fromSerializedForm);
}
private List<Instance> readInstances(Predicate<ApplicationId> instanceFilter) {
return readInstanceIds().filter(instanceFilter)
.map(this::readInstance)
.flatMap(Optional::stream)
.collect(Collectors.toUnmodifiableList());
}
public void writeLastRun(Run run) {
curator.set(lastRunPath(run.id().application(), run.id().type()), asJson(runSerializer.toSlime(run)));
}
public void writeHistoricRuns(ApplicationId id, JobType type, Iterable<Run> runs) {
curator.set(runsPath(id, type), asJson(runSerializer.toSlime(runs)));
}
public Optional<Run> readLastRun(ApplicationId id, JobType type) {
return readSlime(lastRunPath(id, type)).map(runSerializer::runFromSlime);
}
public SortedMap<RunId, Run> readHistoricRuns(ApplicationId id, JobType type) {
return readSlime(runsPath(id, type)).map(runSerializer::runsFromSlime).orElse(new TreeMap<>(comparing(RunId::number)));
}
public void deleteRunData(ApplicationId id, JobType type) {
curator.delete(runsPath(id, type));
curator.delete(lastRunPath(id, type));
}
public void deleteRunData(ApplicationId id) {
curator.delete(jobRoot.append(id.serializedForm()));
}
public List<ApplicationId> applicationsWithJobs() {
return curator.getChildren(jobRoot).stream()
.map(ApplicationId::fromSerializedForm)
.collect(Collectors.toList());
}
public Optional<byte[]> readLog(ApplicationId id, JobType type, long chunkId) {
return curator.getData(logPath(id, type, chunkId));
}
public void writeLog(ApplicationId id, JobType type, long chunkId, byte[] log) {
curator.set(logPath(id, type, chunkId), log);
}
public void deleteLog(ApplicationId id, JobType type) {
curator.delete(runsPath(id, type).append("logs"));
}
public Optional<Long> readLastLogEntryId(ApplicationId id, JobType type) {
return curator.getData(lastLogPath(id, type))
.map(String::new).map(Long::parseLong);
}
public void writeLastLogEntryId(ApplicationId id, JobType type, long lastId) {
curator.set(lastLogPath(id, type), Long.toString(lastId).getBytes());
}
public LongStream getLogChunkIds(ApplicationId id, JobType type) {
return curator.getChildren(runsPath(id, type).append("logs")).stream()
.mapToLong(Long::parseLong)
.sorted();
}
public AuditLog readAuditLog() {
return readSlime(auditLogPath()).map(auditLogSerializer::fromSlime)
.orElse(AuditLog.empty);
}
public void writeAuditLog(AuditLog log) {
curator.set(auditLogPath(), asJson(auditLogSerializer.toSlime(log)));
}
public NameServiceQueue readNameServiceQueue() {
return readSlime(nameServiceQueuePath()).map(nameServiceQueueSerializer::fromSlime)
.orElse(NameServiceQueue.EMPTY);
}
public void writeNameServiceQueue(NameServiceQueue queue) {
curator.set(nameServiceQueuePath(), asJson(nameServiceQueueSerializer.toSlime(queue)));
}
@SuppressWarnings("unused")
public Optional<byte[]> readProvisionState(String provisionId) {
return curator.getData(provisionStatePath(provisionId));
}
@SuppressWarnings("unused")
public void writeProvisionState(String provisionId, byte[] data) {
curator.set(provisionStatePath(provisionId), data);
}
@SuppressWarnings("unused")
public List<String> readProvisionStateIds() {
return curator.getChildren(provisionStatePath());
}
public void writeRoutingPolicies(ApplicationId application, Set<RoutingPolicy> policies) {
curator.set(routingPolicyPath(application), asJson(routingPolicySerializer.toSlime(policies)));
}
public Map<ApplicationId, Set<RoutingPolicy>> readRoutingPolicies() {
return curator.getChildren(routingPoliciesRoot).stream()
.map(ApplicationId::fromSerializedForm)
.collect(Collectors.toUnmodifiableMap(Function.identity(), this::readRoutingPolicies));
}
public Set<RoutingPolicy> readRoutingPolicies(ApplicationId application) {
return readSlime(routingPolicyPath(application)).map(slime -> routingPolicySerializer.fromSlime(application, slime))
.orElseGet(Collections::emptySet);
}
public void writeApplicationCertificate(ApplicationId applicationId, ApplicationCertificate applicationCertificate) {
curator.set(applicationCertificatePath(applicationId), applicationCertificate.secretsKeyNamePrefix().getBytes());
}
public Optional<ApplicationCertificate> readApplicationCertificate(ApplicationId applicationId) {
return curator.getData(applicationCertificatePath(applicationId)).map(String::new).map(ApplicationCertificate::new);
}
private Path lockPath(TenantName tenant) {
return lockRoot
.append(tenant.value());
}
private Path lockPath(ApplicationId application) {
return lockPath(application.tenant())
.append(application.application().value())
.append(application.instance().value());
}
private Path lockPath(ApplicationId application, ZoneId zone) {
return lockPath(application)
.append(zone.environment().value())
.append(zone.region().value());
}
private Path lockPath(ApplicationId application, JobType type) {
return lockPath(application)
.append(type.jobName());
}
private Path lockPath(ApplicationId application, JobType type, Step step) {
return lockPath(application, type)
.append(step.name());
}
private Path lockPath(String provisionId) {
return lockRoot
.append(provisionStatePath())
.append(provisionId);
}
private static Path inactiveJobsPath() {
return root.append("inactiveJobs");
}
private static Path upgradesPerMinutePath() {
return root.append("upgrader").append("upgradesPerMinute");
}
private static Path targetMajorVersionPath() {
return root.append("upgrader").append("targetMajorVersion");
}
private static Path confidenceOverridesPath() {
return root.append("upgrader").append("confidenceOverrides");
}
private static Path osTargetVersionPath() {
return root.append("osUpgrader").append("targetVersion");
}
private static Path osVersionStatusPath() {
return root.append("osVersionStatus");
}
private static Path versionStatusPath() {
return root.append("versionStatus");
}
private static Path routingPolicyPath(ApplicationId application) {
return routingPoliciesRoot.append(application.serializedForm());
}
private static Path nameServiceQueuePath() {
return root.append("nameServiceQueue");
}
private static Path auditLogPath() {
return root.append("auditLog");
}
private static Path provisionStatePath() {
return root.append("provisioning").append("states");
}
private static Path provisionStatePath(String provisionId) {
return provisionStatePath().append(provisionId);
}
private static Path tenantPath(TenantName name) {
return tenantRoot.append(name.value());
}
private static Path applicationPath(ApplicationId application) {
return applicationRoot.append(application.serializedForm());
}
private static Path instancePath(ApplicationId id) {
return instanceRoot.append(id.serializedForm());
}
private static Path runsPath(ApplicationId id, JobType type) {
return jobRoot.append(id.serializedForm()).append(type.jobName());
}
private static Path lastRunPath(ApplicationId id, JobType type) {
return runsPath(id, type).append("last");
}
private static Path logPath(ApplicationId id, JobType type, long first) {
return runsPath(id, type).append("logs").append(Long.toString(first));
}
private static Path lastLogPath(ApplicationId id, JobType type) {
return runsPath(id, type).append("logs");
}
private static Path controllerPath(String hostname) {
return controllerRoot.append(hostname);
}
private static Path applicationCertificatePath(ApplicationId id) {
return applicationCertificateRoot.append(id.serializedForm());
}
} |
This was removed after 7.67, but was reverted due to Vespa 6 apps: https://github.com/vespa-engine/vespa/pull/10042 | public void createContainer(NodeAgentContext context, ContainerData containerData, ContainerResources containerResources) {
context.log(logger, "Creating container");
Inet6Address ipV6Address = ipAddresses.getIPv6Address(context.node().hostname()).orElseThrow(
() -> new RuntimeException("Unable to find a valid IPv6 address for " + context.node().hostname() +
". Missing an AAAA DNS entry?"));
Docker.CreateContainerCommand command = docker.createContainerCommand(
context.node().wantedDockerImage().get(), context.containerName())
.withHostName(context.node().hostname())
.withResources(containerResources)
.withManagedBy(MANAGER_NAME)
.withUlimit("nofile", 262_144, 262_144)
.withUlimit("nproc", 409_600, 409_600)
.withUlimit("core", -1, -1)
.withAddCapability("SYS_PTRACE")
.withAddCapability("SYS_ADMIN")
.withAddCapability("SYS_NICE");
if (context.node().membership().map(NodeMembership::clusterType).map("content"::equalsIgnoreCase).orElse(false)) {
command.withSecurityOpts("seccomp=unconfined");
}
DockerNetworking networking = context.dockerNetworking();
command.withNetworkMode(networking.getDockerNetworkMode());
if (networking == DockerNetworking.NPT) {
InetAddress ipV6Local = IPAddresses.prefixTranslate(ipV6Address, IPV6_NPT_PREFIX, 8);
command.withIpAddress(ipV6Local);
Optional<InetAddress> ipV4Local = ipAddresses.getIPv4Address(context.node().hostname())
.map(ipV4Address -> IPAddresses.prefixTranslate(ipV4Address, IPV4_NPT_PREFIX, 2));
ipV4Local.ifPresent(command::withIpAddress);
addEtcHosts(containerData, context.node().hostname(), ipV4Local, ipV6Local);
}
addMounts(context, command);
logger.info("Creating new container with args: " + command);
command.create();
} | command.create(); | public void createContainer(NodeAgentContext context, ContainerData containerData, ContainerResources containerResources) {
context.log(logger, "Creating container");
Inet6Address ipV6Address = ipAddresses.getIPv6Address(context.node().hostname()).orElseThrow(
() -> new RuntimeException("Unable to find a valid IPv6 address for " + context.node().hostname() +
". Missing an AAAA DNS entry?"));
Docker.CreateContainerCommand command = docker.createContainerCommand(
context.node().wantedDockerImage().get(), context.containerName())
.withHostName(context.node().hostname())
.withResources(containerResources)
.withManagedBy(MANAGER_NAME)
.withUlimit("nofile", 262_144, 262_144)
.withUlimit("nproc", 409_600, 409_600)
.withUlimit("core", -1, -1)
.withAddCapability("SYS_PTRACE")
.withAddCapability("SYS_ADMIN")
.withAddCapability("SYS_NICE");
if (context.node().membership().map(NodeMembership::clusterType).map("content"::equalsIgnoreCase).orElse(false)) {
command.withSecurityOpts("seccomp=unconfined");
}
DockerNetworking networking = context.dockerNetworking();
command.withNetworkMode(networking.getDockerNetworkMode());
if (networking == DockerNetworking.NPT) {
InetAddress ipV6Local = IPAddresses.prefixTranslate(ipV6Address, IPV6_NPT_PREFIX, 8);
command.withIpAddress(ipV6Local);
Optional<InetAddress> ipV4Local = ipAddresses.getIPv4Address(context.node().hostname())
.map(ipV4Address -> IPAddresses.prefixTranslate(ipV4Address, IPV4_NPT_PREFIX, 2));
ipV4Local.ifPresent(command::withIpAddress);
addEtcHosts(containerData, context.node().hostname(), ipV4Local, ipV6Local);
}
addMounts(context, command);
logger.info("Creating new container with args: " + command);
command.create();
} | class DockerOperationsImpl implements DockerOperations {
private static final Logger logger = Logger.getLogger(DockerOperationsImpl.class.getName());
private static final String MANAGER_NAME = "node-admin";
private static final InetAddress IPV6_NPT_PREFIX = InetAddresses.forString("fd00::");
private static final InetAddress IPV4_NPT_PREFIX = InetAddresses.forString("172.17.0.0");
private final Docker docker;
private final ProcessExecuter processExecuter;
private final IPAddresses ipAddresses;
public DockerOperationsImpl(Docker docker) {
this(docker, new ProcessExecuter(), new IPAddressesImpl());
}
public DockerOperationsImpl(Docker docker, ProcessExecuter processExecuter, IPAddresses ipAddresses) {
this.docker = docker;
this.processExecuter = processExecuter;
this.ipAddresses = ipAddresses;
}
@Override
void addEtcHosts(ContainerData containerData,
String hostname,
Optional<InetAddress> ipV4Local,
InetAddress ipV6Local) {
StringBuilder etcHosts = new StringBuilder(
"
"127.0.0.1\tlocalhost\n" +
"::1\tlocalhost ip6-localhost ip6-loopback\n" +
"fe00::0\tip6-localnet\n" +
"ff00::0\tip6-mcastprefix\n" +
"ff02::1\tip6-allnodes\n" +
"ff02::2\tip6-allrouters\n" +
ipV6Local.getHostAddress() + '\t' + hostname + '\n');
ipV4Local.ifPresent(ipv4 -> etcHosts.append(ipv4.getHostAddress()).append('\t').append(hostname).append('\n'));
containerData.addFile(Paths.get("/etc/hosts"), etcHosts.toString());
}
@Override
public void startContainer(NodeAgentContext context) {
context.log(logger, "Starting container");
docker.startContainer(context.containerName());
}
@Override
public void removeContainer(NodeAgentContext context, Container container) {
if (container.state.isRunning()) {
context.log(logger, "Stopping container");
docker.stopContainer(context.containerName());
}
context.log(logger, "Deleting container");
docker.deleteContainer(context.containerName());
}
@Override
public void updateContainer(NodeAgentContext context, ContainerResources containerResources) {
docker.updateContainer(context.containerName(), containerResources);
}
@Override
public Optional<Container> getContainer(NodeAgentContext context) {
return docker.getContainer(context.containerName());
}
@Override
public boolean pullImageAsyncIfNeeded(DockerImage dockerImage) {
return docker.pullImageAsyncIfNeeded(dockerImage);
}
@Override
public ProcessResult executeCommandInContainerAsRoot(NodeAgentContext context, Long timeoutSeconds, String... command) {
return docker.executeInContainerAsUser(context.containerName(), "root", OptionalLong.of(timeoutSeconds), command);
}
@Override
public ProcessResult executeCommandInContainerAsRoot(NodeAgentContext context, String... command) {
return docker.executeInContainerAsUser(context.containerName(), "root", OptionalLong.empty(), command);
}
@Override
public ProcessResult executeCommandInNetworkNamespace(NodeAgentContext context, String... command) {
int containerPid = docker.getContainer(context.containerName())
.filter(container -> container.state.isRunning())
.orElseThrow(() -> new RuntimeException(
"Found no running container named " + context.containerName().asString()))
.pid;
String[] wrappedCommand = Stream.concat(Stream.of("nsenter",
String.format("--net=/proc/%d/ns/net", containerPid),
"--"),
Stream.of(command))
.toArray(String[]::new);
try {
Pair<Integer, String> result = processExecuter.exec(wrappedCommand);
if (result.getFirst() != 0) {
throw new RuntimeException(String.format(
"Failed to execute %s in network namespace for %s (PID = %d), exit code: %d, output: %s",
Arrays.toString(wrappedCommand), context.containerName().asString(), containerPid, result.getFirst(), result.getSecond()));
}
return new ProcessResult(0, result.getSecond(), "");
} catch (IOException e) {
throw new RuntimeException(String.format("IOException while executing %s in network namespace for %s (PID = %d)",
Arrays.toString(wrappedCommand), context.containerName().asString(), containerPid), e);
}
}
@Override
public void resumeNode(NodeAgentContext context) {
executeNodeCtlInContainer(context, "resume");
}
@Override
public void suspendNode(NodeAgentContext context) {
executeNodeCtlInContainer(context, "suspend");
}
@Override
public void restartVespa(NodeAgentContext context) {
executeNodeCtlInContainer(context, "restart-vespa");
}
@Override
public void startServices(NodeAgentContext context) {
executeNodeCtlInContainer(context, "start");
}
@Override
public void stopServices(NodeAgentContext context) {
executeNodeCtlInContainer(context, "stop");
}
ProcessResult executeNodeCtlInContainer(NodeAgentContext context, String program) {
String[] command = new String[] {context.pathInNodeUnderVespaHome("bin/vespa-nodectl").toString(), program};
ProcessResult result = executeCommandInContainerAsRoot(context, command);
if (!result.isSuccess()) {
throw new RuntimeException("Container " + context.containerName().asString() +
": command " + Arrays.toString(command) + " failed: " + result);
}
return result;
}
@Override
public Optional<ContainerStats> getContainerStats(NodeAgentContext context) {
return docker.getContainerStats(context.containerName());
}
private static void addMounts(NodeAgentContext context, Docker.CreateContainerCommand command) {
Path varLibSia = Paths.get("/var/lib/sia");
List<Path> paths = new ArrayList<>(List.of(
Paths.get("/etc/vespa/flags"),
Paths.get("/etc/yamas-agent"),
Paths.get("/opt/splunkforwarder/var/log"),
Paths.get("/var/log"),
Paths.get("/var/spool/postfix/maildrop"),
context.pathInNodeUnderVespaHome("logs/daemontools_y"),
context.pathInNodeUnderVespaHome("logs/vespa"),
context.pathInNodeUnderVespaHome("logs/yca"),
context.pathInNodeUnderVespaHome("logs/ykeykeyd"),
context.pathInNodeUnderVespaHome("logs/ysar"),
context.pathInNodeUnderVespaHome("tmp"),
context.pathInNodeUnderVespaHome("var/crash"),
context.pathInNodeUnderVespaHome("var/container-data"),
context.pathInNodeUnderVespaHome("var/db/vespa"),
context.pathInNodeUnderVespaHome("var/jdisc_container"),
context.pathInNodeUnderVespaHome("var/vespa"),
context.pathInNodeUnderVespaHome("var/yca"),
context.pathInNodeUnderVespaHome("var/zookeeper")
));
if (context.nodeType() == NodeType.proxy) {
paths.add(context.pathInNodeUnderVespaHome("logs/nginx"));
paths.add(context.pathInNodeUnderVespaHome("var/vespa-hosted/routing"));
} else if (context.nodeType() == NodeType.tenant)
paths.add(varLibSia);
paths.forEach(path -> command.withVolume(context.pathOnHostFromPathInNode(path), path));
if (isInfrastructureHost(context.nodeType()))
command.withSharedVolume(varLibSia, varLibSia);
boolean isMain = context.zone().getSystemName() == SystemName.cd || context.zone().getSystemName() == SystemName.main;
if (isMain && context.nodeType() == NodeType.tenant)
command.withSharedVolume(Paths.get("/var/zpe"), context.pathInNodeUnderVespaHome("var/zpe"));
}
@Override
public boolean noManagedContainersRunning() {
return docker.noManagedContainersRunning(MANAGER_NAME);
}
@Override
public boolean deleteUnusedDockerImages(List<DockerImage> excludes, Duration minImageAgeToDelete) {
return docker.deleteUnusedDockerImages(excludes, minImageAgeToDelete);
}
/** Returns whether given nodeType is a Docker host for infrastructure nodes */
private static boolean isInfrastructureHost(NodeType nodeType) {
return nodeType == NodeType.config ||
nodeType == NodeType.proxy ||
nodeType == NodeType.controller;
}
} | class DockerOperationsImpl implements DockerOperations {
private static final Logger logger = Logger.getLogger(DockerOperationsImpl.class.getName());
private static final String MANAGER_NAME = "node-admin";
private static final InetAddress IPV6_NPT_PREFIX = InetAddresses.forString("fd00::");
private static final InetAddress IPV4_NPT_PREFIX = InetAddresses.forString("172.17.0.0");
private final Docker docker;
private final ProcessExecuter processExecuter;
private final IPAddresses ipAddresses;
public DockerOperationsImpl(Docker docker) {
this(docker, new ProcessExecuter(), new IPAddressesImpl());
}
public DockerOperationsImpl(Docker docker, ProcessExecuter processExecuter, IPAddresses ipAddresses) {
this.docker = docker;
this.processExecuter = processExecuter;
this.ipAddresses = ipAddresses;
}
@Override
void addEtcHosts(ContainerData containerData,
String hostname,
Optional<InetAddress> ipV4Local,
InetAddress ipV6Local) {
StringBuilder etcHosts = new StringBuilder(
"
"127.0.0.1\tlocalhost\n" +
"::1\tlocalhost ip6-localhost ip6-loopback\n" +
"fe00::0\tip6-localnet\n" +
"ff00::0\tip6-mcastprefix\n" +
"ff02::1\tip6-allnodes\n" +
"ff02::2\tip6-allrouters\n" +
ipV6Local.getHostAddress() + '\t' + hostname + '\n');
ipV4Local.ifPresent(ipv4 -> etcHosts.append(ipv4.getHostAddress()).append('\t').append(hostname).append('\n'));
containerData.addFile(Paths.get("/etc/hosts"), etcHosts.toString());
}
@Override
public void startContainer(NodeAgentContext context) {
context.log(logger, "Starting container");
docker.startContainer(context.containerName());
}
@Override
public void removeContainer(NodeAgentContext context, Container container) {
if (container.state.isRunning()) {
context.log(logger, "Stopping container");
docker.stopContainer(context.containerName());
}
context.log(logger, "Deleting container");
docker.deleteContainer(context.containerName());
}
@Override
public void updateContainer(NodeAgentContext context, ContainerResources containerResources) {
docker.updateContainer(context.containerName(), containerResources);
}
@Override
public Optional<Container> getContainer(NodeAgentContext context) {
return docker.getContainer(context.containerName());
}
@Override
public boolean pullImageAsyncIfNeeded(DockerImage dockerImage) {
return docker.pullImageAsyncIfNeeded(dockerImage);
}
@Override
public ProcessResult executeCommandInContainerAsRoot(NodeAgentContext context, Long timeoutSeconds, String... command) {
return docker.executeInContainerAsUser(context.containerName(), "root", OptionalLong.of(timeoutSeconds), command);
}
@Override
public ProcessResult executeCommandInContainerAsRoot(NodeAgentContext context, String... command) {
return docker.executeInContainerAsUser(context.containerName(), "root", OptionalLong.empty(), command);
}
@Override
public ProcessResult executeCommandInNetworkNamespace(NodeAgentContext context, String... command) {
int containerPid = docker.getContainer(context.containerName())
.filter(container -> container.state.isRunning())
.orElseThrow(() -> new RuntimeException(
"Found no running container named " + context.containerName().asString()))
.pid;
String[] wrappedCommand = Stream.concat(Stream.of("nsenter",
String.format("--net=/proc/%d/ns/net", containerPid),
"--"),
Stream.of(command))
.toArray(String[]::new);
try {
Pair<Integer, String> result = processExecuter.exec(wrappedCommand);
if (result.getFirst() != 0) {
throw new RuntimeException(String.format(
"Failed to execute %s in network namespace for %s (PID = %d), exit code: %d, output: %s",
Arrays.toString(wrappedCommand), context.containerName().asString(), containerPid, result.getFirst(), result.getSecond()));
}
return new ProcessResult(0, result.getSecond(), "");
} catch (IOException e) {
throw new RuntimeException(String.format("IOException while executing %s in network namespace for %s (PID = %d)",
Arrays.toString(wrappedCommand), context.containerName().asString(), containerPid), e);
}
}
@Override
public void resumeNode(NodeAgentContext context) {
executeNodeCtlInContainer(context, "resume");
}
@Override
public void suspendNode(NodeAgentContext context) {
executeNodeCtlInContainer(context, "suspend");
}
@Override
public void restartVespa(NodeAgentContext context) {
executeNodeCtlInContainer(context, "restart-vespa");
}
@Override
public void startServices(NodeAgentContext context) {
executeNodeCtlInContainer(context, "start");
}
@Override
public void stopServices(NodeAgentContext context) {
executeNodeCtlInContainer(context, "stop");
}
ProcessResult executeNodeCtlInContainer(NodeAgentContext context, String program) {
String[] command = new String[] {context.pathInNodeUnderVespaHome("bin/vespa-nodectl").toString(), program};
ProcessResult result = executeCommandInContainerAsRoot(context, command);
if (!result.isSuccess()) {
throw new RuntimeException("Container " + context.containerName().asString() +
": command " + Arrays.toString(command) + " failed: " + result);
}
return result;
}
@Override
public Optional<ContainerStats> getContainerStats(NodeAgentContext context) {
return docker.getContainerStats(context.containerName());
}
private static void addMounts(NodeAgentContext context, Docker.CreateContainerCommand command) {
Path varLibSia = Paths.get("/var/lib/sia");
List<Path> paths = new ArrayList<>(List.of(
Paths.get("/etc/vespa/flags"),
Paths.get("/etc/yamas-agent"),
Paths.get("/opt/splunkforwarder/var/log"),
Paths.get("/var/log"),
Paths.get("/var/spool/postfix/maildrop"),
context.pathInNodeUnderVespaHome("logs/daemontools_y"),
context.pathInNodeUnderVespaHome("logs/vespa"),
context.pathInNodeUnderVespaHome("logs/yca"),
context.pathInNodeUnderVespaHome("logs/ykeykeyd"),
context.pathInNodeUnderVespaHome("logs/ysar"),
context.pathInNodeUnderVespaHome("tmp"),
context.pathInNodeUnderVespaHome("var/crash"),
context.pathInNodeUnderVespaHome("var/container-data"),
context.pathInNodeUnderVespaHome("var/db/vespa"),
context.pathInNodeUnderVespaHome("var/jdisc_container"),
context.pathInNodeUnderVespaHome("var/vespa"),
context.pathInNodeUnderVespaHome("var/yca"),
context.pathInNodeUnderVespaHome("var/zookeeper")
));
if (context.nodeType() == NodeType.proxy) {
paths.add(context.pathInNodeUnderVespaHome("logs/nginx"));
paths.add(context.pathInNodeUnderVespaHome("var/vespa-hosted/routing"));
} else if (context.nodeType() == NodeType.tenant)
paths.add(varLibSia);
paths.forEach(path -> command.withVolume(context.pathOnHostFromPathInNode(path), path));
if (isInfrastructureHost(context.nodeType()))
command.withSharedVolume(varLibSia, varLibSia);
boolean isMain = context.zone().getSystemName() == SystemName.cd || context.zone().getSystemName() == SystemName.main;
if (isMain && context.nodeType() == NodeType.tenant)
command.withSharedVolume(Paths.get("/var/zpe"), context.pathInNodeUnderVespaHome("var/zpe"));
}
@Override
public boolean noManagedContainersRunning() {
return docker.noManagedContainersRunning(MANAGER_NAME);
}
@Override
public boolean deleteUnusedDockerImages(List<DockerImage> excludes, Duration minImageAgeToDelete) {
return docker.deleteUnusedDockerImages(excludes, minImageAgeToDelete);
}
/** Returns whether given nodeType is a Docker host for infrastructure nodes */
private static boolean isInfrastructureHost(NodeType nodeType) {
return nodeType == NodeType.config ||
nodeType == NodeType.proxy ||
nodeType == NodeType.controller;
}
} |
Not strictly related to Vespa 6, but was brought back to give time for customers to migrate off, which was a long time ago: https://github.com/vespa-engine/vespa/pull/10039. This directly has been deleted at every container start up since that time, so I dont think any one using it. | private static void addMounts(NodeAgentContext context, Docker.CreateContainerCommand command) {
Path varLibSia = Paths.get("/var/lib/sia");
List<Path> paths = new ArrayList<>(List.of(
Paths.get("/etc/vespa/flags"),
Paths.get("/etc/yamas-agent"),
Paths.get("/opt/splunkforwarder/var/log"),
Paths.get("/var/log"),
Paths.get("/var/spool/postfix/maildrop"),
context.pathInNodeUnderVespaHome("logs/daemontools_y"),
context.pathInNodeUnderVespaHome("logs/vespa"),
context.pathInNodeUnderVespaHome("logs/yca"),
context.pathInNodeUnderVespaHome("logs/ykeykeyd"),
context.pathInNodeUnderVespaHome("logs/ysar"),
context.pathInNodeUnderVespaHome("tmp"),
context.pathInNodeUnderVespaHome("var/crash"),
context.pathInNodeUnderVespaHome("var/container-data"),
context.pathInNodeUnderVespaHome("var/db/vespa"),
context.pathInNodeUnderVespaHome("var/jdisc_container"),
context.pathInNodeUnderVespaHome("var/vespa"),
context.pathInNodeUnderVespaHome("var/yca"),
context.pathInNodeUnderVespaHome("var/zookeeper")
));
if (context.nodeType() == NodeType.proxy) {
paths.add(context.pathInNodeUnderVespaHome("logs/nginx"));
paths.add(context.pathInNodeUnderVespaHome("var/vespa-hosted/routing"));
} else if (context.nodeType() == NodeType.tenant)
paths.add(varLibSia);
paths.forEach(path -> command.withVolume(context.pathOnHostFromPathInNode(path), path));
if (isInfrastructureHost(context.nodeType()))
command.withSharedVolume(varLibSia, varLibSia);
boolean isMain = context.zone().getSystemName() == SystemName.cd || context.zone().getSystemName() == SystemName.main;
if (isMain && context.nodeType() == NodeType.tenant)
command.withSharedVolume(Paths.get("/var/zpe"), context.pathInNodeUnderVespaHome("var/zpe"));
} | paths.forEach(path -> command.withVolume(context.pathOnHostFromPathInNode(path), path)); | private static void addMounts(NodeAgentContext context, Docker.CreateContainerCommand command) {
Path varLibSia = Paths.get("/var/lib/sia");
List<Path> paths = new ArrayList<>(List.of(
Paths.get("/etc/vespa/flags"),
Paths.get("/etc/yamas-agent"),
Paths.get("/opt/splunkforwarder/var/log"),
Paths.get("/var/log"),
Paths.get("/var/spool/postfix/maildrop"),
context.pathInNodeUnderVespaHome("logs/daemontools_y"),
context.pathInNodeUnderVespaHome("logs/vespa"),
context.pathInNodeUnderVespaHome("logs/yca"),
context.pathInNodeUnderVespaHome("logs/ykeykeyd"),
context.pathInNodeUnderVespaHome("logs/ysar"),
context.pathInNodeUnderVespaHome("tmp"),
context.pathInNodeUnderVespaHome("var/crash"),
context.pathInNodeUnderVespaHome("var/container-data"),
context.pathInNodeUnderVespaHome("var/db/vespa"),
context.pathInNodeUnderVespaHome("var/jdisc_container"),
context.pathInNodeUnderVespaHome("var/vespa"),
context.pathInNodeUnderVespaHome("var/yca"),
context.pathInNodeUnderVespaHome("var/zookeeper")
));
if (context.nodeType() == NodeType.proxy) {
paths.add(context.pathInNodeUnderVespaHome("logs/nginx"));
paths.add(context.pathInNodeUnderVespaHome("var/vespa-hosted/routing"));
} else if (context.nodeType() == NodeType.tenant)
paths.add(varLibSia);
paths.forEach(path -> command.withVolume(context.pathOnHostFromPathInNode(path), path));
if (isInfrastructureHost(context.nodeType()))
command.withSharedVolume(varLibSia, varLibSia);
boolean isMain = context.zone().getSystemName() == SystemName.cd || context.zone().getSystemName() == SystemName.main;
if (isMain && context.nodeType() == NodeType.tenant)
command.withSharedVolume(Paths.get("/var/zpe"), context.pathInNodeUnderVespaHome("var/zpe"));
} | class DockerOperationsImpl implements DockerOperations {
private static final Logger logger = Logger.getLogger(DockerOperationsImpl.class.getName());
private static final String MANAGER_NAME = "node-admin";
private static final InetAddress IPV6_NPT_PREFIX = InetAddresses.forString("fd00::");
private static final InetAddress IPV4_NPT_PREFIX = InetAddresses.forString("172.17.0.0");
private final Docker docker;
private final ProcessExecuter processExecuter;
private final IPAddresses ipAddresses;
public DockerOperationsImpl(Docker docker) {
this(docker, new ProcessExecuter(), new IPAddressesImpl());
}
public DockerOperationsImpl(Docker docker, ProcessExecuter processExecuter, IPAddresses ipAddresses) {
this.docker = docker;
this.processExecuter = processExecuter;
this.ipAddresses = ipAddresses;
}
@Override
public void createContainer(NodeAgentContext context, ContainerData containerData, ContainerResources containerResources) {
context.log(logger, "Creating container");
Inet6Address ipV6Address = ipAddresses.getIPv6Address(context.node().hostname()).orElseThrow(
() -> new RuntimeException("Unable to find a valid IPv6 address for " + context.node().hostname() +
". Missing an AAAA DNS entry?"));
Docker.CreateContainerCommand command = docker.createContainerCommand(
context.node().wantedDockerImage().get(), context.containerName())
.withHostName(context.node().hostname())
.withResources(containerResources)
.withManagedBy(MANAGER_NAME)
.withUlimit("nofile", 262_144, 262_144)
.withUlimit("nproc", 409_600, 409_600)
.withUlimit("core", -1, -1)
.withAddCapability("SYS_PTRACE")
.withAddCapability("SYS_ADMIN")
.withAddCapability("SYS_NICE");
if (context.node().membership().map(NodeMembership::clusterType).map("content"::equalsIgnoreCase).orElse(false)) {
command.withSecurityOpts("seccomp=unconfined");
}
DockerNetworking networking = context.dockerNetworking();
command.withNetworkMode(networking.getDockerNetworkMode());
if (networking == DockerNetworking.NPT) {
InetAddress ipV6Local = IPAddresses.prefixTranslate(ipV6Address, IPV6_NPT_PREFIX, 8);
command.withIpAddress(ipV6Local);
Optional<InetAddress> ipV4Local = ipAddresses.getIPv4Address(context.node().hostname())
.map(ipV4Address -> IPAddresses.prefixTranslate(ipV4Address, IPV4_NPT_PREFIX, 2));
ipV4Local.ifPresent(command::withIpAddress);
addEtcHosts(containerData, context.node().hostname(), ipV4Local, ipV6Local);
}
addMounts(context, command);
logger.info("Creating new container with args: " + command);
command.create();
}
void addEtcHosts(ContainerData containerData,
String hostname,
Optional<InetAddress> ipV4Local,
InetAddress ipV6Local) {
StringBuilder etcHosts = new StringBuilder(
"
"127.0.0.1\tlocalhost\n" +
"::1\tlocalhost ip6-localhost ip6-loopback\n" +
"fe00::0\tip6-localnet\n" +
"ff00::0\tip6-mcastprefix\n" +
"ff02::1\tip6-allnodes\n" +
"ff02::2\tip6-allrouters\n" +
ipV6Local.getHostAddress() + '\t' + hostname + '\n');
ipV4Local.ifPresent(ipv4 -> etcHosts.append(ipv4.getHostAddress()).append('\t').append(hostname).append('\n'));
containerData.addFile(Paths.get("/etc/hosts"), etcHosts.toString());
}
@Override
public void startContainer(NodeAgentContext context) {
context.log(logger, "Starting container");
docker.startContainer(context.containerName());
}
@Override
public void removeContainer(NodeAgentContext context, Container container) {
if (container.state.isRunning()) {
context.log(logger, "Stopping container");
docker.stopContainer(context.containerName());
}
context.log(logger, "Deleting container");
docker.deleteContainer(context.containerName());
}
@Override
public void updateContainer(NodeAgentContext context, ContainerResources containerResources) {
docker.updateContainer(context.containerName(), containerResources);
}
@Override
public Optional<Container> getContainer(NodeAgentContext context) {
return docker.getContainer(context.containerName());
}
@Override
public boolean pullImageAsyncIfNeeded(DockerImage dockerImage) {
return docker.pullImageAsyncIfNeeded(dockerImage);
}
@Override
public ProcessResult executeCommandInContainerAsRoot(NodeAgentContext context, Long timeoutSeconds, String... command) {
return docker.executeInContainerAsUser(context.containerName(), "root", OptionalLong.of(timeoutSeconds), command);
}
@Override
public ProcessResult executeCommandInContainerAsRoot(NodeAgentContext context, String... command) {
return docker.executeInContainerAsUser(context.containerName(), "root", OptionalLong.empty(), command);
}
@Override
public ProcessResult executeCommandInNetworkNamespace(NodeAgentContext context, String... command) {
int containerPid = docker.getContainer(context.containerName())
.filter(container -> container.state.isRunning())
.orElseThrow(() -> new RuntimeException(
"Found no running container named " + context.containerName().asString()))
.pid;
String[] wrappedCommand = Stream.concat(Stream.of("nsenter",
String.format("--net=/proc/%d/ns/net", containerPid),
"--"),
Stream.of(command))
.toArray(String[]::new);
try {
Pair<Integer, String> result = processExecuter.exec(wrappedCommand);
if (result.getFirst() != 0) {
throw new RuntimeException(String.format(
"Failed to execute %s in network namespace for %s (PID = %d), exit code: %d, output: %s",
Arrays.toString(wrappedCommand), context.containerName().asString(), containerPid, result.getFirst(), result.getSecond()));
}
return new ProcessResult(0, result.getSecond(), "");
} catch (IOException e) {
throw new RuntimeException(String.format("IOException while executing %s in network namespace for %s (PID = %d)",
Arrays.toString(wrappedCommand), context.containerName().asString(), containerPid), e);
}
}
@Override
public void resumeNode(NodeAgentContext context) {
executeNodeCtlInContainer(context, "resume");
}
@Override
public void suspendNode(NodeAgentContext context) {
executeNodeCtlInContainer(context, "suspend");
}
@Override
public void restartVespa(NodeAgentContext context) {
executeNodeCtlInContainer(context, "restart-vespa");
}
@Override
public void startServices(NodeAgentContext context) {
executeNodeCtlInContainer(context, "start");
}
@Override
public void stopServices(NodeAgentContext context) {
executeNodeCtlInContainer(context, "stop");
}
ProcessResult executeNodeCtlInContainer(NodeAgentContext context, String program) {
String[] command = new String[] {context.pathInNodeUnderVespaHome("bin/vespa-nodectl").toString(), program};
ProcessResult result = executeCommandInContainerAsRoot(context, command);
if (!result.isSuccess()) {
throw new RuntimeException("Container " + context.containerName().asString() +
": command " + Arrays.toString(command) + " failed: " + result);
}
return result;
}
@Override
public Optional<ContainerStats> getContainerStats(NodeAgentContext context) {
return docker.getContainerStats(context.containerName());
}
@Override
public boolean noManagedContainersRunning() {
return docker.noManagedContainersRunning(MANAGER_NAME);
}
@Override
public boolean deleteUnusedDockerImages(List<DockerImage> excludes, Duration minImageAgeToDelete) {
return docker.deleteUnusedDockerImages(excludes, minImageAgeToDelete);
}
/** Returns whether given nodeType is a Docker host for infrastructure nodes */
private static boolean isInfrastructureHost(NodeType nodeType) {
return nodeType == NodeType.config ||
nodeType == NodeType.proxy ||
nodeType == NodeType.controller;
}
} | class DockerOperationsImpl implements DockerOperations {
private static final Logger logger = Logger.getLogger(DockerOperationsImpl.class.getName());
private static final String MANAGER_NAME = "node-admin";
private static final InetAddress IPV6_NPT_PREFIX = InetAddresses.forString("fd00::");
private static final InetAddress IPV4_NPT_PREFIX = InetAddresses.forString("172.17.0.0");
private final Docker docker;
private final ProcessExecuter processExecuter;
private final IPAddresses ipAddresses;
public DockerOperationsImpl(Docker docker) {
this(docker, new ProcessExecuter(), new IPAddressesImpl());
}
public DockerOperationsImpl(Docker docker, ProcessExecuter processExecuter, IPAddresses ipAddresses) {
this.docker = docker;
this.processExecuter = processExecuter;
this.ipAddresses = ipAddresses;
}
@Override
public void createContainer(NodeAgentContext context, ContainerData containerData, ContainerResources containerResources) {
context.log(logger, "Creating container");
Inet6Address ipV6Address = ipAddresses.getIPv6Address(context.node().hostname()).orElseThrow(
() -> new RuntimeException("Unable to find a valid IPv6 address for " + context.node().hostname() +
". Missing an AAAA DNS entry?"));
Docker.CreateContainerCommand command = docker.createContainerCommand(
context.node().wantedDockerImage().get(), context.containerName())
.withHostName(context.node().hostname())
.withResources(containerResources)
.withManagedBy(MANAGER_NAME)
.withUlimit("nofile", 262_144, 262_144)
.withUlimit("nproc", 409_600, 409_600)
.withUlimit("core", -1, -1)
.withAddCapability("SYS_PTRACE")
.withAddCapability("SYS_ADMIN")
.withAddCapability("SYS_NICE");
if (context.node().membership().map(NodeMembership::clusterType).map("content"::equalsIgnoreCase).orElse(false)) {
command.withSecurityOpts("seccomp=unconfined");
}
DockerNetworking networking = context.dockerNetworking();
command.withNetworkMode(networking.getDockerNetworkMode());
if (networking == DockerNetworking.NPT) {
InetAddress ipV6Local = IPAddresses.prefixTranslate(ipV6Address, IPV6_NPT_PREFIX, 8);
command.withIpAddress(ipV6Local);
Optional<InetAddress> ipV4Local = ipAddresses.getIPv4Address(context.node().hostname())
.map(ipV4Address -> IPAddresses.prefixTranslate(ipV4Address, IPV4_NPT_PREFIX, 2));
ipV4Local.ifPresent(command::withIpAddress);
addEtcHosts(containerData, context.node().hostname(), ipV4Local, ipV6Local);
}
addMounts(context, command);
logger.info("Creating new container with args: " + command);
command.create();
}
void addEtcHosts(ContainerData containerData,
String hostname,
Optional<InetAddress> ipV4Local,
InetAddress ipV6Local) {
StringBuilder etcHosts = new StringBuilder(
"
"127.0.0.1\tlocalhost\n" +
"::1\tlocalhost ip6-localhost ip6-loopback\n" +
"fe00::0\tip6-localnet\n" +
"ff00::0\tip6-mcastprefix\n" +
"ff02::1\tip6-allnodes\n" +
"ff02::2\tip6-allrouters\n" +
ipV6Local.getHostAddress() + '\t' + hostname + '\n');
ipV4Local.ifPresent(ipv4 -> etcHosts.append(ipv4.getHostAddress()).append('\t').append(hostname).append('\n'));
containerData.addFile(Paths.get("/etc/hosts"), etcHosts.toString());
}
@Override
public void startContainer(NodeAgentContext context) {
context.log(logger, "Starting container");
docker.startContainer(context.containerName());
}
@Override
public void removeContainer(NodeAgentContext context, Container container) {
if (container.state.isRunning()) {
context.log(logger, "Stopping container");
docker.stopContainer(context.containerName());
}
context.log(logger, "Deleting container");
docker.deleteContainer(context.containerName());
}
@Override
public void updateContainer(NodeAgentContext context, ContainerResources containerResources) {
docker.updateContainer(context.containerName(), containerResources);
}
@Override
public Optional<Container> getContainer(NodeAgentContext context) {
return docker.getContainer(context.containerName());
}
@Override
public boolean pullImageAsyncIfNeeded(DockerImage dockerImage) {
return docker.pullImageAsyncIfNeeded(dockerImage);
}
@Override
public ProcessResult executeCommandInContainerAsRoot(NodeAgentContext context, Long timeoutSeconds, String... command) {
return docker.executeInContainerAsUser(context.containerName(), "root", OptionalLong.of(timeoutSeconds), command);
}
@Override
public ProcessResult executeCommandInContainerAsRoot(NodeAgentContext context, String... command) {
return docker.executeInContainerAsUser(context.containerName(), "root", OptionalLong.empty(), command);
}
@Override
public ProcessResult executeCommandInNetworkNamespace(NodeAgentContext context, String... command) {
int containerPid = docker.getContainer(context.containerName())
.filter(container -> container.state.isRunning())
.orElseThrow(() -> new RuntimeException(
"Found no running container named " + context.containerName().asString()))
.pid;
String[] wrappedCommand = Stream.concat(Stream.of("nsenter",
String.format("--net=/proc/%d/ns/net", containerPid),
"--"),
Stream.of(command))
.toArray(String[]::new);
try {
Pair<Integer, String> result = processExecuter.exec(wrappedCommand);
if (result.getFirst() != 0) {
throw new RuntimeException(String.format(
"Failed to execute %s in network namespace for %s (PID = %d), exit code: %d, output: %s",
Arrays.toString(wrappedCommand), context.containerName().asString(), containerPid, result.getFirst(), result.getSecond()));
}
return new ProcessResult(0, result.getSecond(), "");
} catch (IOException e) {
throw new RuntimeException(String.format("IOException while executing %s in network namespace for %s (PID = %d)",
Arrays.toString(wrappedCommand), context.containerName().asString(), containerPid), e);
}
}
@Override
public void resumeNode(NodeAgentContext context) {
executeNodeCtlInContainer(context, "resume");
}
@Override
public void suspendNode(NodeAgentContext context) {
executeNodeCtlInContainer(context, "suspend");
}
@Override
public void restartVespa(NodeAgentContext context) {
executeNodeCtlInContainer(context, "restart-vespa");
}
@Override
public void startServices(NodeAgentContext context) {
executeNodeCtlInContainer(context, "start");
}
@Override
public void stopServices(NodeAgentContext context) {
executeNodeCtlInContainer(context, "stop");
}
ProcessResult executeNodeCtlInContainer(NodeAgentContext context, String program) {
String[] command = new String[] {context.pathInNodeUnderVespaHome("bin/vespa-nodectl").toString(), program};
ProcessResult result = executeCommandInContainerAsRoot(context, command);
if (!result.isSuccess()) {
throw new RuntimeException("Container " + context.containerName().asString() +
": command " + Arrays.toString(command) + " failed: " + result);
}
return result;
}
@Override
public Optional<ContainerStats> getContainerStats(NodeAgentContext context) {
return docker.getContainerStats(context.containerName());
}
@Override
public boolean noManagedContainersRunning() {
return docker.noManagedContainersRunning(MANAGER_NAME);
}
@Override
public boolean deleteUnusedDockerImages(List<DockerImage> excludes, Duration minImageAgeToDelete) {
return docker.deleteUnusedDockerImages(excludes, minImageAgeToDelete);
}
/** Returns whether given nodeType is a Docker host for infrastructure nodes */
private static boolean isInfrastructureHost(NodeType nodeType) {
return nodeType == NodeType.config ||
nodeType == NodeType.proxy ||
nodeType == NodeType.controller;
}
} |
@hakonhall Need to update your nodes view dashboard | private void updateNodeMetrics(Node node, Map<HostName, List<ServiceInstance>> servicesByHost) {
Metric.Context context;
Optional<Allocation> allocation = node.allocation();
if (allocation.isPresent()) {
ApplicationId applicationId = allocation.get().owner();
context = getContextAt(
"state", node.state().name(),
"host", node.hostname(),
"tenantName", applicationId.tenant().value(),
"applicationId", applicationId.serializedForm().replace(':', '.'),
"app", toApp(applicationId),
"clustertype", allocation.get().membership().cluster().type().name(),
"clusterid", allocation.get().membership().cluster().id().value());
long wantedRestartGeneration = allocation.get().restartGeneration().wanted();
metric.set("wantedRestartGeneration", wantedRestartGeneration, context);
long currentRestartGeneration = allocation.get().restartGeneration().current();
metric.set("currentRestartGeneration", currentRestartGeneration, context);
boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration;
metric.set("wantToRestart", wantToRestart ? 1 : 0, context);
metric.set("retired", allocation.get().membership().retired() ? 1 : 0, context);
Version wantedVersion = allocation.get().membership().cluster().vespaVersion();
double wantedVersionNumber = getVersionAsNumber(wantedVersion);
metric.set("wantedVespaVersion", wantedVersionNumber, context);
Optional<Version> currentVersion = node.status().vespaVersion();
boolean converged = currentVersion.isPresent() &&
currentVersion.get().equals(wantedVersion);
metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context);
} else {
context = getContextAt(
"state", node.state().name(),
"host", node.hostname());
}
Optional<Version> currentVersion = node.status().vespaVersion();
if (currentVersion.isPresent()) {
double currentVersionNumber = getVersionAsNumber(currentVersion.get());
metric.set("currentVespaVersion", currentVersionNumber, context);
}
long wantedRebootGeneration = node.status().reboot().wanted();
metric.set("wantedRebootGeneration", wantedRebootGeneration, context);
long currentRebootGeneration = node.status().reboot().current();
metric.set("currentRebootGeneration", currentRebootGeneration, context);
boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration;
metric.set("wantToReboot", wantToReboot ? 1 : 0, context);
metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context);
metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context);
metric.set("failReport", NodeFailer.reasonsToFailParentHost(node).isEmpty() ? 0 : 1, context);
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN ? 1 : 0)
.ifPresent(allowedToBeDown -> metric.set("allowedToBeDown", allowedToBeDown, context));
long numberOfServices;
HostName hostName = new HostName(node.hostname());
List<ServiceInstance> services = servicesByHost.get(hostName);
if (services == null) {
numberOfServices = 0;
} else {
Map<ServiceStatus, Long> servicesCount = services.stream().collect(
Collectors.groupingBy(ServiceInstance::serviceStatus, Collectors.counting()));
numberOfServices = servicesCount.values().stream().mapToLong(Long::longValue).sum();
metric.set(
"numberOfServicesUp",
servicesCount.getOrDefault(ServiceStatus.UP, 0L),
context);
metric.set(
"numberOfServicesNotChecked",
servicesCount.getOrDefault(ServiceStatus.NOT_CHECKED, 0L),
context);
long numberOfServicesDown = servicesCount.getOrDefault(ServiceStatus.DOWN, 0L);
metric.set("numberOfServicesDown", numberOfServicesDown, context);
metric.set("someServicesDown", (numberOfServicesDown > 0 ? 1 : 0), context);
boolean badNode = NodeFailer.badNode(services);
metric.set("nodeFailerBadNode", (badNode ? 1 : 0), context);
boolean nodeDownInNodeRepo = node.history().event(History.Event.Type.down).isPresent();
metric.set("downInNodeRepo", (nodeDownInNodeRepo ? 1 : 0), context);
}
metric.set("numberOfServices", numberOfServices, context);
} | metric.set("failReport", NodeFailer.reasonsToFailParentHost(node).isEmpty() ? 0 : 1, context); | private void updateNodeMetrics(Node node, Map<HostName, List<ServiceInstance>> servicesByHost) {
Metric.Context context;
Optional<Allocation> allocation = node.allocation();
if (allocation.isPresent()) {
ApplicationId applicationId = allocation.get().owner();
context = getContextAt(
"state", node.state().name(),
"host", node.hostname(),
"tenantName", applicationId.tenant().value(),
"applicationId", applicationId.serializedForm().replace(':', '.'),
"app", toApp(applicationId),
"clustertype", allocation.get().membership().cluster().type().name(),
"clusterid", allocation.get().membership().cluster().id().value());
long wantedRestartGeneration = allocation.get().restartGeneration().wanted();
metric.set("wantedRestartGeneration", wantedRestartGeneration, context);
long currentRestartGeneration = allocation.get().restartGeneration().current();
metric.set("currentRestartGeneration", currentRestartGeneration, context);
boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration;
metric.set("wantToRestart", wantToRestart ? 1 : 0, context);
metric.set("retired", allocation.get().membership().retired() ? 1 : 0, context);
Version wantedVersion = allocation.get().membership().cluster().vespaVersion();
double wantedVersionNumber = getVersionAsNumber(wantedVersion);
metric.set("wantedVespaVersion", wantedVersionNumber, context);
Optional<Version> currentVersion = node.status().vespaVersion();
boolean converged = currentVersion.isPresent() &&
currentVersion.get().equals(wantedVersion);
metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context);
} else {
context = getContextAt(
"state", node.state().name(),
"host", node.hostname());
}
Optional<Version> currentVersion = node.status().vespaVersion();
if (currentVersion.isPresent()) {
double currentVersionNumber = getVersionAsNumber(currentVersion.get());
metric.set("currentVespaVersion", currentVersionNumber, context);
}
long wantedRebootGeneration = node.status().reboot().wanted();
metric.set("wantedRebootGeneration", wantedRebootGeneration, context);
long currentRebootGeneration = node.status().reboot().current();
metric.set("currentRebootGeneration", currentRebootGeneration, context);
boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration;
metric.set("wantToReboot", wantToReboot ? 1 : 0, context);
metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context);
metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context);
metric.set("failReport", NodeFailer.reasonsToFailParentHost(node).isEmpty() ? 0 : 1, context);
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN ? 1 : 0)
.ifPresent(allowedToBeDown -> metric.set("allowedToBeDown", allowedToBeDown, context));
long numberOfServices;
HostName hostName = new HostName(node.hostname());
List<ServiceInstance> services = servicesByHost.get(hostName);
if (services == null) {
numberOfServices = 0;
} else {
Map<ServiceStatus, Long> servicesCount = services.stream().collect(
Collectors.groupingBy(ServiceInstance::serviceStatus, Collectors.counting()));
numberOfServices = servicesCount.values().stream().mapToLong(Long::longValue).sum();
metric.set(
"numberOfServicesUp",
servicesCount.getOrDefault(ServiceStatus.UP, 0L),
context);
metric.set(
"numberOfServicesNotChecked",
servicesCount.getOrDefault(ServiceStatus.NOT_CHECKED, 0L),
context);
long numberOfServicesDown = servicesCount.getOrDefault(ServiceStatus.DOWN, 0L);
metric.set("numberOfServicesDown", numberOfServicesDown, context);
metric.set("someServicesDown", (numberOfServicesDown > 0 ? 1 : 0), context);
boolean badNode = NodeFailer.badNode(services);
metric.set("nodeFailerBadNode", (badNode ? 1 : 0), context);
boolean nodeDownInNodeRepo = node.history().event(History.Event.Type.down).isPresent();
metric.set("downInNodeRepo", (nodeDownInNodeRepo ? 1 : 0), context);
}
metric.set("numberOfServices", numberOfServices, context);
} | class MetricsReporter extends Maintainer {
private final Metric metric;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final ServiceMonitor serviceMonitor;
private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>();
private final Supplier<Integer> pendingRedeploymentsSupplier;
MetricsReporter(NodeRepository nodeRepository,
Metric metric,
Orchestrator orchestrator,
ServiceMonitor serviceMonitor,
Supplier<Integer> pendingRedeploymentsSupplier,
Duration interval) {
super(nodeRepository, interval);
this.metric = metric;
this.orchestrator = orchestrator.getNodeStatuses();
this.serviceMonitor = serviceMonitor;
this.pendingRedeploymentsSupplier = pendingRedeploymentsSupplier;
}
@Override
public void maintain() {
NodeList nodes = nodeRepository().list();
Map<HostName, List<ServiceInstance>> servicesByHost =
serviceMonitor.getServiceModelSnapshot().getServiceInstancesByHostName();
nodes.forEach(node -> updateNodeMetrics(node, servicesByHost));
updateStateMetrics(nodes);
updateMaintenanceMetrics();
updateDockerMetrics(nodes);
}
private void updateMaintenanceMetrics() {
metric.set("hostedVespa.pendingRedeployments", pendingRedeploymentsSupplier.get(), null);
}
private static String toApp(ApplicationId applicationId) {
return applicationId.application().value() + "." + applicationId.instance().value();
}
/**
* A version 6.163.20 will be returned as a number 163.020. The major
* version can normally be inferred. As long as the micro version stays
* below 1000 these numbers sort like Version.
*/
private static double getVersionAsNumber(Version version) {
return version.getMinor() + version.getMicro() / 1000.0;
}
private Metric.Context getContextAt(String... point) {
if (point.length % 2 != 0)
throw new IllegalArgumentException("Dimension specification comes in pairs");
Map<String, String> dimensions = new HashMap<>();
for (int i = 0; i < point.length; i += 2) {
dimensions.put(point[i], point[i + 1]);
}
return contextMap.computeIfAbsent(dimensions, metric::createContext);
}
private void updateStateMetrics(NodeList nodes) {
Map<Node.State, List<Node>> nodesByState = nodes.nodeType(NodeType.tenant).asList().stream()
.collect(Collectors.groupingBy(Node::state));
for (Node.State state : Node.State.values()) {
List<Node> nodesInState = nodesByState.getOrDefault(state, List.of());
metric.set("hostedVespa." + state.name() + "Hosts", nodesInState.size(), null);
}
}
private void updateDockerMetrics(NodeList nodes) {
NodeResources totalCapacity = getCapacityTotal(nodes);
metric.set("hostedVespa.docker.totalCapacityCpu", totalCapacity.vcpu(), null);
metric.set("hostedVespa.docker.totalCapacityMem", totalCapacity.memoryGb(), null);
metric.set("hostedVespa.docker.totalCapacityDisk", totalCapacity.diskGb(), null);
NodeResources totalFreeCapacity = getFreeCapacityTotal(nodes);
metric.set("hostedVespa.docker.freeCapacityCpu", totalFreeCapacity.vcpu(), null);
metric.set("hostedVespa.docker.freeCapacityMem", totalFreeCapacity.memoryGb(), null);
metric.set("hostedVespa.docker.freeCapacityDisk", totalFreeCapacity.diskGb(), null);
}
private static NodeResources getCapacityTotal(NodeList nodes) {
return nodes.nodeType(NodeType.host).asList().stream()
.map(host -> host.flavor().resources())
.map(resources -> resources.withDiskSpeed(any))
.reduce(new NodeResources(0, 0, 0, 0, any), NodeResources::add);
}
private static NodeResources getFreeCapacityTotal(NodeList nodes) {
return nodes.nodeType(NodeType.host).asList().stream()
.map(n -> freeCapacityOf(nodes, n))
.map(resources -> resources.withDiskSpeed(any))
.reduce(new NodeResources(0, 0, 0, 0, any), NodeResources::add);
}
private static NodeResources freeCapacityOf(NodeList nodes, Node dockerHost) {
return nodes.childrenOf(dockerHost).asList().stream()
.map(node -> node.flavor().resources().withDiskSpeed(any))
.reduce(dockerHost.flavor().resources().withDiskSpeed(any), NodeResources::subtract);
}
} | class MetricsReporter extends Maintainer {
private final Metric metric;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final ServiceMonitor serviceMonitor;
private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>();
private final Supplier<Integer> pendingRedeploymentsSupplier;
MetricsReporter(NodeRepository nodeRepository,
Metric metric,
Orchestrator orchestrator,
ServiceMonitor serviceMonitor,
Supplier<Integer> pendingRedeploymentsSupplier,
Duration interval) {
super(nodeRepository, interval);
this.metric = metric;
this.orchestrator = orchestrator.getNodeStatuses();
this.serviceMonitor = serviceMonitor;
this.pendingRedeploymentsSupplier = pendingRedeploymentsSupplier;
}
@Override
public void maintain() {
NodeList nodes = nodeRepository().list();
Map<HostName, List<ServiceInstance>> servicesByHost =
serviceMonitor.getServiceModelSnapshot().getServiceInstancesByHostName();
nodes.forEach(node -> updateNodeMetrics(node, servicesByHost));
updateStateMetrics(nodes);
updateMaintenanceMetrics();
updateDockerMetrics(nodes);
}
private void updateMaintenanceMetrics() {
metric.set("hostedVespa.pendingRedeployments", pendingRedeploymentsSupplier.get(), null);
}
private static String toApp(ApplicationId applicationId) {
return applicationId.application().value() + "." + applicationId.instance().value();
}
/**
* A version 6.163.20 will be returned as a number 163.020. The major
* version can normally be inferred. As long as the micro version stays
* below 1000 these numbers sort like Version.
*/
private static double getVersionAsNumber(Version version) {
return version.getMinor() + version.getMicro() / 1000.0;
}
private Metric.Context getContextAt(String... point) {
if (point.length % 2 != 0)
throw new IllegalArgumentException("Dimension specification comes in pairs");
Map<String, String> dimensions = new HashMap<>();
for (int i = 0; i < point.length; i += 2) {
dimensions.put(point[i], point[i + 1]);
}
return contextMap.computeIfAbsent(dimensions, metric::createContext);
}
private void updateStateMetrics(NodeList nodes) {
Map<Node.State, List<Node>> nodesByState = nodes.nodeType(NodeType.tenant).asList().stream()
.collect(Collectors.groupingBy(Node::state));
for (Node.State state : Node.State.values()) {
List<Node> nodesInState = nodesByState.getOrDefault(state, List.of());
metric.set("hostedVespa." + state.name() + "Hosts", nodesInState.size(), null);
}
}
private void updateDockerMetrics(NodeList nodes) {
NodeResources totalCapacity = getCapacityTotal(nodes);
metric.set("hostedVespa.docker.totalCapacityCpu", totalCapacity.vcpu(), null);
metric.set("hostedVespa.docker.totalCapacityMem", totalCapacity.memoryGb(), null);
metric.set("hostedVespa.docker.totalCapacityDisk", totalCapacity.diskGb(), null);
NodeResources totalFreeCapacity = getFreeCapacityTotal(nodes);
metric.set("hostedVespa.docker.freeCapacityCpu", totalFreeCapacity.vcpu(), null);
metric.set("hostedVespa.docker.freeCapacityMem", totalFreeCapacity.memoryGb(), null);
metric.set("hostedVespa.docker.freeCapacityDisk", totalFreeCapacity.diskGb(), null);
}
private static NodeResources getCapacityTotal(NodeList nodes) {
return nodes.nodeType(NodeType.host).asList().stream()
.map(host -> host.flavor().resources())
.map(resources -> resources.withDiskSpeed(any))
.reduce(new NodeResources(0, 0, 0, 0, any), NodeResources::add);
}
private static NodeResources getFreeCapacityTotal(NodeList nodes) {
return nodes.nodeType(NodeType.host).asList().stream()
.map(n -> freeCapacityOf(nodes, n))
.map(resources -> resources.withDiskSpeed(any))
.reduce(new NodeResources(0, 0, 0, 0, any), NodeResources::add);
}
private static NodeResources freeCapacityOf(NodeList nodes, Node dockerHost) {
return nodes.childrenOf(dockerHost).asList().stream()
.map(node -> node.flavor().resources().withDiskSpeed(any))
.reduce(dockerHost.flavor().resources().withDiskSpeed(any), NodeResources::subtract);
}
} |
👍 | private void updateNodeMetrics(Node node, Map<HostName, List<ServiceInstance>> servicesByHost) {
Metric.Context context;
Optional<Allocation> allocation = node.allocation();
if (allocation.isPresent()) {
ApplicationId applicationId = allocation.get().owner();
context = getContextAt(
"state", node.state().name(),
"host", node.hostname(),
"tenantName", applicationId.tenant().value(),
"applicationId", applicationId.serializedForm().replace(':', '.'),
"app", toApp(applicationId),
"clustertype", allocation.get().membership().cluster().type().name(),
"clusterid", allocation.get().membership().cluster().id().value());
long wantedRestartGeneration = allocation.get().restartGeneration().wanted();
metric.set("wantedRestartGeneration", wantedRestartGeneration, context);
long currentRestartGeneration = allocation.get().restartGeneration().current();
metric.set("currentRestartGeneration", currentRestartGeneration, context);
boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration;
metric.set("wantToRestart", wantToRestart ? 1 : 0, context);
metric.set("retired", allocation.get().membership().retired() ? 1 : 0, context);
Version wantedVersion = allocation.get().membership().cluster().vespaVersion();
double wantedVersionNumber = getVersionAsNumber(wantedVersion);
metric.set("wantedVespaVersion", wantedVersionNumber, context);
Optional<Version> currentVersion = node.status().vespaVersion();
boolean converged = currentVersion.isPresent() &&
currentVersion.get().equals(wantedVersion);
metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context);
} else {
context = getContextAt(
"state", node.state().name(),
"host", node.hostname());
}
Optional<Version> currentVersion = node.status().vespaVersion();
if (currentVersion.isPresent()) {
double currentVersionNumber = getVersionAsNumber(currentVersion.get());
metric.set("currentVespaVersion", currentVersionNumber, context);
}
long wantedRebootGeneration = node.status().reboot().wanted();
metric.set("wantedRebootGeneration", wantedRebootGeneration, context);
long currentRebootGeneration = node.status().reboot().current();
metric.set("currentRebootGeneration", currentRebootGeneration, context);
boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration;
metric.set("wantToReboot", wantToReboot ? 1 : 0, context);
metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context);
metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context);
metric.set("failReport", NodeFailer.reasonsToFailParentHost(node).isEmpty() ? 0 : 1, context);
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN ? 1 : 0)
.ifPresent(allowedToBeDown -> metric.set("allowedToBeDown", allowedToBeDown, context));
long numberOfServices;
HostName hostName = new HostName(node.hostname());
List<ServiceInstance> services = servicesByHost.get(hostName);
if (services == null) {
numberOfServices = 0;
} else {
Map<ServiceStatus, Long> servicesCount = services.stream().collect(
Collectors.groupingBy(ServiceInstance::serviceStatus, Collectors.counting()));
numberOfServices = servicesCount.values().stream().mapToLong(Long::longValue).sum();
metric.set(
"numberOfServicesUp",
servicesCount.getOrDefault(ServiceStatus.UP, 0L),
context);
metric.set(
"numberOfServicesNotChecked",
servicesCount.getOrDefault(ServiceStatus.NOT_CHECKED, 0L),
context);
long numberOfServicesDown = servicesCount.getOrDefault(ServiceStatus.DOWN, 0L);
metric.set("numberOfServicesDown", numberOfServicesDown, context);
metric.set("someServicesDown", (numberOfServicesDown > 0 ? 1 : 0), context);
boolean badNode = NodeFailer.badNode(services);
metric.set("nodeFailerBadNode", (badNode ? 1 : 0), context);
boolean nodeDownInNodeRepo = node.history().event(History.Event.Type.down).isPresent();
metric.set("downInNodeRepo", (nodeDownInNodeRepo ? 1 : 0), context);
}
metric.set("numberOfServices", numberOfServices, context);
} | metric.set("failReport", NodeFailer.reasonsToFailParentHost(node).isEmpty() ? 0 : 1, context); | private void updateNodeMetrics(Node node, Map<HostName, List<ServiceInstance>> servicesByHost) {
Metric.Context context;
Optional<Allocation> allocation = node.allocation();
if (allocation.isPresent()) {
ApplicationId applicationId = allocation.get().owner();
context = getContextAt(
"state", node.state().name(),
"host", node.hostname(),
"tenantName", applicationId.tenant().value(),
"applicationId", applicationId.serializedForm().replace(':', '.'),
"app", toApp(applicationId),
"clustertype", allocation.get().membership().cluster().type().name(),
"clusterid", allocation.get().membership().cluster().id().value());
long wantedRestartGeneration = allocation.get().restartGeneration().wanted();
metric.set("wantedRestartGeneration", wantedRestartGeneration, context);
long currentRestartGeneration = allocation.get().restartGeneration().current();
metric.set("currentRestartGeneration", currentRestartGeneration, context);
boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration;
metric.set("wantToRestart", wantToRestart ? 1 : 0, context);
metric.set("retired", allocation.get().membership().retired() ? 1 : 0, context);
Version wantedVersion = allocation.get().membership().cluster().vespaVersion();
double wantedVersionNumber = getVersionAsNumber(wantedVersion);
metric.set("wantedVespaVersion", wantedVersionNumber, context);
Optional<Version> currentVersion = node.status().vespaVersion();
boolean converged = currentVersion.isPresent() &&
currentVersion.get().equals(wantedVersion);
metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context);
} else {
context = getContextAt(
"state", node.state().name(),
"host", node.hostname());
}
Optional<Version> currentVersion = node.status().vespaVersion();
if (currentVersion.isPresent()) {
double currentVersionNumber = getVersionAsNumber(currentVersion.get());
metric.set("currentVespaVersion", currentVersionNumber, context);
}
long wantedRebootGeneration = node.status().reboot().wanted();
metric.set("wantedRebootGeneration", wantedRebootGeneration, context);
long currentRebootGeneration = node.status().reboot().current();
metric.set("currentRebootGeneration", currentRebootGeneration, context);
boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration;
metric.set("wantToReboot", wantToReboot ? 1 : 0, context);
metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context);
metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context);
metric.set("failReport", NodeFailer.reasonsToFailParentHost(node).isEmpty() ? 0 : 1, context);
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN ? 1 : 0)
.ifPresent(allowedToBeDown -> metric.set("allowedToBeDown", allowedToBeDown, context));
long numberOfServices;
HostName hostName = new HostName(node.hostname());
List<ServiceInstance> services = servicesByHost.get(hostName);
if (services == null) {
numberOfServices = 0;
} else {
Map<ServiceStatus, Long> servicesCount = services.stream().collect(
Collectors.groupingBy(ServiceInstance::serviceStatus, Collectors.counting()));
numberOfServices = servicesCount.values().stream().mapToLong(Long::longValue).sum();
metric.set(
"numberOfServicesUp",
servicesCount.getOrDefault(ServiceStatus.UP, 0L),
context);
metric.set(
"numberOfServicesNotChecked",
servicesCount.getOrDefault(ServiceStatus.NOT_CHECKED, 0L),
context);
long numberOfServicesDown = servicesCount.getOrDefault(ServiceStatus.DOWN, 0L);
metric.set("numberOfServicesDown", numberOfServicesDown, context);
metric.set("someServicesDown", (numberOfServicesDown > 0 ? 1 : 0), context);
boolean badNode = NodeFailer.badNode(services);
metric.set("nodeFailerBadNode", (badNode ? 1 : 0), context);
boolean nodeDownInNodeRepo = node.history().event(History.Event.Type.down).isPresent();
metric.set("downInNodeRepo", (nodeDownInNodeRepo ? 1 : 0), context);
}
metric.set("numberOfServices", numberOfServices, context);
} | class MetricsReporter extends Maintainer {
private final Metric metric;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final ServiceMonitor serviceMonitor;
private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>();
private final Supplier<Integer> pendingRedeploymentsSupplier;
MetricsReporter(NodeRepository nodeRepository,
Metric metric,
Orchestrator orchestrator,
ServiceMonitor serviceMonitor,
Supplier<Integer> pendingRedeploymentsSupplier,
Duration interval) {
super(nodeRepository, interval);
this.metric = metric;
this.orchestrator = orchestrator.getNodeStatuses();
this.serviceMonitor = serviceMonitor;
this.pendingRedeploymentsSupplier = pendingRedeploymentsSupplier;
}
@Override
public void maintain() {
NodeList nodes = nodeRepository().list();
Map<HostName, List<ServiceInstance>> servicesByHost =
serviceMonitor.getServiceModelSnapshot().getServiceInstancesByHostName();
nodes.forEach(node -> updateNodeMetrics(node, servicesByHost));
updateStateMetrics(nodes);
updateMaintenanceMetrics();
updateDockerMetrics(nodes);
}
private void updateMaintenanceMetrics() {
metric.set("hostedVespa.pendingRedeployments", pendingRedeploymentsSupplier.get(), null);
}
private static String toApp(ApplicationId applicationId) {
return applicationId.application().value() + "." + applicationId.instance().value();
}
/**
* A version 6.163.20 will be returned as a number 163.020. The major
* version can normally be inferred. As long as the micro version stays
* below 1000 these numbers sort like Version.
*/
private static double getVersionAsNumber(Version version) {
return version.getMinor() + version.getMicro() / 1000.0;
}
private Metric.Context getContextAt(String... point) {
if (point.length % 2 != 0)
throw new IllegalArgumentException("Dimension specification comes in pairs");
Map<String, String> dimensions = new HashMap<>();
for (int i = 0; i < point.length; i += 2) {
dimensions.put(point[i], point[i + 1]);
}
return contextMap.computeIfAbsent(dimensions, metric::createContext);
}
private void updateStateMetrics(NodeList nodes) {
Map<Node.State, List<Node>> nodesByState = nodes.nodeType(NodeType.tenant).asList().stream()
.collect(Collectors.groupingBy(Node::state));
for (Node.State state : Node.State.values()) {
List<Node> nodesInState = nodesByState.getOrDefault(state, List.of());
metric.set("hostedVespa." + state.name() + "Hosts", nodesInState.size(), null);
}
}
private void updateDockerMetrics(NodeList nodes) {
NodeResources totalCapacity = getCapacityTotal(nodes);
metric.set("hostedVespa.docker.totalCapacityCpu", totalCapacity.vcpu(), null);
metric.set("hostedVespa.docker.totalCapacityMem", totalCapacity.memoryGb(), null);
metric.set("hostedVespa.docker.totalCapacityDisk", totalCapacity.diskGb(), null);
NodeResources totalFreeCapacity = getFreeCapacityTotal(nodes);
metric.set("hostedVespa.docker.freeCapacityCpu", totalFreeCapacity.vcpu(), null);
metric.set("hostedVespa.docker.freeCapacityMem", totalFreeCapacity.memoryGb(), null);
metric.set("hostedVespa.docker.freeCapacityDisk", totalFreeCapacity.diskGb(), null);
}
private static NodeResources getCapacityTotal(NodeList nodes) {
return nodes.nodeType(NodeType.host).asList().stream()
.map(host -> host.flavor().resources())
.map(resources -> resources.withDiskSpeed(any))
.reduce(new NodeResources(0, 0, 0, 0, any), NodeResources::add);
}
private static NodeResources getFreeCapacityTotal(NodeList nodes) {
return nodes.nodeType(NodeType.host).asList().stream()
.map(n -> freeCapacityOf(nodes, n))
.map(resources -> resources.withDiskSpeed(any))
.reduce(new NodeResources(0, 0, 0, 0, any), NodeResources::add);
}
private static NodeResources freeCapacityOf(NodeList nodes, Node dockerHost) {
return nodes.childrenOf(dockerHost).asList().stream()
.map(node -> node.flavor().resources().withDiskSpeed(any))
.reduce(dockerHost.flavor().resources().withDiskSpeed(any), NodeResources::subtract);
}
} | class MetricsReporter extends Maintainer {
private final Metric metric;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final ServiceMonitor serviceMonitor;
private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>();
private final Supplier<Integer> pendingRedeploymentsSupplier;
MetricsReporter(NodeRepository nodeRepository,
Metric metric,
Orchestrator orchestrator,
ServiceMonitor serviceMonitor,
Supplier<Integer> pendingRedeploymentsSupplier,
Duration interval) {
super(nodeRepository, interval);
this.metric = metric;
this.orchestrator = orchestrator.getNodeStatuses();
this.serviceMonitor = serviceMonitor;
this.pendingRedeploymentsSupplier = pendingRedeploymentsSupplier;
}
@Override
public void maintain() {
NodeList nodes = nodeRepository().list();
Map<HostName, List<ServiceInstance>> servicesByHost =
serviceMonitor.getServiceModelSnapshot().getServiceInstancesByHostName();
nodes.forEach(node -> updateNodeMetrics(node, servicesByHost));
updateStateMetrics(nodes);
updateMaintenanceMetrics();
updateDockerMetrics(nodes);
}
private void updateMaintenanceMetrics() {
metric.set("hostedVespa.pendingRedeployments", pendingRedeploymentsSupplier.get(), null);
}
private static String toApp(ApplicationId applicationId) {
return applicationId.application().value() + "." + applicationId.instance().value();
}
/**
* A version 6.163.20 will be returned as a number 163.020. The major
* version can normally be inferred. As long as the micro version stays
* below 1000 these numbers sort like Version.
*/
private static double getVersionAsNumber(Version version) {
return version.getMinor() + version.getMicro() / 1000.0;
}
private Metric.Context getContextAt(String... point) {
if (point.length % 2 != 0)
throw new IllegalArgumentException("Dimension specification comes in pairs");
Map<String, String> dimensions = new HashMap<>();
for (int i = 0; i < point.length; i += 2) {
dimensions.put(point[i], point[i + 1]);
}
return contextMap.computeIfAbsent(dimensions, metric::createContext);
}
private void updateStateMetrics(NodeList nodes) {
Map<Node.State, List<Node>> nodesByState = nodes.nodeType(NodeType.tenant).asList().stream()
.collect(Collectors.groupingBy(Node::state));
for (Node.State state : Node.State.values()) {
List<Node> nodesInState = nodesByState.getOrDefault(state, List.of());
metric.set("hostedVespa." + state.name() + "Hosts", nodesInState.size(), null);
}
}
private void updateDockerMetrics(NodeList nodes) {
NodeResources totalCapacity = getCapacityTotal(nodes);
metric.set("hostedVespa.docker.totalCapacityCpu", totalCapacity.vcpu(), null);
metric.set("hostedVespa.docker.totalCapacityMem", totalCapacity.memoryGb(), null);
metric.set("hostedVespa.docker.totalCapacityDisk", totalCapacity.diskGb(), null);
NodeResources totalFreeCapacity = getFreeCapacityTotal(nodes);
metric.set("hostedVespa.docker.freeCapacityCpu", totalFreeCapacity.vcpu(), null);
metric.set("hostedVespa.docker.freeCapacityMem", totalFreeCapacity.memoryGb(), null);
metric.set("hostedVespa.docker.freeCapacityDisk", totalFreeCapacity.diskGb(), null);
}
private static NodeResources getCapacityTotal(NodeList nodes) {
return nodes.nodeType(NodeType.host).asList().stream()
.map(host -> host.flavor().resources())
.map(resources -> resources.withDiskSpeed(any))
.reduce(new NodeResources(0, 0, 0, 0, any), NodeResources::add);
}
private static NodeResources getFreeCapacityTotal(NodeList nodes) {
return nodes.nodeType(NodeType.host).asList().stream()
.map(n -> freeCapacityOf(nodes, n))
.map(resources -> resources.withDiskSpeed(any))
.reduce(new NodeResources(0, 0, 0, 0, any), NodeResources::add);
}
private static NodeResources freeCapacityOf(NodeList nodes, Node dockerHost) {
return nodes.childrenOf(dockerHost).asList().stream()
.map(node -> node.flavor().resources().withDiskSpeed(any))
.reduce(dockerHost.flavor().resources().withDiskSpeed(any), NodeResources::subtract);
}
} |
Please consider "{" on one-line if statements. | public void getConfig(DispatchConfig.Builder builder) {
for (SearchNode node : getSearchNodes()) {
DispatchConfig.Node.Builder nodeBuilder = new DispatchConfig.Node.Builder();
nodeBuilder.key(node.getDistributionKey());
nodeBuilder.group(node.getNodeSpec().groupIndex());
nodeBuilder.host(node.getHostName());
nodeBuilder.port(node.getRpcPort());
nodeBuilder.fs4port(node.getDispatchPort());
builder.node(nodeBuilder);
}
if (useAdaptiveDispatch)
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
if (tuning.dispatch.minActiveDocsCoverage != null)
builder.minActivedocsPercentage(tuning.dispatch.minActiveDocsCoverage);
if (tuning.dispatch.minGroupCoverage != null)
builder.minGroupCoverage(tuning.dispatch.minGroupCoverage);
if (tuning.dispatch.policy != null) {
switch (tuning.dispatch.policy) {
case ADAPTIVE:
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
break;
case ROUNDROBIN:
builder.distributionPolicy(DistributionPolicy.ROUNDROBIN);
break;
}
}
if (tuning.dispatch.maxHitsPerPartition != null)
builder.maxHitsPerNode(tuning.dispatch.maxHitsPerPartition);
builder.maxNodesDownPerGroup(rootDispatch.getMaxNodesDownPerFixedRow());
builder.useLocalNode(tuning.dispatch.useLocalNode);
builder.searchableCopies(rootDispatch.getSearchableCopies());
if (searchCoverage != null) {
if (searchCoverage.getMinimum() != null)
builder.minSearchCoverage(searchCoverage.getMinimum() * 100.0);
if (searchCoverage.getMinWaitAfterCoverageFactor() != null)
builder.minWaitAfterCoverageFactor(searchCoverage.getMinWaitAfterCoverageFactor());
if (searchCoverage.getMaxWaitAfterCoverageFactor() != null)
builder.maxWaitAfterCoverageFactor(searchCoverage.getMaxWaitAfterCoverageFactor());
}
} | if (useAdaptiveDispatch) | public void getConfig(DispatchConfig.Builder builder) {
for (SearchNode node : getSearchNodes()) {
DispatchConfig.Node.Builder nodeBuilder = new DispatchConfig.Node.Builder();
nodeBuilder.key(node.getDistributionKey());
nodeBuilder.group(node.getNodeSpec().groupIndex());
nodeBuilder.host(node.getHostName());
nodeBuilder.port(node.getRpcPort());
nodeBuilder.fs4port(node.getDispatchPort());
builder.node(nodeBuilder);
}
if (useAdaptiveDispatch)
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
if (tuning.dispatch.minActiveDocsCoverage != null)
builder.minActivedocsPercentage(tuning.dispatch.minActiveDocsCoverage);
if (tuning.dispatch.minGroupCoverage != null)
builder.minGroupCoverage(tuning.dispatch.minGroupCoverage);
if (tuning.dispatch.policy != null) {
switch (tuning.dispatch.policy) {
case ADAPTIVE:
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
break;
case ROUNDROBIN:
builder.distributionPolicy(DistributionPolicy.ROUNDROBIN);
break;
}
}
if (tuning.dispatch.maxHitsPerPartition != null)
builder.maxHitsPerNode(tuning.dispatch.maxHitsPerPartition);
builder.maxNodesDownPerGroup(rootDispatch.getMaxNodesDownPerFixedRow());
builder.useLocalNode(tuning.dispatch.useLocalNode);
builder.searchableCopies(rootDispatch.getSearchableCopies());
if (searchCoverage != null) {
if (searchCoverage.getMinimum() != null)
builder.minSearchCoverage(searchCoverage.getMinimum() * 100.0);
if (searchCoverage.getMinWaitAfterCoverageFactor() != null)
builder.minWaitAfterCoverageFactor(searchCoverage.getMinWaitAfterCoverageFactor());
if (searchCoverage.getMaxWaitAfterCoverageFactor() != null)
builder.maxWaitAfterCoverageFactor(searchCoverage.getMaxWaitAfterCoverageFactor());
}
} | class UnionConfiguration
extends AbstractConfigProducer
implements AttributesConfig.Producer {
private final List<DocumentDatabase> docDbs;
public void getConfig(IndexInfoConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(IlscriptsConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
@Override
public void getConfig(AttributesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(RankProfilesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
private UnionConfiguration(AbstractConfigProducer parent, List<DocumentDatabase> docDbs) {
super(parent, "union");
this.docDbs = docDbs;
}
} | class UnionConfiguration
extends AbstractConfigProducer
implements AttributesConfig.Producer {
private final List<DocumentDatabase> docDbs;
public void getConfig(IndexInfoConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(IlscriptsConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
@Override
public void getConfig(AttributesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(RankProfilesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
private UnionConfiguration(AbstractConfigProducer parent, List<DocumentDatabase> docDbs) {
super(parent, "union");
this.docDbs = docDbs;
}
} |
Please consider "{" on one-line if statements. | public void getConfig(DispatchConfig.Builder builder) {
for (SearchNode node : getSearchNodes()) {
DispatchConfig.Node.Builder nodeBuilder = new DispatchConfig.Node.Builder();
nodeBuilder.key(node.getDistributionKey());
nodeBuilder.group(node.getNodeSpec().groupIndex());
nodeBuilder.host(node.getHostName());
nodeBuilder.port(node.getRpcPort());
nodeBuilder.fs4port(node.getDispatchPort());
builder.node(nodeBuilder);
}
if (useAdaptiveDispatch)
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
if (tuning.dispatch.minActiveDocsCoverage != null)
builder.minActivedocsPercentage(tuning.dispatch.minActiveDocsCoverage);
if (tuning.dispatch.minGroupCoverage != null)
builder.minGroupCoverage(tuning.dispatch.minGroupCoverage);
if (tuning.dispatch.policy != null) {
switch (tuning.dispatch.policy) {
case ADAPTIVE:
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
break;
case ROUNDROBIN:
builder.distributionPolicy(DistributionPolicy.ROUNDROBIN);
break;
}
}
if (tuning.dispatch.maxHitsPerPartition != null)
builder.maxHitsPerNode(tuning.dispatch.maxHitsPerPartition);
builder.maxNodesDownPerGroup(rootDispatch.getMaxNodesDownPerFixedRow());
builder.useLocalNode(tuning.dispatch.useLocalNode);
builder.searchableCopies(rootDispatch.getSearchableCopies());
if (searchCoverage != null) {
if (searchCoverage.getMinimum() != null)
builder.minSearchCoverage(searchCoverage.getMinimum() * 100.0);
if (searchCoverage.getMinWaitAfterCoverageFactor() != null)
builder.minWaitAfterCoverageFactor(searchCoverage.getMinWaitAfterCoverageFactor());
if (searchCoverage.getMaxWaitAfterCoverageFactor() != null)
builder.maxWaitAfterCoverageFactor(searchCoverage.getMaxWaitAfterCoverageFactor());
}
} | if (tuning.dispatch.maxHitsPerPartition != null) | public void getConfig(DispatchConfig.Builder builder) {
for (SearchNode node : getSearchNodes()) {
DispatchConfig.Node.Builder nodeBuilder = new DispatchConfig.Node.Builder();
nodeBuilder.key(node.getDistributionKey());
nodeBuilder.group(node.getNodeSpec().groupIndex());
nodeBuilder.host(node.getHostName());
nodeBuilder.port(node.getRpcPort());
nodeBuilder.fs4port(node.getDispatchPort());
builder.node(nodeBuilder);
}
if (useAdaptiveDispatch)
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
if (tuning.dispatch.minActiveDocsCoverage != null)
builder.minActivedocsPercentage(tuning.dispatch.minActiveDocsCoverage);
if (tuning.dispatch.minGroupCoverage != null)
builder.minGroupCoverage(tuning.dispatch.minGroupCoverage);
if (tuning.dispatch.policy != null) {
switch (tuning.dispatch.policy) {
case ADAPTIVE:
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
break;
case ROUNDROBIN:
builder.distributionPolicy(DistributionPolicy.ROUNDROBIN);
break;
}
}
if (tuning.dispatch.maxHitsPerPartition != null)
builder.maxHitsPerNode(tuning.dispatch.maxHitsPerPartition);
builder.maxNodesDownPerGroup(rootDispatch.getMaxNodesDownPerFixedRow());
builder.useLocalNode(tuning.dispatch.useLocalNode);
builder.searchableCopies(rootDispatch.getSearchableCopies());
if (searchCoverage != null) {
if (searchCoverage.getMinimum() != null)
builder.minSearchCoverage(searchCoverage.getMinimum() * 100.0);
if (searchCoverage.getMinWaitAfterCoverageFactor() != null)
builder.minWaitAfterCoverageFactor(searchCoverage.getMinWaitAfterCoverageFactor());
if (searchCoverage.getMaxWaitAfterCoverageFactor() != null)
builder.maxWaitAfterCoverageFactor(searchCoverage.getMaxWaitAfterCoverageFactor());
}
} | class UnionConfiguration
extends AbstractConfigProducer
implements AttributesConfig.Producer {
private final List<DocumentDatabase> docDbs;
public void getConfig(IndexInfoConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(IlscriptsConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
@Override
public void getConfig(AttributesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(RankProfilesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
private UnionConfiguration(AbstractConfigProducer parent, List<DocumentDatabase> docDbs) {
super(parent, "union");
this.docDbs = docDbs;
}
} | class UnionConfiguration
extends AbstractConfigProducer
implements AttributesConfig.Producer {
private final List<DocumentDatabase> docDbs;
public void getConfig(IndexInfoConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(IlscriptsConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
@Override
public void getConfig(AttributesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(RankProfilesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
private UnionConfiguration(AbstractConfigProducer parent, List<DocumentDatabase> docDbs) {
super(parent, "union");
this.docDbs = docDbs;
}
} |
Normally I do, but I prefer following the consensus in the file. And here all where non-braced. | public void getConfig(DispatchConfig.Builder builder) {
for (SearchNode node : getSearchNodes()) {
DispatchConfig.Node.Builder nodeBuilder = new DispatchConfig.Node.Builder();
nodeBuilder.key(node.getDistributionKey());
nodeBuilder.group(node.getNodeSpec().groupIndex());
nodeBuilder.host(node.getHostName());
nodeBuilder.port(node.getRpcPort());
nodeBuilder.fs4port(node.getDispatchPort());
builder.node(nodeBuilder);
}
if (useAdaptiveDispatch)
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
if (tuning.dispatch.minActiveDocsCoverage != null)
builder.minActivedocsPercentage(tuning.dispatch.minActiveDocsCoverage);
if (tuning.dispatch.minGroupCoverage != null)
builder.minGroupCoverage(tuning.dispatch.minGroupCoverage);
if (tuning.dispatch.policy != null) {
switch (tuning.dispatch.policy) {
case ADAPTIVE:
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
break;
case ROUNDROBIN:
builder.distributionPolicy(DistributionPolicy.ROUNDROBIN);
break;
}
}
if (tuning.dispatch.maxHitsPerPartition != null)
builder.maxHitsPerNode(tuning.dispatch.maxHitsPerPartition);
builder.maxNodesDownPerGroup(rootDispatch.getMaxNodesDownPerFixedRow());
builder.useLocalNode(tuning.dispatch.useLocalNode);
builder.searchableCopies(rootDispatch.getSearchableCopies());
if (searchCoverage != null) {
if (searchCoverage.getMinimum() != null)
builder.minSearchCoverage(searchCoverage.getMinimum() * 100.0);
if (searchCoverage.getMinWaitAfterCoverageFactor() != null)
builder.minWaitAfterCoverageFactor(searchCoverage.getMinWaitAfterCoverageFactor());
if (searchCoverage.getMaxWaitAfterCoverageFactor() != null)
builder.maxWaitAfterCoverageFactor(searchCoverage.getMaxWaitAfterCoverageFactor());
}
} | if (useAdaptiveDispatch) | public void getConfig(DispatchConfig.Builder builder) {
for (SearchNode node : getSearchNodes()) {
DispatchConfig.Node.Builder nodeBuilder = new DispatchConfig.Node.Builder();
nodeBuilder.key(node.getDistributionKey());
nodeBuilder.group(node.getNodeSpec().groupIndex());
nodeBuilder.host(node.getHostName());
nodeBuilder.port(node.getRpcPort());
nodeBuilder.fs4port(node.getDispatchPort());
builder.node(nodeBuilder);
}
if (useAdaptiveDispatch)
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
if (tuning.dispatch.minActiveDocsCoverage != null)
builder.minActivedocsPercentage(tuning.dispatch.minActiveDocsCoverage);
if (tuning.dispatch.minGroupCoverage != null)
builder.minGroupCoverage(tuning.dispatch.minGroupCoverage);
if (tuning.dispatch.policy != null) {
switch (tuning.dispatch.policy) {
case ADAPTIVE:
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
break;
case ROUNDROBIN:
builder.distributionPolicy(DistributionPolicy.ROUNDROBIN);
break;
}
}
if (tuning.dispatch.maxHitsPerPartition != null)
builder.maxHitsPerNode(tuning.dispatch.maxHitsPerPartition);
builder.maxNodesDownPerGroup(rootDispatch.getMaxNodesDownPerFixedRow());
builder.useLocalNode(tuning.dispatch.useLocalNode);
builder.searchableCopies(rootDispatch.getSearchableCopies());
if (searchCoverage != null) {
if (searchCoverage.getMinimum() != null)
builder.minSearchCoverage(searchCoverage.getMinimum() * 100.0);
if (searchCoverage.getMinWaitAfterCoverageFactor() != null)
builder.minWaitAfterCoverageFactor(searchCoverage.getMinWaitAfterCoverageFactor());
if (searchCoverage.getMaxWaitAfterCoverageFactor() != null)
builder.maxWaitAfterCoverageFactor(searchCoverage.getMaxWaitAfterCoverageFactor());
}
} | class UnionConfiguration
extends AbstractConfigProducer
implements AttributesConfig.Producer {
private final List<DocumentDatabase> docDbs;
public void getConfig(IndexInfoConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(IlscriptsConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
@Override
public void getConfig(AttributesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(RankProfilesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
private UnionConfiguration(AbstractConfigProducer parent, List<DocumentDatabase> docDbs) {
super(parent, "union");
this.docDbs = docDbs;
}
} | class UnionConfiguration
extends AbstractConfigProducer
implements AttributesConfig.Producer {
private final List<DocumentDatabase> docDbs;
public void getConfig(IndexInfoConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(IlscriptsConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
@Override
public void getConfig(AttributesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(RankProfilesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
private UnionConfiguration(AbstractConfigProducer parent, List<DocumentDatabase> docDbs) {
super(parent, "union");
this.docDbs = docDbs;
}
} |
Normally I do, but I prefer following the consensus in the file. And here all where non-braced. | public void getConfig(DispatchConfig.Builder builder) {
for (SearchNode node : getSearchNodes()) {
DispatchConfig.Node.Builder nodeBuilder = new DispatchConfig.Node.Builder();
nodeBuilder.key(node.getDistributionKey());
nodeBuilder.group(node.getNodeSpec().groupIndex());
nodeBuilder.host(node.getHostName());
nodeBuilder.port(node.getRpcPort());
nodeBuilder.fs4port(node.getDispatchPort());
builder.node(nodeBuilder);
}
if (useAdaptiveDispatch)
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
if (tuning.dispatch.minActiveDocsCoverage != null)
builder.minActivedocsPercentage(tuning.dispatch.minActiveDocsCoverage);
if (tuning.dispatch.minGroupCoverage != null)
builder.minGroupCoverage(tuning.dispatch.minGroupCoverage);
if (tuning.dispatch.policy != null) {
switch (tuning.dispatch.policy) {
case ADAPTIVE:
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
break;
case ROUNDROBIN:
builder.distributionPolicy(DistributionPolicy.ROUNDROBIN);
break;
}
}
if (tuning.dispatch.maxHitsPerPartition != null)
builder.maxHitsPerNode(tuning.dispatch.maxHitsPerPartition);
builder.maxNodesDownPerGroup(rootDispatch.getMaxNodesDownPerFixedRow());
builder.useLocalNode(tuning.dispatch.useLocalNode);
builder.searchableCopies(rootDispatch.getSearchableCopies());
if (searchCoverage != null) {
if (searchCoverage.getMinimum() != null)
builder.minSearchCoverage(searchCoverage.getMinimum() * 100.0);
if (searchCoverage.getMinWaitAfterCoverageFactor() != null)
builder.minWaitAfterCoverageFactor(searchCoverage.getMinWaitAfterCoverageFactor());
if (searchCoverage.getMaxWaitAfterCoverageFactor() != null)
builder.maxWaitAfterCoverageFactor(searchCoverage.getMaxWaitAfterCoverageFactor());
}
} | if (tuning.dispatch.maxHitsPerPartition != null) | public void getConfig(DispatchConfig.Builder builder) {
for (SearchNode node : getSearchNodes()) {
DispatchConfig.Node.Builder nodeBuilder = new DispatchConfig.Node.Builder();
nodeBuilder.key(node.getDistributionKey());
nodeBuilder.group(node.getNodeSpec().groupIndex());
nodeBuilder.host(node.getHostName());
nodeBuilder.port(node.getRpcPort());
nodeBuilder.fs4port(node.getDispatchPort());
builder.node(nodeBuilder);
}
if (useAdaptiveDispatch)
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
if (tuning.dispatch.minActiveDocsCoverage != null)
builder.minActivedocsPercentage(tuning.dispatch.minActiveDocsCoverage);
if (tuning.dispatch.minGroupCoverage != null)
builder.minGroupCoverage(tuning.dispatch.minGroupCoverage);
if (tuning.dispatch.policy != null) {
switch (tuning.dispatch.policy) {
case ADAPTIVE:
builder.distributionPolicy(DistributionPolicy.ADAPTIVE);
break;
case ROUNDROBIN:
builder.distributionPolicy(DistributionPolicy.ROUNDROBIN);
break;
}
}
if (tuning.dispatch.maxHitsPerPartition != null)
builder.maxHitsPerNode(tuning.dispatch.maxHitsPerPartition);
builder.maxNodesDownPerGroup(rootDispatch.getMaxNodesDownPerFixedRow());
builder.useLocalNode(tuning.dispatch.useLocalNode);
builder.searchableCopies(rootDispatch.getSearchableCopies());
if (searchCoverage != null) {
if (searchCoverage.getMinimum() != null)
builder.minSearchCoverage(searchCoverage.getMinimum() * 100.0);
if (searchCoverage.getMinWaitAfterCoverageFactor() != null)
builder.minWaitAfterCoverageFactor(searchCoverage.getMinWaitAfterCoverageFactor());
if (searchCoverage.getMaxWaitAfterCoverageFactor() != null)
builder.maxWaitAfterCoverageFactor(searchCoverage.getMaxWaitAfterCoverageFactor());
}
} | class UnionConfiguration
extends AbstractConfigProducer
implements AttributesConfig.Producer {
private final List<DocumentDatabase> docDbs;
public void getConfig(IndexInfoConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(IlscriptsConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
@Override
public void getConfig(AttributesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(RankProfilesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
private UnionConfiguration(AbstractConfigProducer parent, List<DocumentDatabase> docDbs) {
super(parent, "union");
this.docDbs = docDbs;
}
} | class UnionConfiguration
extends AbstractConfigProducer
implements AttributesConfig.Producer {
private final List<DocumentDatabase> docDbs;
public void getConfig(IndexInfoConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(IlscriptsConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
@Override
public void getConfig(AttributesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
public void getConfig(RankProfilesConfig.Builder builder) {
for (DocumentDatabase docDb : docDbs) {
docDb.getConfig(builder);
}
}
private UnionConfiguration(AbstractConfigProducer parent, List<DocumentDatabase> docDbs) {
super(parent, "union");
this.docDbs = docDbs;
}
} |
The release before this one should make all instances lock on the application level (in addition to on the instance level), making it OK for this release to lock _only_ on application level. | public Application createApplication(ApplicationId id, Optional<Credentials> credentials) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
try (Lock lock = lock(TenantAndApplicationId.from(id))) {
if (getApplication(TenantAndApplicationId.from(id)).isEmpty())
com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId.validate(id.application().value());
Optional<Tenant> tenant = controller.tenants().get(id.tenant());
if (tenant.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
if (getInstance(id).isPresent())
throw new IllegalArgumentException("Could not create '" + id + "': Application already exists");
if (getInstance(dashToUnderscore(id)).isPresent())
throw new IllegalArgumentException("Could not create '" + id + "': Application " + dashToUnderscore(id) + " already exists");
if (tenant.get().type() != Tenant.Type.user) {
if (credentials.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': No credentials provided");
if ( ! id.instance().isTester())
accessControl.createApplication(id, credentials.get());
}
List<Instance> instances = getApplication(TenantAndApplicationId.from(id)).map(application -> application.instances().values())
.map(ArrayList::new)
.orElse(new ArrayList<>());
instances.add(new Instance(id, clock.instant()));
LockedApplication application = new LockedApplication(Application.aggregate(instances).get(), lock);
store(application);
log.info("Created " + application);
return application.get();
}
} | } | public Application createApplication(ApplicationId id, Optional<Credentials> credentials) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
try (Lock lock = lock(TenantAndApplicationId.from(id))) {
if (getApplication(TenantAndApplicationId.from(id)).isEmpty())
com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId.validate(id.application().value());
Optional<Tenant> tenant = controller.tenants().get(id.tenant());
if (tenant.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
if (getInstance(id).isPresent())
throw new IllegalArgumentException("Could not create '" + id + "': Application already exists");
if (getInstance(dashToUnderscore(id)).isPresent())
throw new IllegalArgumentException("Could not create '" + id + "': Application " + dashToUnderscore(id) + " already exists");
if (tenant.get().type() != Tenant.Type.user) {
if (credentials.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': No credentials provided");
if ( ! id.instance().isTester())
accessControl.createApplication(id, credentials.get());
}
List<Instance> instances = getApplication(TenantAndApplicationId.from(id)).map(application -> application.instances().values())
.map(ArrayList::new)
.orElse(new ArrayList<>());
instances.add(new Instance(id, clock.instant()));
LockedApplication application = new LockedApplication(Application.aggregate(instances).get(), lock);
store(application);
log.info("Created " + application);
return application.get();
}
} | 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 RotationRepository rotationRepository;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final RoutingGenerator routingGenerator;
private final RoutingPolicies routingPolicies;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final BooleanFlag provisionApplicationCertificate;
private final DeploymentSpecValidator deploymentSpecValidator;
ApplicationController(Controller controller, CuratorDb curator,
AccessControl accessControl, RotationsConfig rotationsConfig,
Clock clock) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.routingGenerator = controller.serviceRegistry().routingGenerator();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
routingPolicies = new RoutingPolicies(controller);
rotationRepository = new RotationRepository(rotationsConfig, this, curator);
deploymentTrigger = new DeploymentTrigger(controller, controller.serviceRegistry().buildService(), clock);
provisionApplicationCertificate = Flags.PROVISION_APPLICATION_CERTIFICATE.bindTo(controller.flagSource());
deploymentSpecValidator = new DeploymentSpecValidator(controller);
Once.after(Duration.ofMinutes(1), () -> {
curator.clearInstanceRoot();
Instant start = clock.instant();
int count = 0;
for (Application application : curator.readApplications()) {
lockApplicationIfPresent(application.id(), this::store);
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 application with the given id, or null if it is not present */
public Optional<Application> getApplication(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id));
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(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();
}
/** 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 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());
}
/** Change the global endpoint status for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
findGlobalEndpoint(deployment).map(endpoint -> {
try {
configServer.setGlobalRotationStatus(deployment, endpoint.upstreamName(), status);
return endpoint;
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + deployment, e);
}
}).orElseThrow(() -> new IllegalArgumentException("No global endpoint exists for " + deployment));
}
/** Get global endpoint status for given deployment */
public Map<RoutingEndpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
return findGlobalEndpoint(deployment).map(endpoint -> {
try {
EndpointStatus status = configServer.getGlobalRotationStatus(deployment, endpoint.upstreamName());
return Map.of(endpoint, status);
} catch (Exception e) {
throw new RuntimeException("Failed to get rotation status of " + deployment, e);
}
}).orElseGet(Collections::emptyMap);
}
/** Find the global endpoint of given deployment, if any */
private Optional<RoutingEndpoint> findGlobalEndpoint(DeploymentId deployment) {
return routingGenerator.endpoints(deployment).stream()
.filter(RoutingEndpoint::isGlobal)
.findFirst();
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options, Optional.empty());
}
/** Deploys an application. If the application does not exist it is created. */
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
Optional<ApplicationVersion> applicationVersionFromDeployer,
DeployOptions options,
Optional<Principal> deployingIdentity) {
if (applicationId.instance().isTester())
throw new IllegalArgumentException("'" + applicationId + "' is a tester application!");
Tenant tenant = controller.tenants().require(applicationId.tenant());
if (tenant.type() == Tenant.Type.user && getInstance(applicationId).isEmpty())
createApplication(applicationId, Optional.empty());
try (Lock deploymentLock = lockForDeployment(applicationId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<ApplicationCertificate> applicationCertificate;
try (Lock lock = lock(TenantAndApplicationId.from(applicationId))) {
LockedApplication application = new LockedApplication(requireApplication(TenantAndApplicationId.from(applicationId)), lock);
InstanceName instance = applicationId.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 + "."));
Optional<JobStatus> job = Optional.ofNullable(application.get().require(instance).deploymentJobs().jobStatus().get(jobType));
if ( job.isEmpty()
|| job.get().lastTriggered().isEmpty()
|| job.get().lastCompleted().isPresent() && job.get().lastCompleted().get().at().isAfter(job.get().lastTriggered().get().at()))
return unexpectedDeployment(applicationId, zone);
JobRun triggered = job.get().lastTriggered().get();
platformVersion = preferOldestVersion ? triggered.sourcePlatform().orElse(triggered.platform())
: triggered.platform();
applicationVersion = preferOldestVersion ? triggered.sourceApplication().orElse(triggered.application())
: triggered.application();
applicationPackage = getApplicationPackage(applicationId, application.get().internal(), applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, applicationId, jobType);
validateRun(application.get(), instance, zone, platformVersion, applicationVersion);
}
verifyApplicationIdentityConfiguration(applicationId.tenant(), applicationPackage, deployingIdentity);
if (zone.environment().isProduction())
application = withRotation(application, instance);
endpoints = registerEndpointsInDns(application.get().deploymentSpec(), application.get().require(applicationId.instance()), zone);
if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
applicationCertificate = getApplicationCertificate(application.get().require(instance));
} else {
applicationCertificate = Optional.empty();
}
if ( ! preferOldestVersion
&& ! application.get().internal()
&& ! zone.environment().isManuallyDeployed()) {
storeWithUpdatedConfig(application, applicationPackage);
}
}
options = withVersion(platformVersion, options);
ActivateResult result = deploy(applicationId, applicationPackage, zone, options, endpoints,
applicationCertificate.orElse(null));
lockApplicationOrThrow(TenantAndApplicationId.from(applicationId), application ->
store(application.with(applicationId.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, boolean internal, ApplicationVersion version) {
try {
return internal
? new ApplicationPackage(applicationStore.get(id, version))
: new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()));
}
catch (RuntimeException e) {
try {
log.info("Fetching application package for " + id + " from alternate repository; it is now deployed "
+ (internal ? "internally" : "externally") + "\nException was: " + Exceptions.toMessageString(e));
return internal
? new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()))
: new ApplicationPackage(applicationStore.get(id, version));
}
catch (RuntimeException s) {
e.addSuppressed(s);
throw e;
}
}
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public void storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
deploymentSpecValidator.validate(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
for (InstanceName instanceName : application.get().instances().keySet()) {
application = withoutDeletedDeployments(application, instanceName);
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
application = application.with(instanceName, instance -> withoutUnreferencedDeploymentJobs(deploymentSpec, instance));
}
store(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)
);
DeployOptions options = withVersion(version, DeployOptions.none());
return deploy(application.id(), applicationPackage, zone, options, Set.of(), /* No application cert */ null);
} 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, DeployOptions options) {
return deploy(tester.id(), applicationPackage, zone, options, Set.of(), /* No application cert for tester*/ null);
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, DeployOptions deployOptions, Set<ContainerEndpoint> endpoints,
ApplicationCertificate applicationCertificate) {
DeploymentId deploymentId = new DeploymentId(application, zone);
try {
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(deploymentId, deployOptions, Set.of(), endpoints, applicationCertificate, applicationPackage.zippedContent());
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
routingPolicies.refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
/** Makes sure the application has a global rotation, if eligible. */
private LockedApplication withRotation(LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(application.get().deploymentSpec(),
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
store(application);
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
private Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
var registerLegacyNames = deploymentSpec.globalServiceId().isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId())
.scope(Endpoint.Scope.global);
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
if (!registerLegacyNames) {
endpoints = endpoints.legacy(false);
}
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.asList().forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
private Optional<ApplicationCertificate> getApplicationCertificate(Instance instance) {
boolean provisionCertificate = provisionApplicationCertificate.with(FetchVector.Dimension.APPLICATION_ID,
instance.id().serializedForm()).value();
if (!provisionCertificate) {
return Optional.empty();
}
Optional<ApplicationCertificate> applicationCertificate = curator.readApplicationCertificate(instance.id());
if(applicationCertificate.isPresent())
return applicationCertificate;
ApplicationCertificate newCertificate = controller.serviceRegistry().applicationCertificateProvider().requestCaSignedCertificate(instance.id(), dnsNamesOf(instance.id()));
curator.writeApplicationCertificate(instance.id(), newCertificate);
return Optional.of(newCertificate);
}
/** Returns all valid DNS names of given application */
private List<String> dnsNamesOf(ApplicationId applicationId) {
List<String> endpointDnsNames = new ArrayList<>();
endpointDnsNames.add(Endpoint.createHashedCn(applicationId, controller.system()));
var globalDefaultEndpoint = Endpoint.of(applicationId).named(EndpointId.default_());
var rotationEndpoints = Endpoint.of(applicationId).wildcard();
var zoneLocalEndpoints = controller.zoneRegistry().zones().directlyRouted().zones().stream().flatMap(zone -> Stream.of(
Endpoint.of(applicationId).target(ClusterSpec.Id.from("default"), zone.getId()),
Endpoint.of(applicationId).wildcard(zone.getId())
));
Stream.concat(Stream.of(globalDefaultEndpoint, rotationEndpoints), zoneLocalEndpoints)
.map(Endpoint.EndpointBuilder::directRouting)
.map(endpoint -> endpoint.on(Endpoint.Port.tls()))
.map(endpointBuilder -> endpointBuilder.in(controller.system()))
.map(Endpoint::dnsName).forEach(endpointDnsNames::add);
return Collections.unmodifiableList(endpointDnsNames);
}
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<Deployment> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.filter(deployment -> ! deploymentSpec.includes(deployment.zone().environment(),
Optional.of(deployment.zone().region())))
.collect(Collectors.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(deployment -> deployment.zone().region().value())
.collect(Collectors.joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
for (Deployment deployment : deploymentsToRemove)
application = deactivate(application, instance, deployment.zone());
return application;
}
private Instance withoutUnreferencedDeploymentJobs(DeploymentSpec deploymentSpec, Instance instance) {
for (JobType job : JobList.from(instance).production().mapToList(JobStatus::type)) {
ZoneId zone = job.zone(controller.system());
if (deploymentSpec.includes(zone.environment(), Optional.of(zone.region())))
continue;
instance = instance.withoutDeploymentJob(job);
}
return instance;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/** Returns the endpoints of the deployment, or empty if the request fails */
public List<URI> getDeploymentEndpoints(DeploymentId deploymentId) {
if ( ! getInstance(deploymentId.applicationId())
.map(application -> application.deployments().containsKey(deploymentId.zoneId()))
.orElse(deploymentId.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", deploymentId.toString());
try {
return ImmutableList.copyOf(routingGenerator.endpoints(deploymentId).stream()
.map(RoutingEndpoint::endpoint)
.map(URI::create)
.iterator());
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e);
return Collections.emptyList();
}
}
/** Returns the non-empty endpoints per cluster in the given deployment, or empty if endpoints can't be found. */
public Map<ClusterSpec.Id, URI> clusterEndpoints(DeploymentId id) {
if ( ! getInstance(id.applicationId())
.map(application -> application.deployments().containsKey(id.zoneId()))
.orElse(id.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", id.toString());
try {
var endpoints = routingGenerator.clusterEndpoints(id);
if ( ! endpoints.isEmpty())
return endpoints;
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + id, e);
}
return routingPolicies.get(id).stream()
.filter(policy -> policy.endpointIn(controller.system()).scope() == Endpoint.Scope.zone)
.collect(Collectors.toUnmodifiableMap(policy -> policy.cluster(),
policy -> policy.endpointIn(controller.system()).url()));
}
/** Returns all zone-specific cluster endpoints for the given application, in the given zones. */
public Map<ZoneId, Map<ClusterSpec.Id, URI>> clusterEndpoints(ApplicationId id, Collection<ZoneId> zones) {
Map<ZoneId, Map<ClusterSpec.Id, URI>> deployments = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (ZoneId zone : zones) {
var endpoints = clusterEndpoints(new DeploymentId(id, zone));
if ( ! endpoints.isEmpty())
deployments.put(zone, endpoints);
}
return Collections.unmodifiableMap(deployments);
}
/**
* 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(TenantName tenantName, ApplicationName applicationName, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(tenantName);
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + tenantName + "." + applicationName + "': No credentials provided");
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
List<ApplicationId> instances = requireApplication(id).instances().keySet().stream()
.map(id::instance)
.collect(Collectors.toUnmodifiableList());
if (instances.size() > 1)
throw new IllegalArgumentException("Could not delete application; more than one instance present: " + instances);
for (ApplicationId instance : instances)
deleteInstance(instance, credentials);
}
/**
* 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 applicationId, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(applicationId.tenant());
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + applicationId + "': No credentials provided");
if (getInstance(applicationId).isEmpty())
throw new NotExistsException("Could not delete application '" + applicationId + "': Application not found");
lockApplicationOrThrow(TenantAndApplicationId.from(applicationId), application -> {
if ( ! application.get().require(applicationId.instance()).deployments().isEmpty())
throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments in: " +
application.get().require(applicationId.instance()).deployments().keySet().stream().map(ZoneId::toString)
.sorted().collect(Collectors.joining(", ")));
curator.removeApplication(applicationId);
applicationStore.removeAll(applicationId);
applicationStore.removeAll(TesterId.of(applicationId));
Instance instance = application.get().require(applicationId.instance());
instance.rotations().forEach(assignedRotation -> {
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId());
endpoints.asList().stream()
.map(Endpoint::dnsName)
.forEach(name -> {
controller.nameServiceForwarder().removeRecords(Record.Type.CNAME, RecordName.from(name), Priority.normal);
});
});
log.info("Deleted " + application);
});
if (tenant.type() != Tenant.Type.user && getApplication(applicationId).isEmpty())
accessControl.deleteApplication(applicationId, credentials.get());
}
/**
* 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.
*
* WARNING: Uses only the "default" instance.
*
* @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) {
ApplicationId instanceId = applicationId.defaultInstance();
try (Lock lock = lock(applicationId)) {
action.accept(new LockedApplication(requireApplication(TenantAndApplicationId.from(instanceId)), 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 {
routingPolicies.refresh(application.get().id().instance(instanceName), application.get().deploymentSpec(), zone);
}
return application.with(instanceName, instance -> instance.withoutDeploymentIn(zone));
}
public DeploymentTrigger deploymentTrigger() { return deploymentTrigger; }
private ApplicationId dashToUnderscore(ApplicationId id) {
return ApplicationId.from(id.tenant().value(),
id.application().value().replaceAll("-", "_"),
id.instance().value());
}
/**
* 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(Application application, InstanceName instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = application.require(instance).deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! application.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).",
application.id().instance(instance), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/** Returns the rotation repository, used for managing global rotation assignments */
public RotationRepository rotationRepository() {
return rotationRepository;
}
public RoutingPolicies routingPolicies() {
return routingPolicies;
}
/**
* 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, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
applicationPackage.deploymentSpec().athenzDomain().ifPresent(identityDomain -> {
Tenant tenant = controller.tenants().require(tenantName);
deployer.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.ifPresentOrElse(user -> {
if ( ! ((AthenzFacade) accessControl).hasTenantAdminAccess(user, new AthenzDomain(identityDomain.value())))
throw new IllegalArgumentException("User " + user.getFullName() + " is not allowed to launch " +
"services in Athenz domain " + identityDomain.value() + ". " +
"Please reach out to the domain admin.");
},
() -> {
if (tenant.type() != Tenant.Type.athenz)
throw new IllegalArgumentException("Athenz domain defined in deployment.xml, but no " +
"Athenz domain for tenant " + tenantName.value());
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain.getName(), identityDomain.value()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.value() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
});
});
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(athenzDomain -> {
controller.zoneRegistry().zones().reachable().ids()
.forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService(zone.environment(), zone.region())
.map(service -> new AthenzService(athenzDomain.value(), service.value()))
.ifPresent(service -> {
boolean allowedToLaunch = ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, service);
if (!allowedToLaunch)
throw new IllegalArgumentException("Not allowed to launch Athenz service " + service.getFullName());
});
});
});
}
/** Returns the latest known version within the given major. */
private 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 RotationRepository rotationRepository;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final RoutingGenerator routingGenerator;
private final RoutingPolicies routingPolicies;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final BooleanFlag provisionApplicationCertificate;
private final DeploymentSpecValidator deploymentSpecValidator;
ApplicationController(Controller controller, CuratorDb curator,
AccessControl accessControl, RotationsConfig rotationsConfig,
Clock clock) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.routingGenerator = controller.serviceRegistry().routingGenerator();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
routingPolicies = new RoutingPolicies(controller);
rotationRepository = new RotationRepository(rotationsConfig, this, curator);
deploymentTrigger = new DeploymentTrigger(controller, controller.serviceRegistry().buildService(), clock);
provisionApplicationCertificate = Flags.PROVISION_APPLICATION_CERTIFICATE.bindTo(controller.flagSource());
deploymentSpecValidator = new DeploymentSpecValidator(controller);
Once.after(Duration.ofMinutes(1), () -> {
curator.clearInstanceRoot();
Instant start = clock.instant();
int count = 0;
for (Application application : curator.readApplications()) {
lockApplicationIfPresent(application.id(), this::store);
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 application with the given id, or null if it is not present */
public Optional<Application> getApplication(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id));
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(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();
}
/** 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 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());
}
/** Change the global endpoint status for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
findGlobalEndpoint(deployment).map(endpoint -> {
try {
configServer.setGlobalRotationStatus(deployment, endpoint.upstreamName(), status);
return endpoint;
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + deployment, e);
}
}).orElseThrow(() -> new IllegalArgumentException("No global endpoint exists for " + deployment));
}
/** Get global endpoint status for given deployment */
public Map<RoutingEndpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
return findGlobalEndpoint(deployment).map(endpoint -> {
try {
EndpointStatus status = configServer.getGlobalRotationStatus(deployment, endpoint.upstreamName());
return Map.of(endpoint, status);
} catch (Exception e) {
throw new RuntimeException("Failed to get rotation status of " + deployment, e);
}
}).orElseGet(Collections::emptyMap);
}
/** Find the global endpoint of given deployment, if any */
private Optional<RoutingEndpoint> findGlobalEndpoint(DeploymentId deployment) {
return routingGenerator.endpoints(deployment).stream()
.filter(RoutingEndpoint::isGlobal)
.findFirst();
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options, Optional.empty());
}
/** Deploys an application. If the application does not exist it is created. */
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
Optional<ApplicationVersion> applicationVersionFromDeployer,
DeployOptions options,
Optional<Principal> deployingIdentity) {
if (applicationId.instance().isTester())
throw new IllegalArgumentException("'" + applicationId + "' is a tester application!");
Tenant tenant = controller.tenants().require(applicationId.tenant());
if (tenant.type() == Tenant.Type.user && getInstance(applicationId).isEmpty())
createApplication(applicationId, Optional.empty());
try (Lock deploymentLock = lockForDeployment(applicationId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<ApplicationCertificate> applicationCertificate;
try (Lock lock = lock(TenantAndApplicationId.from(applicationId))) {
LockedApplication application = new LockedApplication(requireApplication(TenantAndApplicationId.from(applicationId)), lock);
InstanceName instance = applicationId.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 + "."));
Optional<JobStatus> job = Optional.ofNullable(application.get().require(instance).deploymentJobs().jobStatus().get(jobType));
if ( job.isEmpty()
|| job.get().lastTriggered().isEmpty()
|| job.get().lastCompleted().isPresent() && job.get().lastCompleted().get().at().isAfter(job.get().lastTriggered().get().at()))
return unexpectedDeployment(applicationId, zone);
JobRun triggered = job.get().lastTriggered().get();
platformVersion = preferOldestVersion ? triggered.sourcePlatform().orElse(triggered.platform())
: triggered.platform();
applicationVersion = preferOldestVersion ? triggered.sourceApplication().orElse(triggered.application())
: triggered.application();
applicationPackage = getApplicationPackage(applicationId, application.get().internal(), applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, applicationId, jobType);
validateRun(application.get(), instance, zone, platformVersion, applicationVersion);
}
verifyApplicationIdentityConfiguration(applicationId.tenant(), applicationPackage, deployingIdentity);
if (zone.environment().isProduction())
application = withRotation(application, instance);
endpoints = registerEndpointsInDns(application.get().deploymentSpec(), application.get().require(applicationId.instance()), zone);
if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
applicationCertificate = getApplicationCertificate(application.get().require(instance));
} else {
applicationCertificate = Optional.empty();
}
if ( ! preferOldestVersion
&& ! application.get().internal()
&& ! zone.environment().isManuallyDeployed()) {
storeWithUpdatedConfig(application, applicationPackage);
}
}
options = withVersion(platformVersion, options);
ActivateResult result = deploy(applicationId, applicationPackage, zone, options, endpoints,
applicationCertificate.orElse(null));
lockApplicationOrThrow(TenantAndApplicationId.from(applicationId), application ->
store(application.with(applicationId.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, boolean internal, ApplicationVersion version) {
try {
return internal
? new ApplicationPackage(applicationStore.get(id, version))
: new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()));
}
catch (RuntimeException e) {
try {
log.info("Fetching application package for " + id + " from alternate repository; it is now deployed "
+ (internal ? "internally" : "externally") + "\nException was: " + Exceptions.toMessageString(e));
return internal
? new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()))
: new ApplicationPackage(applicationStore.get(id, version));
}
catch (RuntimeException s) {
e.addSuppressed(s);
throw e;
}
}
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public void storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
deploymentSpecValidator.validate(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
for (InstanceName instanceName : application.get().instances().keySet()) {
application = withoutDeletedDeployments(application, instanceName);
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
application = application.with(instanceName, instance -> withoutUnreferencedDeploymentJobs(deploymentSpec, instance));
}
store(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)
);
DeployOptions options = withVersion(version, DeployOptions.none());
return deploy(application.id(), applicationPackage, zone, options, Set.of(), /* No application cert */ null);
} 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, DeployOptions options) {
return deploy(tester.id(), applicationPackage, zone, options, Set.of(), /* No application cert for tester*/ null);
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, DeployOptions deployOptions, Set<ContainerEndpoint> endpoints,
ApplicationCertificate applicationCertificate) {
DeploymentId deploymentId = new DeploymentId(application, zone);
try {
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(deploymentId, deployOptions, Set.of(), endpoints, applicationCertificate, applicationPackage.zippedContent());
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
routingPolicies.refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
/** Makes sure the application has a global rotation, if eligible. */
private LockedApplication withRotation(LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(application.get().deploymentSpec(),
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
store(application);
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
private Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
var registerLegacyNames = deploymentSpec.globalServiceId().isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId())
.scope(Endpoint.Scope.global);
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
if (!registerLegacyNames) {
endpoints = endpoints.legacy(false);
}
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.asList().forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
private Optional<ApplicationCertificate> getApplicationCertificate(Instance instance) {
boolean provisionCertificate = provisionApplicationCertificate.with(FetchVector.Dimension.APPLICATION_ID,
instance.id().serializedForm()).value();
if (!provisionCertificate) {
return Optional.empty();
}
Optional<ApplicationCertificate> applicationCertificate = curator.readApplicationCertificate(instance.id());
if(applicationCertificate.isPresent())
return applicationCertificate;
ApplicationCertificate newCertificate = controller.serviceRegistry().applicationCertificateProvider().requestCaSignedCertificate(instance.id(), dnsNamesOf(instance.id()));
curator.writeApplicationCertificate(instance.id(), newCertificate);
return Optional.of(newCertificate);
}
/** Returns all valid DNS names of given application */
private List<String> dnsNamesOf(ApplicationId applicationId) {
List<String> endpointDnsNames = new ArrayList<>();
endpointDnsNames.add(Endpoint.createHashedCn(applicationId, controller.system()));
var globalDefaultEndpoint = Endpoint.of(applicationId).named(EndpointId.default_());
var rotationEndpoints = Endpoint.of(applicationId).wildcard();
var zoneLocalEndpoints = controller.zoneRegistry().zones().directlyRouted().zones().stream().flatMap(zone -> Stream.of(
Endpoint.of(applicationId).target(ClusterSpec.Id.from("default"), zone.getId()),
Endpoint.of(applicationId).wildcard(zone.getId())
));
Stream.concat(Stream.of(globalDefaultEndpoint, rotationEndpoints), zoneLocalEndpoints)
.map(Endpoint.EndpointBuilder::directRouting)
.map(endpoint -> endpoint.on(Endpoint.Port.tls()))
.map(endpointBuilder -> endpointBuilder.in(controller.system()))
.map(Endpoint::dnsName).forEach(endpointDnsNames::add);
return Collections.unmodifiableList(endpointDnsNames);
}
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<Deployment> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.filter(deployment -> ! deploymentSpec.includes(deployment.zone().environment(),
Optional.of(deployment.zone().region())))
.collect(Collectors.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(deployment -> deployment.zone().region().value())
.collect(Collectors.joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
for (Deployment deployment : deploymentsToRemove)
application = deactivate(application, instance, deployment.zone());
return application;
}
private Instance withoutUnreferencedDeploymentJobs(DeploymentSpec deploymentSpec, Instance instance) {
for (JobType job : JobList.from(instance).production().mapToList(JobStatus::type)) {
ZoneId zone = job.zone(controller.system());
if (deploymentSpec.includes(zone.environment(), Optional.of(zone.region())))
continue;
instance = instance.withoutDeploymentJob(job);
}
return instance;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/** Returns the endpoints of the deployment, or empty if the request fails */
public List<URI> getDeploymentEndpoints(DeploymentId deploymentId) {
if ( ! getInstance(deploymentId.applicationId())
.map(application -> application.deployments().containsKey(deploymentId.zoneId()))
.orElse(deploymentId.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", deploymentId.toString());
try {
return ImmutableList.copyOf(routingGenerator.endpoints(deploymentId).stream()
.map(RoutingEndpoint::endpoint)
.map(URI::create)
.iterator());
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e);
return Collections.emptyList();
}
}
/** Returns the non-empty endpoints per cluster in the given deployment, or empty if endpoints can't be found. */
public Map<ClusterSpec.Id, URI> clusterEndpoints(DeploymentId id) {
if ( ! getInstance(id.applicationId())
.map(application -> application.deployments().containsKey(id.zoneId()))
.orElse(id.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", id.toString());
try {
var endpoints = routingGenerator.clusterEndpoints(id);
if ( ! endpoints.isEmpty())
return endpoints;
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + id, e);
}
return routingPolicies.get(id).stream()
.filter(policy -> policy.endpointIn(controller.system()).scope() == Endpoint.Scope.zone)
.collect(Collectors.toUnmodifiableMap(policy -> policy.cluster(),
policy -> policy.endpointIn(controller.system()).url()));
}
/** Returns all zone-specific cluster endpoints for the given application, in the given zones. */
public Map<ZoneId, Map<ClusterSpec.Id, URI>> clusterEndpoints(ApplicationId id, Collection<ZoneId> zones) {
Map<ZoneId, Map<ClusterSpec.Id, URI>> deployments = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (ZoneId zone : zones) {
var endpoints = clusterEndpoints(new DeploymentId(id, zone));
if ( ! endpoints.isEmpty())
deployments.put(zone, endpoints);
}
return Collections.unmodifiableMap(deployments);
}
/**
* 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(TenantName tenantName, ApplicationName applicationName, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(tenantName);
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + tenantName + "." + applicationName + "': No credentials provided");
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
List<ApplicationId> instances = requireApplication(id).instances().keySet().stream()
.map(id::instance)
.collect(Collectors.toUnmodifiableList());
if (instances.size() > 1)
throw new IllegalArgumentException("Could not delete application; more than one instance present: " + instances);
for (ApplicationId instance : instances)
deleteInstance(instance, credentials);
}
/**
* 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 applicationId, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(applicationId.tenant());
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + applicationId + "': No credentials provided");
if (getInstance(applicationId).isEmpty())
throw new NotExistsException("Could not delete application '" + applicationId + "': Application not found");
lockApplicationOrThrow(TenantAndApplicationId.from(applicationId), application -> {
if ( ! application.get().require(applicationId.instance()).deployments().isEmpty())
throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments in: " +
application.get().require(applicationId.instance()).deployments().keySet().stream().map(ZoneId::toString)
.sorted().collect(Collectors.joining(", ")));
curator.removeApplication(applicationId);
applicationStore.removeAll(applicationId);
applicationStore.removeAll(TesterId.of(applicationId));
Instance instance = application.get().require(applicationId.instance());
instance.rotations().forEach(assignedRotation -> {
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId());
endpoints.asList().stream()
.map(Endpoint::dnsName)
.forEach(name -> {
controller.nameServiceForwarder().removeRecords(Record.Type.CNAME, RecordName.from(name), Priority.normal);
});
});
log.info("Deleted " + application);
});
if (tenant.type() != Tenant.Type.user && getApplication(applicationId).isEmpty())
accessControl.deleteApplication(applicationId, credentials.get());
}
/**
* 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 {
routingPolicies.refresh(application.get().id().instance(instanceName), application.get().deploymentSpec(), zone);
}
return application.with(instanceName, instance -> instance.withoutDeploymentIn(zone));
}
public DeploymentTrigger deploymentTrigger() { return deploymentTrigger; }
private ApplicationId dashToUnderscore(ApplicationId id) {
return ApplicationId.from(id.tenant().value(),
id.application().value().replaceAll("-", "_"),
id.instance().value());
}
/**
* 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(Application application, InstanceName instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = application.require(instance).deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! application.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).",
application.id().instance(instance), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/** Returns the rotation repository, used for managing global rotation assignments */
public RotationRepository rotationRepository() {
return rotationRepository;
}
public RoutingPolicies routingPolicies() {
return routingPolicies;
}
/**
* 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, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
applicationPackage.deploymentSpec().athenzDomain().ifPresent(identityDomain -> {
Tenant tenant = controller.tenants().require(tenantName);
deployer.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.ifPresentOrElse(user -> {
if ( ! ((AthenzFacade) accessControl).hasTenantAdminAccess(user, new AthenzDomain(identityDomain.value())))
throw new IllegalArgumentException("User " + user.getFullName() + " is not allowed to launch " +
"services in Athenz domain " + identityDomain.value() + ". " +
"Please reach out to the domain admin.");
},
() -> {
if (tenant.type() != Tenant.Type.athenz)
throw new IllegalArgumentException("Athenz domain defined in deployment.xml, but no " +
"Athenz domain for tenant " + tenantName.value());
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain.getName(), identityDomain.value()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.value() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
});
});
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(athenzDomain -> {
controller.zoneRegistry().zones().reachable().ids()
.forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService(zone.environment(), zone.region())
.map(service -> new AthenzService(athenzDomain.value(), service.value()))
.ifPresent(service -> {
boolean allowedToLaunch = ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, service);
if (!allowedToLaunch)
throw new IllegalArgumentException("Not allowed to launch Athenz service " + service.getFullName());
});
});
});
}
/** Returns the latest known version within the given major. */
private 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);
}
} |
`getStatus` moved outside of holding the application lock. Ok? | protected void maintain() {
var failures = new AtomicInteger(0);
var attempts = new AtomicInteger(0);
var lastException = new AtomicReference<Exception>(null);
var instancesWithRotations = ApplicationList.from(applications.asList()).hasRotation().asList().stream()
.flatMap(application -> application.instances().values().stream())
.filter(instance -> ! instance.rotations().isEmpty());
var pool = new ForkJoinPool(applicationsToUpdateInParallel);
pool.submit(() -> {
instancesWithRotations.parallel().forEach(instance -> {
attempts.incrementAndGet();
try {
RotationStatus status = getStatus(instance);
applications.lockApplicationIfPresent(TenantAndApplicationId.from(instance.id()), app ->
applications.store(app.with(instance.name(), locked -> locked.with(status))));
} catch (Exception e) {
failures.incrementAndGet();
lastException.set(e);
}
});
});
pool.shutdown();
try {
pool.awaitTermination(30, TimeUnit.SECONDS);
if (lastException.get() != null) {
log.log(LogLevel.WARNING, String.format("Failed to get global routing status of %d/%d applications. Retrying in %s. Last error: ",
failures.get(),
attempts.get(),
maintenanceInterval()),
lastException.get());
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} | RotationStatus status = getStatus(instance); | protected void maintain() {
var failures = new AtomicInteger(0);
var attempts = new AtomicInteger(0);
var lastException = new AtomicReference<Exception>(null);
var instancesWithRotations = ApplicationList.from(applications.asList()).hasRotation().asList().stream()
.flatMap(application -> application.instances().values().stream())
.filter(instance -> ! instance.rotations().isEmpty());
var pool = new ForkJoinPool(applicationsToUpdateInParallel);
pool.submit(() -> {
instancesWithRotations.parallel().forEach(instance -> {
attempts.incrementAndGet();
try {
RotationStatus status = getStatus(instance);
applications.lockApplicationIfPresent(TenantAndApplicationId.from(instance.id()), app ->
applications.store(app.with(instance.name(), locked -> locked.with(status))));
} catch (Exception e) {
failures.incrementAndGet();
lastException.set(e);
}
});
});
pool.shutdown();
try {
pool.awaitTermination(30, TimeUnit.SECONDS);
if (lastException.get() != null) {
log.log(LogLevel.WARNING, String.format("Failed to get global routing status of %d/%d applications. Retrying in %s. Last error: ",
failures.get(),
attempts.get(),
maintenanceInterval()),
lastException.get());
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} | class RotationStatusUpdater extends Maintainer {
private static final int applicationsToUpdateInParallel = 10;
private final GlobalRoutingService service;
private final ApplicationController applications;
public RotationStatusUpdater(Controller controller, Duration interval, JobControl jobControl) {
super(controller, interval, jobControl);
this.service = controller.serviceRegistry().globalRoutingService();
this.applications = controller.applications();
}
@Override
private RotationStatus getStatus(Instance instance) {
var statusMap = new LinkedHashMap<RotationId, Map<ZoneId, RotationState>>();
for (var assignedRotation : instance.rotations()) {
var rotation = applications.rotationRepository().getRotation(assignedRotation.rotationId());
if (rotation.isEmpty()) continue;
var rotationStatus = service.getHealthStatus(rotation.get().name()).entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, (kv) -> from(kv.getValue())));
statusMap.put(assignedRotation.rotationId(), rotationStatus);
}
return RotationStatus.from(statusMap);
}
private static RotationState from(com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus status) {
switch (status) {
case IN: return RotationState.in;
case OUT: return RotationState.out;
case UNKNOWN: return RotationState.unknown;
default: throw new IllegalArgumentException("Unknown API value for rotation status: " + status);
}
}
} | class RotationStatusUpdater extends Maintainer {
private static final int applicationsToUpdateInParallel = 10;
private final GlobalRoutingService service;
private final ApplicationController applications;
public RotationStatusUpdater(Controller controller, Duration interval, JobControl jobControl) {
super(controller, interval, jobControl);
this.service = controller.serviceRegistry().globalRoutingService();
this.applications = controller.applications();
}
@Override
private RotationStatus getStatus(Instance instance) {
var statusMap = new LinkedHashMap<RotationId, Map<ZoneId, RotationState>>();
for (var assignedRotation : instance.rotations()) {
var rotation = applications.rotationRepository().getRotation(assignedRotation.rotationId());
if (rotation.isEmpty()) continue;
var rotationStatus = service.getHealthStatus(rotation.get().name()).entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, (kv) -> from(kv.getValue())));
statusMap.put(assignedRotation.rotationId(), rotationStatus);
}
return RotationStatus.from(statusMap);
}
private static RotationState from(com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus status) {
switch (status) {
case IN: return RotationState.in;
case OUT: return RotationState.out;
case UNKNOWN: return RotationState.unknown;
default: throw new IllegalArgumentException("Unknown API value for rotation status: " + status);
}
}
} |
Should be OK. | protected void maintain() {
var failures = new AtomicInteger(0);
var attempts = new AtomicInteger(0);
var lastException = new AtomicReference<Exception>(null);
var instancesWithRotations = ApplicationList.from(applications.asList()).hasRotation().asList().stream()
.flatMap(application -> application.instances().values().stream())
.filter(instance -> ! instance.rotations().isEmpty());
var pool = new ForkJoinPool(applicationsToUpdateInParallel);
pool.submit(() -> {
instancesWithRotations.parallel().forEach(instance -> {
attempts.incrementAndGet();
try {
RotationStatus status = getStatus(instance);
applications.lockApplicationIfPresent(TenantAndApplicationId.from(instance.id()), app ->
applications.store(app.with(instance.name(), locked -> locked.with(status))));
} catch (Exception e) {
failures.incrementAndGet();
lastException.set(e);
}
});
});
pool.shutdown();
try {
pool.awaitTermination(30, TimeUnit.SECONDS);
if (lastException.get() != null) {
log.log(LogLevel.WARNING, String.format("Failed to get global routing status of %d/%d applications. Retrying in %s. Last error: ",
failures.get(),
attempts.get(),
maintenanceInterval()),
lastException.get());
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} | RotationStatus status = getStatus(instance); | protected void maintain() {
var failures = new AtomicInteger(0);
var attempts = new AtomicInteger(0);
var lastException = new AtomicReference<Exception>(null);
var instancesWithRotations = ApplicationList.from(applications.asList()).hasRotation().asList().stream()
.flatMap(application -> application.instances().values().stream())
.filter(instance -> ! instance.rotations().isEmpty());
var pool = new ForkJoinPool(applicationsToUpdateInParallel);
pool.submit(() -> {
instancesWithRotations.parallel().forEach(instance -> {
attempts.incrementAndGet();
try {
RotationStatus status = getStatus(instance);
applications.lockApplicationIfPresent(TenantAndApplicationId.from(instance.id()), app ->
applications.store(app.with(instance.name(), locked -> locked.with(status))));
} catch (Exception e) {
failures.incrementAndGet();
lastException.set(e);
}
});
});
pool.shutdown();
try {
pool.awaitTermination(30, TimeUnit.SECONDS);
if (lastException.get() != null) {
log.log(LogLevel.WARNING, String.format("Failed to get global routing status of %d/%d applications. Retrying in %s. Last error: ",
failures.get(),
attempts.get(),
maintenanceInterval()),
lastException.get());
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} | class RotationStatusUpdater extends Maintainer {
private static final int applicationsToUpdateInParallel = 10;
private final GlobalRoutingService service;
private final ApplicationController applications;
public RotationStatusUpdater(Controller controller, Duration interval, JobControl jobControl) {
super(controller, interval, jobControl);
this.service = controller.serviceRegistry().globalRoutingService();
this.applications = controller.applications();
}
@Override
private RotationStatus getStatus(Instance instance) {
var statusMap = new LinkedHashMap<RotationId, Map<ZoneId, RotationState>>();
for (var assignedRotation : instance.rotations()) {
var rotation = applications.rotationRepository().getRotation(assignedRotation.rotationId());
if (rotation.isEmpty()) continue;
var rotationStatus = service.getHealthStatus(rotation.get().name()).entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, (kv) -> from(kv.getValue())));
statusMap.put(assignedRotation.rotationId(), rotationStatus);
}
return RotationStatus.from(statusMap);
}
private static RotationState from(com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus status) {
switch (status) {
case IN: return RotationState.in;
case OUT: return RotationState.out;
case UNKNOWN: return RotationState.unknown;
default: throw new IllegalArgumentException("Unknown API value for rotation status: " + status);
}
}
} | class RotationStatusUpdater extends Maintainer {
private static final int applicationsToUpdateInParallel = 10;
private final GlobalRoutingService service;
private final ApplicationController applications;
public RotationStatusUpdater(Controller controller, Duration interval, JobControl jobControl) {
super(controller, interval, jobControl);
this.service = controller.serviceRegistry().globalRoutingService();
this.applications = controller.applications();
}
@Override
private RotationStatus getStatus(Instance instance) {
var statusMap = new LinkedHashMap<RotationId, Map<ZoneId, RotationState>>();
for (var assignedRotation : instance.rotations()) {
var rotation = applications.rotationRepository().getRotation(assignedRotation.rotationId());
if (rotation.isEmpty()) continue;
var rotationStatus = service.getHealthStatus(rotation.get().name()).entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, (kv) -> from(kv.getValue())));
statusMap.put(assignedRotation.rotationId(), rotationStatus);
}
return RotationStatus.from(statusMap);
}
private static RotationState from(com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus status) {
switch (status) {
case IN: return RotationState.in;
case OUT: return RotationState.out;
case UNKNOWN: return RotationState.unknown;
default: throw new IllegalArgumentException("Unknown API value for rotation status: " + status);
}
}
} |
Consider adding this message to the INFO message that anyway is printed | public void run() {
System.setProperty(ZOOKEEPER_JMX_LOG4J_DISABLE, "true");
String[] args = new String[]{getDefaults().underVespaHome(zookeeperServerConfig.zooKeeperConfigFile())};
log.log(LogLevel.DEBUG, "Starting ZooKeeper server with config file " + args[0]);
log.log(LogLevel.INFO, "Trying to establish ZooKeeper quorum (from " + zookeeperServerHostnames(zookeeperServerConfig) + ")");
org.apache.zookeeper.server.quorum.QuorumPeerMain.main(args);
} | log.log(LogLevel.DEBUG, "Starting ZooKeeper server with config file " + args[0]); | public void run() {
System.setProperty(ZOOKEEPER_JMX_LOG4J_DISABLE, "true");
String[] args = new String[]{getDefaults().underVespaHome(zookeeperServerConfig.zooKeeperConfigFile())};
log.log(LogLevel.DEBUG, "Starting ZooKeeper server with config file " + args[0]);
log.log(LogLevel.INFO, "Trying to establish ZooKeeper quorum (from " + zookeeperServerHostnames(zookeeperServerConfig) + ")");
org.apache.zookeeper.server.quorum.QuorumPeerMain.main(args);
} | class ZooKeeperServer extends AbstractComponent implements Runnable {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(ZooKeeperServer.class.getName());
private static final String ZOOKEEPER_JMX_LOG4J_DISABLE = "zookeeper.jmx.log4j.disable";
static final String ZOOKEEPER_JUTE_MAX_BUFFER = "jute.maxbuffer";
private final Thread zkServerThread;
private final ZookeeperServerConfig zookeeperServerConfig;
ZooKeeperServer(ZookeeperServerConfig zookeeperServerConfig, boolean startServer) {
this.zookeeperServerConfig = zookeeperServerConfig;
System.setProperty("zookeeper.jmx.log4j.disable", "true");
System.setProperty("zookeeper.snapshot.trust.empty", Boolean.valueOf(zookeeperServerConfig.trustEmptySnapshot()).toString());
System.setProperty(ZOOKEEPER_JUTE_MAX_BUFFER, Integer.valueOf(zookeeperServerConfig.juteMaxBuffer()).toString());
writeConfigToDisk(zookeeperServerConfig);
zkServerThread = new Thread(this, "zookeeper server");
if (startServer) {
zkServerThread.start();
}
}
@Inject
public ZooKeeperServer(ZookeeperServerConfig zookeeperServerConfig) {
this(zookeeperServerConfig, true);
}
private void writeConfigToDisk(ZookeeperServerConfig config) {
String configFilePath = getDefaults().underVespaHome(config.zooKeeperConfigFile());
new File(configFilePath).getParentFile().mkdirs();
try (FileWriter writer = new FileWriter(configFilePath)) {
writer.write(transformConfigToString(config));
writeMyIdFile(config);
} catch (IOException e) {
throw new RuntimeException("Error writing zookeeper config", e);
}
}
private String transformConfigToString(ZookeeperServerConfig config) {
StringBuilder sb = new StringBuilder();
sb.append("tickTime=").append(config.tickTime()).append("\n");
sb.append("initLimit=").append(config.initLimit()).append("\n");
sb.append("syncLimit=").append(config.syncLimit()).append("\n");
sb.append("maxClientCnxns=").append(config.maxClientConnections()).append("\n");
sb.append("snapCount=").append(config.snapshotCount()).append("\n");
sb.append("dataDir=").append(getDefaults().underVespaHome(config.dataDir())).append("\n");
sb.append("clientPort=").append(config.clientPort()).append("\n");
sb.append("autopurge.purgeInterval=").append(config.autopurge().purgeInterval()).append("\n");
sb.append("autopurge.snapRetainCount=").append(config.autopurge().snapRetainCount()).append("\n");
sb.append("4lw.commands.whitelist=conf,cons,crst,dump,envi,mntr,ruok,srst,srvr,stat,wchs").append("\n");
ensureThisServerIsRepresented(config.myid(), config.server());
config.server().forEach(server -> addServerToCfg(sb, server));
return sb.toString();
}
private void writeMyIdFile(ZookeeperServerConfig config) throws IOException {
if (config.server().size() > 1) {
try (FileWriter writer = new FileWriter(getDefaults().underVespaHome(config.myidFile()))) {
writer.write(config.myid() + "\n");
}
}
}
private void ensureThisServerIsRepresented(int myid, List<ZookeeperServerConfig.Server> servers) {
boolean found = false;
for (ZookeeperServerConfig.Server server : servers) {
if (myid == server.id()) {
found = true;
break;
}
}
if (!found) {
throw new RuntimeException("No id in zookeeper server list that corresponds to my id(" + myid + ")");
}
}
private void addServerToCfg(StringBuilder sb, ZookeeperServerConfig.Server server) {
sb.append("server.").append(server.id()).append("=").append(server.hostname()).append(":").append(server.quorumPort()).append(":").append(server.electionPort()).append("\n");
}
private void shutdown() {
zkServerThread.interrupt();
try {
zkServerThread.join();
} catch (InterruptedException e) {
log.log(LogLevel.WARNING, "Error joining server thread on shutdown", e);
}
}
@Override
@Override
public void deconstruct() {
shutdown();
super.deconstruct();
}
public ZookeeperServerConfig getZookeeperServerConfig() { return zookeeperServerConfig; }
private static Set<String> zookeeperServerHostnames(ZookeeperServerConfig zookeeperServerConfig) {
return zookeeperServerConfig.server().stream().map(ZookeeperServerConfig.Server::hostname).collect(Collectors.toSet());
}
} | class ZooKeeperServer extends AbstractComponent implements Runnable {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(ZooKeeperServer.class.getName());
private static final String ZOOKEEPER_JMX_LOG4J_DISABLE = "zookeeper.jmx.log4j.disable";
static final String ZOOKEEPER_JUTE_MAX_BUFFER = "jute.maxbuffer";
private final Thread zkServerThread;
private final ZookeeperServerConfig zookeeperServerConfig;
ZooKeeperServer(ZookeeperServerConfig zookeeperServerConfig, boolean startServer) {
this.zookeeperServerConfig = zookeeperServerConfig;
System.setProperty("zookeeper.jmx.log4j.disable", "true");
System.setProperty("zookeeper.snapshot.trust.empty", Boolean.valueOf(zookeeperServerConfig.trustEmptySnapshot()).toString());
System.setProperty(ZOOKEEPER_JUTE_MAX_BUFFER, Integer.valueOf(zookeeperServerConfig.juteMaxBuffer()).toString());
writeConfigToDisk(zookeeperServerConfig);
zkServerThread = new Thread(this, "zookeeper server");
if (startServer) {
zkServerThread.start();
}
}
@Inject
public ZooKeeperServer(ZookeeperServerConfig zookeeperServerConfig) {
this(zookeeperServerConfig, true);
}
private void writeConfigToDisk(ZookeeperServerConfig config) {
String configFilePath = getDefaults().underVespaHome(config.zooKeeperConfigFile());
new File(configFilePath).getParentFile().mkdirs();
try (FileWriter writer = new FileWriter(configFilePath)) {
writer.write(transformConfigToString(config));
writeMyIdFile(config);
} catch (IOException e) {
throw new RuntimeException("Error writing zookeeper config", e);
}
}
private String transformConfigToString(ZookeeperServerConfig config) {
StringBuilder sb = new StringBuilder();
sb.append("tickTime=").append(config.tickTime()).append("\n");
sb.append("initLimit=").append(config.initLimit()).append("\n");
sb.append("syncLimit=").append(config.syncLimit()).append("\n");
sb.append("maxClientCnxns=").append(config.maxClientConnections()).append("\n");
sb.append("snapCount=").append(config.snapshotCount()).append("\n");
sb.append("dataDir=").append(getDefaults().underVespaHome(config.dataDir())).append("\n");
sb.append("clientPort=").append(config.clientPort()).append("\n");
sb.append("autopurge.purgeInterval=").append(config.autopurge().purgeInterval()).append("\n");
sb.append("autopurge.snapRetainCount=").append(config.autopurge().snapRetainCount()).append("\n");
sb.append("4lw.commands.whitelist=conf,cons,crst,dump,envi,mntr,ruok,srst,srvr,stat,wchs").append("\n");
ensureThisServerIsRepresented(config.myid(), config.server());
config.server().forEach(server -> addServerToCfg(sb, server));
return sb.toString();
}
private void writeMyIdFile(ZookeeperServerConfig config) throws IOException {
if (config.server().size() > 1) {
try (FileWriter writer = new FileWriter(getDefaults().underVespaHome(config.myidFile()))) {
writer.write(config.myid() + "\n");
}
}
}
private void ensureThisServerIsRepresented(int myid, List<ZookeeperServerConfig.Server> servers) {
boolean found = false;
for (ZookeeperServerConfig.Server server : servers) {
if (myid == server.id()) {
found = true;
break;
}
}
if (!found) {
throw new RuntimeException("No id in zookeeper server list that corresponds to my id(" + myid + ")");
}
}
private void addServerToCfg(StringBuilder sb, ZookeeperServerConfig.Server server) {
sb.append("server.").append(server.id()).append("=").append(server.hostname()).append(":").append(server.quorumPort()).append(":").append(server.electionPort()).append("\n");
}
private void shutdown() {
zkServerThread.interrupt();
try {
zkServerThread.join();
} catch (InterruptedException e) {
log.log(LogLevel.WARNING, "Error joining server thread on shutdown", e);
}
}
@Override
@Override
public void deconstruct() {
shutdown();
super.deconstruct();
}
public ZookeeperServerConfig getZookeeperServerConfig() { return zookeeperServerConfig; }
private static Set<String> zookeeperServerHostnames(ZookeeperServerConfig zookeeperServerConfig) {
return zookeeperServerConfig.server().stream().map(ZookeeperServerConfig.Server::hostname).collect(Collectors.toSet());
}
} |
Thanks, will do that in a later PR | public void run() {
System.setProperty(ZOOKEEPER_JMX_LOG4J_DISABLE, "true");
String[] args = new String[]{getDefaults().underVespaHome(zookeeperServerConfig.zooKeeperConfigFile())};
log.log(LogLevel.DEBUG, "Starting ZooKeeper server with config file " + args[0]);
log.log(LogLevel.INFO, "Trying to establish ZooKeeper quorum (from " + zookeeperServerHostnames(zookeeperServerConfig) + ")");
org.apache.zookeeper.server.quorum.QuorumPeerMain.main(args);
} | log.log(LogLevel.DEBUG, "Starting ZooKeeper server with config file " + args[0]); | public void run() {
System.setProperty(ZOOKEEPER_JMX_LOG4J_DISABLE, "true");
String[] args = new String[]{getDefaults().underVespaHome(zookeeperServerConfig.zooKeeperConfigFile())};
log.log(LogLevel.DEBUG, "Starting ZooKeeper server with config file " + args[0]);
log.log(LogLevel.INFO, "Trying to establish ZooKeeper quorum (from " + zookeeperServerHostnames(zookeeperServerConfig) + ")");
org.apache.zookeeper.server.quorum.QuorumPeerMain.main(args);
} | class ZooKeeperServer extends AbstractComponent implements Runnable {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(ZooKeeperServer.class.getName());
private static final String ZOOKEEPER_JMX_LOG4J_DISABLE = "zookeeper.jmx.log4j.disable";
static final String ZOOKEEPER_JUTE_MAX_BUFFER = "jute.maxbuffer";
private final Thread zkServerThread;
private final ZookeeperServerConfig zookeeperServerConfig;
ZooKeeperServer(ZookeeperServerConfig zookeeperServerConfig, boolean startServer) {
this.zookeeperServerConfig = zookeeperServerConfig;
System.setProperty("zookeeper.jmx.log4j.disable", "true");
System.setProperty("zookeeper.snapshot.trust.empty", Boolean.valueOf(zookeeperServerConfig.trustEmptySnapshot()).toString());
System.setProperty(ZOOKEEPER_JUTE_MAX_BUFFER, Integer.valueOf(zookeeperServerConfig.juteMaxBuffer()).toString());
writeConfigToDisk(zookeeperServerConfig);
zkServerThread = new Thread(this, "zookeeper server");
if (startServer) {
zkServerThread.start();
}
}
@Inject
public ZooKeeperServer(ZookeeperServerConfig zookeeperServerConfig) {
this(zookeeperServerConfig, true);
}
private void writeConfigToDisk(ZookeeperServerConfig config) {
String configFilePath = getDefaults().underVespaHome(config.zooKeeperConfigFile());
new File(configFilePath).getParentFile().mkdirs();
try (FileWriter writer = new FileWriter(configFilePath)) {
writer.write(transformConfigToString(config));
writeMyIdFile(config);
} catch (IOException e) {
throw new RuntimeException("Error writing zookeeper config", e);
}
}
private String transformConfigToString(ZookeeperServerConfig config) {
StringBuilder sb = new StringBuilder();
sb.append("tickTime=").append(config.tickTime()).append("\n");
sb.append("initLimit=").append(config.initLimit()).append("\n");
sb.append("syncLimit=").append(config.syncLimit()).append("\n");
sb.append("maxClientCnxns=").append(config.maxClientConnections()).append("\n");
sb.append("snapCount=").append(config.snapshotCount()).append("\n");
sb.append("dataDir=").append(getDefaults().underVespaHome(config.dataDir())).append("\n");
sb.append("clientPort=").append(config.clientPort()).append("\n");
sb.append("autopurge.purgeInterval=").append(config.autopurge().purgeInterval()).append("\n");
sb.append("autopurge.snapRetainCount=").append(config.autopurge().snapRetainCount()).append("\n");
sb.append("4lw.commands.whitelist=conf,cons,crst,dump,envi,mntr,ruok,srst,srvr,stat,wchs").append("\n");
ensureThisServerIsRepresented(config.myid(), config.server());
config.server().forEach(server -> addServerToCfg(sb, server));
return sb.toString();
}
private void writeMyIdFile(ZookeeperServerConfig config) throws IOException {
if (config.server().size() > 1) {
try (FileWriter writer = new FileWriter(getDefaults().underVespaHome(config.myidFile()))) {
writer.write(config.myid() + "\n");
}
}
}
private void ensureThisServerIsRepresented(int myid, List<ZookeeperServerConfig.Server> servers) {
boolean found = false;
for (ZookeeperServerConfig.Server server : servers) {
if (myid == server.id()) {
found = true;
break;
}
}
if (!found) {
throw new RuntimeException("No id in zookeeper server list that corresponds to my id(" + myid + ")");
}
}
private void addServerToCfg(StringBuilder sb, ZookeeperServerConfig.Server server) {
sb.append("server.").append(server.id()).append("=").append(server.hostname()).append(":").append(server.quorumPort()).append(":").append(server.electionPort()).append("\n");
}
private void shutdown() {
zkServerThread.interrupt();
try {
zkServerThread.join();
} catch (InterruptedException e) {
log.log(LogLevel.WARNING, "Error joining server thread on shutdown", e);
}
}
@Override
@Override
public void deconstruct() {
shutdown();
super.deconstruct();
}
public ZookeeperServerConfig getZookeeperServerConfig() { return zookeeperServerConfig; }
private static Set<String> zookeeperServerHostnames(ZookeeperServerConfig zookeeperServerConfig) {
return zookeeperServerConfig.server().stream().map(ZookeeperServerConfig.Server::hostname).collect(Collectors.toSet());
}
} | class ZooKeeperServer extends AbstractComponent implements Runnable {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(ZooKeeperServer.class.getName());
private static final String ZOOKEEPER_JMX_LOG4J_DISABLE = "zookeeper.jmx.log4j.disable";
static final String ZOOKEEPER_JUTE_MAX_BUFFER = "jute.maxbuffer";
private final Thread zkServerThread;
private final ZookeeperServerConfig zookeeperServerConfig;
ZooKeeperServer(ZookeeperServerConfig zookeeperServerConfig, boolean startServer) {
this.zookeeperServerConfig = zookeeperServerConfig;
System.setProperty("zookeeper.jmx.log4j.disable", "true");
System.setProperty("zookeeper.snapshot.trust.empty", Boolean.valueOf(zookeeperServerConfig.trustEmptySnapshot()).toString());
System.setProperty(ZOOKEEPER_JUTE_MAX_BUFFER, Integer.valueOf(zookeeperServerConfig.juteMaxBuffer()).toString());
writeConfigToDisk(zookeeperServerConfig);
zkServerThread = new Thread(this, "zookeeper server");
if (startServer) {
zkServerThread.start();
}
}
@Inject
public ZooKeeperServer(ZookeeperServerConfig zookeeperServerConfig) {
this(zookeeperServerConfig, true);
}
private void writeConfigToDisk(ZookeeperServerConfig config) {
String configFilePath = getDefaults().underVespaHome(config.zooKeeperConfigFile());
new File(configFilePath).getParentFile().mkdirs();
try (FileWriter writer = new FileWriter(configFilePath)) {
writer.write(transformConfigToString(config));
writeMyIdFile(config);
} catch (IOException e) {
throw new RuntimeException("Error writing zookeeper config", e);
}
}
private String transformConfigToString(ZookeeperServerConfig config) {
StringBuilder sb = new StringBuilder();
sb.append("tickTime=").append(config.tickTime()).append("\n");
sb.append("initLimit=").append(config.initLimit()).append("\n");
sb.append("syncLimit=").append(config.syncLimit()).append("\n");
sb.append("maxClientCnxns=").append(config.maxClientConnections()).append("\n");
sb.append("snapCount=").append(config.snapshotCount()).append("\n");
sb.append("dataDir=").append(getDefaults().underVespaHome(config.dataDir())).append("\n");
sb.append("clientPort=").append(config.clientPort()).append("\n");
sb.append("autopurge.purgeInterval=").append(config.autopurge().purgeInterval()).append("\n");
sb.append("autopurge.snapRetainCount=").append(config.autopurge().snapRetainCount()).append("\n");
sb.append("4lw.commands.whitelist=conf,cons,crst,dump,envi,mntr,ruok,srst,srvr,stat,wchs").append("\n");
ensureThisServerIsRepresented(config.myid(), config.server());
config.server().forEach(server -> addServerToCfg(sb, server));
return sb.toString();
}
private void writeMyIdFile(ZookeeperServerConfig config) throws IOException {
if (config.server().size() > 1) {
try (FileWriter writer = new FileWriter(getDefaults().underVespaHome(config.myidFile()))) {
writer.write(config.myid() + "\n");
}
}
}
private void ensureThisServerIsRepresented(int myid, List<ZookeeperServerConfig.Server> servers) {
boolean found = false;
for (ZookeeperServerConfig.Server server : servers) {
if (myid == server.id()) {
found = true;
break;
}
}
if (!found) {
throw new RuntimeException("No id in zookeeper server list that corresponds to my id(" + myid + ")");
}
}
private void addServerToCfg(StringBuilder sb, ZookeeperServerConfig.Server server) {
sb.append("server.").append(server.id()).append("=").append(server.hostname()).append(":").append(server.quorumPort()).append(":").append(server.electionPort()).append("\n");
}
private void shutdown() {
zkServerThread.interrupt();
try {
zkServerThread.join();
} catch (InterruptedException e) {
log.log(LogLevel.WARNING, "Error joining server thread on shutdown", e);
}
}
@Override
@Override
public void deconstruct() {
shutdown();
super.deconstruct();
}
public ZookeeperServerConfig getZookeeperServerConfig() { return zookeeperServerConfig; }
private static Set<String> zookeeperServerHostnames(ZookeeperServerConfig zookeeperServerConfig) {
return zookeeperServerConfig.server().stream().map(ZookeeperServerConfig.Server::hostname).collect(Collectors.toSet());
}
} |
Consider using `Collectors.toUnmodifiableMap`, and `collectingAndThen(...)` with a specific map type if order needs to be preserved. This will probably get rid of the cast as well. | public DeploymentJobs(Collection<JobStatus> jobStatusEntries) {
this.status = ImmutableMap.copyOf((Iterable<Map.Entry<JobType, JobStatus>>)
jobStatusEntries.stream()
.map(job -> Map.entry(job.type(), job))::iterator);
} | .map(job -> Map.entry(job.type(), job))::iterator); | public DeploymentJobs(Collection<JobStatus> jobStatusEntries) {
this.status = ImmutableMap.copyOf((Iterable<Map.Entry<JobType, JobStatus>>)
jobStatusEntries.stream()
.map(job -> Map.entry(job.type(), job))::iterator);
} | class DeploymentJobs {
private final ImmutableMap<JobType, JobStatus> status;
/** Return a new instance with the given job update applied. */
public DeploymentJobs withUpdate(JobType jobType, UnaryOperator<JobStatus> update) {
Map<JobType, JobStatus> status = new LinkedHashMap<>(this.status);
status.compute(jobType, (type, job) -> {
if (job == null) job = JobStatus.initial(jobType);
return update.apply(job);
});
return new DeploymentJobs(status.values());
}
/** Return a new instance with the given completion */
public DeploymentJobs withCompletion(JobType jobType, JobStatus.JobRun completion, Optional<JobError> jobError) {
return withUpdate(jobType, job -> job.withCompletion(completion, jobError));
}
public DeploymentJobs withTriggering(JobType jobType, JobStatus.JobRun jobRun) {
return withUpdate(jobType, job -> job.withTriggering(jobRun));
}
public DeploymentJobs withPause(JobType jobType, OptionalLong pausedUntil) {
return withUpdate(jobType, job -> job.withPause(pausedUntil));
}
public DeploymentJobs without(JobType job) {
Map<JobType, JobStatus> status = new LinkedHashMap<>(this.status);
status.remove(job);
return new DeploymentJobs(status.values());
}
/** Returns an immutable map of the status entries in this */
public Map<JobType, JobStatus> jobStatus() { return status; }
/** Returns whether this has some job status which is not a success */
public boolean hasFailures() {
return ! JobList.from(status.values())
.failing()
.not().failingBecause(JobError.outOfCapacity)
.isEmpty();
}
/** Returns the JobStatus of the given JobType, or empty. */
public Optional<JobStatus> statusOf(JobType jobType) {
return Optional.ofNullable(jobStatus().get(jobType));
}
/** A job report. This class is immutable. */
public static class JobReport {
private final ApplicationId applicationId;
private final JobType jobType;
private final long projectId;
private final long buildNumber;
private final Optional<ApplicationVersion> version;
private final Optional<JobError> jobError;
private JobReport(ApplicationId applicationId, JobType jobType, long projectId, long buildNumber,
Optional<JobError> jobError, Optional<ApplicationVersion> version) {
Objects.requireNonNull(applicationId, "applicationId cannot be null");
Objects.requireNonNull(jobType, "jobType cannot be null");
Objects.requireNonNull(jobError, "jobError cannot be null");
Objects.requireNonNull(version, "version cannot be null");
if (version.isPresent() && version.get().buildNumber().isPresent() && version.get().buildNumber().getAsLong() != buildNumber)
throw new IllegalArgumentException("Build number in application version must match the one given here.");
this.applicationId = applicationId;
this.projectId = projectId;
this.buildNumber = buildNumber;
this.jobType = jobType;
this.jobError = jobError;
this.version = version;
}
public static JobReport ofComponent(ApplicationId applicationId, long projectId, long buildNumber,
Optional<JobError> jobError, SourceRevision sourceRevision) {
return new JobReport(applicationId, JobType.component, projectId, buildNumber,
jobError, Optional.of(ApplicationVersion.from(sourceRevision, buildNumber)));
}
public static JobReport ofSubmission(ApplicationId applicationId, long projectId, ApplicationVersion version) {
return new JobReport(applicationId, JobType.component, projectId, version.buildNumber().getAsLong(),
Optional.empty(), Optional.of(version));
}
public static JobReport ofJob(ApplicationId applicationId, JobType jobType, long buildNumber, Optional<JobError> jobError) {
return new JobReport(applicationId, jobType, -1, buildNumber, jobError, Optional.empty());
}
public ApplicationId applicationId() { return applicationId; }
public JobType jobType() { return jobType; }
public long projectId() { return projectId; }
public long buildNumber() { return buildNumber; }
public boolean success() { return ! jobError.isPresent(); }
public Optional<ApplicationVersion> version() { return version; }
public Optional<JobError> jobError() { return jobError; }
public BuildService.BuildJob buildJob() { return BuildService.BuildJob.of(applicationId, projectId, jobType.jobName()); }
}
public enum JobError {
unknown,
outOfCapacity
}
} | class DeploymentJobs {
private final ImmutableMap<JobType, JobStatus> status;
/** Return a new instance with the given job update applied. */
public DeploymentJobs withUpdate(JobType jobType, UnaryOperator<JobStatus> update) {
Map<JobType, JobStatus> status = new LinkedHashMap<>(this.status);
status.compute(jobType, (type, job) -> {
if (job == null) job = JobStatus.initial(jobType);
return update.apply(job);
});
return new DeploymentJobs(status.values());
}
/** Return a new instance with the given completion */
public DeploymentJobs withCompletion(JobType jobType, JobStatus.JobRun completion, Optional<JobError> jobError) {
return withUpdate(jobType, job -> job.withCompletion(completion, jobError));
}
public DeploymentJobs withTriggering(JobType jobType, JobStatus.JobRun jobRun) {
return withUpdate(jobType, job -> job.withTriggering(jobRun));
}
public DeploymentJobs withPause(JobType jobType, OptionalLong pausedUntil) {
return withUpdate(jobType, job -> job.withPause(pausedUntil));
}
public DeploymentJobs without(JobType job) {
Map<JobType, JobStatus> status = new LinkedHashMap<>(this.status);
status.remove(job);
return new DeploymentJobs(status.values());
}
/** Returns an immutable map of the status entries in this */
public Map<JobType, JobStatus> jobStatus() { return status; }
/** Returns whether this has some job status which is not a success */
public boolean hasFailures() {
return ! JobList.from(status.values())
.failing()
.not().failingBecause(JobError.outOfCapacity)
.isEmpty();
}
/** Returns the JobStatus of the given JobType, or empty. */
public Optional<JobStatus> statusOf(JobType jobType) {
return Optional.ofNullable(jobStatus().get(jobType));
}
/** A job report. This class is immutable. */
public static class JobReport {
private final ApplicationId applicationId;
private final JobType jobType;
private final long projectId;
private final long buildNumber;
private final Optional<ApplicationVersion> version;
private final Optional<JobError> jobError;
private JobReport(ApplicationId applicationId, JobType jobType, long projectId, long buildNumber,
Optional<JobError> jobError, Optional<ApplicationVersion> version) {
Objects.requireNonNull(applicationId, "applicationId cannot be null");
Objects.requireNonNull(jobType, "jobType cannot be null");
Objects.requireNonNull(jobError, "jobError cannot be null");
Objects.requireNonNull(version, "version cannot be null");
if (version.isPresent() && version.get().buildNumber().isPresent() && version.get().buildNumber().getAsLong() != buildNumber)
throw new IllegalArgumentException("Build number in application version must match the one given here.");
this.applicationId = applicationId;
this.projectId = projectId;
this.buildNumber = buildNumber;
this.jobType = jobType;
this.jobError = jobError;
this.version = version;
}
public static JobReport ofComponent(ApplicationId applicationId, long projectId, long buildNumber,
Optional<JobError> jobError, SourceRevision sourceRevision) {
return new JobReport(applicationId, JobType.component, projectId, buildNumber,
jobError, Optional.of(ApplicationVersion.from(sourceRevision, buildNumber)));
}
public static JobReport ofSubmission(ApplicationId applicationId, long projectId, ApplicationVersion version) {
return new JobReport(applicationId, JobType.component, projectId, version.buildNumber().getAsLong(),
Optional.empty(), Optional.of(version));
}
public static JobReport ofJob(ApplicationId applicationId, JobType jobType, long buildNumber, Optional<JobError> jobError) {
return new JobReport(applicationId, jobType, -1, buildNumber, jobError, Optional.empty());
}
public ApplicationId applicationId() { return applicationId; }
public JobType jobType() { return jobType; }
public long projectId() { return projectId; }
public long buildNumber() { return buildNumber; }
public boolean success() { return ! jobError.isPresent(); }
public Optional<ApplicationVersion> version() { return version; }
public Optional<JobError> jobError() { return jobError; }
public BuildService.BuildJob buildJob() { return BuildService.BuildJob.of(applicationId, projectId, jobType.jobName()); }
}
public enum JobError {
unknown,
outOfCapacity
}
} |
Shouldn't this be `removeAll`? Or just use a `LinkedHashSet` and let the constructor convert it to a list. | public LockedApplication withPemDeployKey(String pemDeployKey) {
List<String> keys = new ArrayList<>(pemDeployKeys);
keys.remove(pemDeployKey);
keys.add(pemDeployKey);
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, keys,
projectId, internal, instances);
} | keys.remove(pemDeployKey); | public LockedApplication withPemDeployKey(String pemDeployKey) {
Set<String> keys = new LinkedHashSet<>(pemDeployKeys);
keys.add(pemDeployKey);
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, keys,
projectId, internal, instances);
} | class LockedApplication {
private final Lock lock;
private final TenantAndApplicationId id;
private final Instant createdAt;
private final DeploymentSpec deploymentSpec;
private final ValidationOverrides validationOverrides;
private final Change change;
private final Change outstandingChange;
private final Optional<IssueId> deploymentIssueId;
private final Optional<IssueId> ownershipIssueId;
private final Optional<User> owner;
private final OptionalInt majorVersion;
private final ApplicationMetrics metrics;
private final List<String> pemDeployKeys;
private final OptionalLong projectId;
private final boolean internal;
private final Map<InstanceName, Instance> instances;
/**
* Used to create a locked application
*
* @param application The application to lock.
* @param lock The lock for the application.
*/
LockedApplication(Application application, Lock lock) {
this(Objects.requireNonNull(lock, "lock cannot be null"), application.id(), application.createdAt(),
application.deploymentSpec(), application.validationOverrides(), application.change(),
application.outstandingChange(), application.deploymentIssueId(), application.ownershipIssueId(),
application.owner(), application.majorVersion(), application.metrics(), application.pemDeployKeys(),
application.projectId(), application.internal(), application.instances());
}
private LockedApplication(Lock lock, TenantAndApplicationId id, Instant createdAt, DeploymentSpec deploymentSpec,
ValidationOverrides validationOverrides, Change change, Change outstandingChange,
Optional<IssueId> deploymentIssueId, Optional<IssueId> ownershipIssueId, Optional<User> owner,
OptionalInt majorVersion, ApplicationMetrics metrics, List<String> pemDeployKeys,
OptionalLong projectId, boolean internal, Map<InstanceName, Instance> instances) {
this.lock = lock;
this.id = id;
this.createdAt = createdAt;
this.deploymentSpec = deploymentSpec;
this.validationOverrides = validationOverrides;
this.change = change;
this.outstandingChange = outstandingChange;
this.deploymentIssueId = deploymentIssueId;
this.ownershipIssueId = ownershipIssueId;
this.owner = owner;
this.majorVersion = majorVersion;
this.metrics = metrics;
this.pemDeployKeys = pemDeployKeys;
this.projectId = projectId;
this.internal = internal;
this.instances = Map.copyOf(instances);
}
/** Returns a read-only copy of this */
public Application get() {
return new Application(id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances.values());
}
public LockedApplication withNewInstance(InstanceName instance) {
var instances = new HashMap<>(this.instances);
instances.put(instance, new Instance(id.instance(instance)));
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication with(InstanceName instance, UnaryOperator<Instance> modification) {
var instances = new HashMap<>(this.instances);
instances.put(instance, modification.apply(instances.get(instance)));
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication without(InstanceName instance) {
var instances = new HashMap<>(this.instances);
instances.remove(instance);
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withBuiltInternally(boolean builtInternally) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, builtInternally, instances);
}
public LockedApplication withProjectId(OptionalLong projectId) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withDeploymentIssueId(IssueId issueId) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
Optional.ofNullable(issueId), ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication with(DeploymentSpec deploymentSpec) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication with(ValidationOverrides validationOverrides) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withChange(Change change) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withOutstandingChange(Change outstandingChange) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withOwnershipIssueId(IssueId issueId) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, Optional.of(issueId), owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withOwner(User owner) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, Optional.of(owner), majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
/** Set a major version for this, or set to null to remove any major version override */
public LockedApplication withMajorVersion(Integer majorVersion) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner,
majorVersion == null ? OptionalInt.empty() : OptionalInt.of(majorVersion),
metrics, pemDeployKeys, projectId, internal, instances);
}
public LockedApplication with(ApplicationMetrics metrics) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withoutPemDeployKey(String pemDeployKey) {
List<String> keys = new ArrayList<>(pemDeployKeys);
keys.remove(pemDeployKey);
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, keys,
projectId, internal, instances);
}
@Override
public String toString() {
return "application '" + id + "'";
}
} | class LockedApplication {
private final Lock lock;
private final TenantAndApplicationId id;
private final Instant createdAt;
private final DeploymentSpec deploymentSpec;
private final ValidationOverrides validationOverrides;
private final Change change;
private final Change outstandingChange;
private final Optional<IssueId> deploymentIssueId;
private final Optional<IssueId> ownershipIssueId;
private final Optional<User> owner;
private final OptionalInt majorVersion;
private final ApplicationMetrics metrics;
private final Set<String> pemDeployKeys;
private final OptionalLong projectId;
private final boolean internal;
private final Map<InstanceName, Instance> instances;
/**
* Used to create a locked application
*
* @param application The application to lock.
* @param lock The lock for the application.
*/
LockedApplication(Application application, Lock lock) {
this(Objects.requireNonNull(lock, "lock cannot be null"), application.id(), application.createdAt(),
application.deploymentSpec(), application.validationOverrides(), application.change(),
application.outstandingChange(), application.deploymentIssueId(), application.ownershipIssueId(),
application.owner(), application.majorVersion(), application.metrics(), application.pemDeployKeys(),
application.projectId(), application.internal(), application.instances());
}
private LockedApplication(Lock lock, TenantAndApplicationId id, Instant createdAt, DeploymentSpec deploymentSpec,
ValidationOverrides validationOverrides, Change change, Change outstandingChange,
Optional<IssueId> deploymentIssueId, Optional<IssueId> ownershipIssueId, Optional<User> owner,
OptionalInt majorVersion, ApplicationMetrics metrics, Set<String> pemDeployKeys,
OptionalLong projectId, boolean internal,
Map<InstanceName, Instance> instances) {
this.lock = lock;
this.id = id;
this.createdAt = createdAt;
this.deploymentSpec = deploymentSpec;
this.validationOverrides = validationOverrides;
this.change = change;
this.outstandingChange = outstandingChange;
this.deploymentIssueId = deploymentIssueId;
this.ownershipIssueId = ownershipIssueId;
this.owner = owner;
this.majorVersion = majorVersion;
this.metrics = metrics;
this.pemDeployKeys = pemDeployKeys;
this.projectId = projectId;
this.internal = internal;
this.instances = Map.copyOf(instances);
}
/** Returns a read-only copy of this */
public Application get() {
return new Application(id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances.values());
}
public LockedApplication withNewInstance(InstanceName instance) {
var instances = new HashMap<>(this.instances);
instances.put(instance, new Instance(id.instance(instance)));
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication with(InstanceName instance, UnaryOperator<Instance> modification) {
var instances = new HashMap<>(this.instances);
instances.put(instance, modification.apply(instances.get(instance)));
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication without(InstanceName instance) {
var instances = new HashMap<>(this.instances);
instances.remove(instance);
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withBuiltInternally(boolean builtInternally) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, builtInternally, instances);
}
public LockedApplication withProjectId(OptionalLong projectId) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withDeploymentIssueId(IssueId issueId) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
Optional.ofNullable(issueId), ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication with(DeploymentSpec deploymentSpec) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication with(ValidationOverrides validationOverrides) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withChange(Change change) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withOutstandingChange(Change outstandingChange) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withOwnershipIssueId(IssueId issueId) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, Optional.of(issueId), owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withOwner(User owner) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, Optional.of(owner), majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
/** Set a major version for this, or set to null to remove any major version override */
public LockedApplication withMajorVersion(Integer majorVersion) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner,
majorVersion == null ? OptionalInt.empty() : OptionalInt.of(majorVersion),
metrics, pemDeployKeys, projectId, internal, instances);
}
public LockedApplication with(ApplicationMetrics metrics) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withoutPemDeployKey(String pemDeployKey) {
Set<String> keys = new LinkedHashSet<>(pemDeployKeys);
keys.remove(pemDeployKey);
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, keys,
projectId, internal, instances);
}
@Override
public String toString() {
return "application '" + id + "'";
}
} |
Throwing away old keys is fine? | public Application fromSlime(Slime slime) {
Inspector root = slime.get();
TenantAndApplicationId id = TenantAndApplicationId.fromSerialized(root.field(idField).asString());
Instant createdAt = Instant.ofEpochMilli(root.field(createdAtField).asLong());
DeploymentSpec deploymentSpec = DeploymentSpec.fromXml(root.field(deploymentSpecField).asString(), false);
ValidationOverrides validationOverrides = ValidationOverrides.fromXml(root.field(validationOverridesField).asString());
Change deploying = changeFromSlime(root.field(deployingField));
Change outstandingChange = changeFromSlime(root.field(outstandingChangeField));
Optional<IssueId> deploymentIssueId = Serializers.optionalString(root.field(deploymentIssueField)).map(IssueId::from);
Optional<IssueId> ownershipIssueId = Serializers.optionalString(root.field(ownershipIssueIdField)).map(IssueId::from);
Optional<User> owner = Serializers.optionalString(root.field(ownerField)).map(User::from);
OptionalInt majorVersion = Serializers.optionalInteger(root.field(majorVersionField));
ApplicationMetrics metrics = new ApplicationMetrics(root.field(queryQualityField).asDouble(),
root.field(writeQualityField).asDouble());
List<String> pemDeployKeys = pemDeployKeysFromSlime(root.field(pemDeployKeysField));
List<Instance> instances = instancesFromSlime(id, deploymentSpec, root.field(instancesField));
OptionalLong projectId = Serializers.optionalLong(root.field(projectIdField));
boolean builtInternally = root.field(builtInternallyField).asBool();
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
pemDeployKeys, projectId, builtInternally, instances);
} | List<String> pemDeployKeys = pemDeployKeysFromSlime(root.field(pemDeployKeysField)); | public Application fromSlime(Slime slime) {
Inspector root = slime.get();
TenantAndApplicationId id = TenantAndApplicationId.fromSerialized(root.field(idField).asString());
Instant createdAt = Instant.ofEpochMilli(root.field(createdAtField).asLong());
DeploymentSpec deploymentSpec = DeploymentSpec.fromXml(root.field(deploymentSpecField).asString(), false);
ValidationOverrides validationOverrides = ValidationOverrides.fromXml(root.field(validationOverridesField).asString());
Change deploying = changeFromSlime(root.field(deployingField));
Change outstandingChange = changeFromSlime(root.field(outstandingChangeField));
Optional<IssueId> deploymentIssueId = Serializers.optionalString(root.field(deploymentIssueField)).map(IssueId::from);
Optional<IssueId> ownershipIssueId = Serializers.optionalString(root.field(ownershipIssueIdField)).map(IssueId::from);
Optional<User> owner = Serializers.optionalString(root.field(ownerField)).map(User::from);
OptionalInt majorVersion = Serializers.optionalInteger(root.field(majorVersionField));
ApplicationMetrics metrics = new ApplicationMetrics(root.field(queryQualityField).asDouble(),
root.field(writeQualityField).asDouble());
Set<String> pemDeployKeys = pemDeployKeysFromSlime(root.field(pemDeployKeysField));
List<Instance> instances = instancesFromSlime(id, deploymentSpec, root.field(instancesField));
OptionalLong projectId = Serializers.optionalLong(root.field(projectIdField));
boolean builtInternally = root.field(builtInternallyField).asBool();
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
pemDeployKeys, projectId, builtInternally, instances);
} | class ApplicationSerializer {
private static final String idField = "id";
private static final String createdAtField = "createdAt";
private static final String deploymentSpecField = "deploymentSpecField";
private static final String validationOverridesField = "validationOverrides";
private static final String instancesField = "instances";
private static final String deployingField = "deployingField";
private static final String projectIdField = "projectId";
private static final String builtInternallyField = "builtInternally";
private static final String pinnedField = "pinned";
private static final String outstandingChangeField = "outstandingChangeField";
private static final String deploymentIssueField = "deploymentIssueId";
private static final String ownershipIssueIdField = "ownershipIssueId";
private static final String ownerField = "confirmedOwner";
private static final String majorVersionField = "majorVersion";
private static final String writeQualityField = "writeQuality";
private static final String queryQualityField = "queryQuality";
private static final String pemDeployKeysField = "pemDeployKeys";
private static final String assignedRotationClusterField = "clusterId";
private static final String assignedRotationRotationField = "rotationId";
private static final String applicationCertificateField = "applicationCertificate";
private static final String instanceNameField = "instanceName";
private static final String deploymentsField = "deployments";
private static final String deploymentJobsField = "deploymentJobs";
private static final String assignedRotationsField = "assignedRotations";
private static final String assignedRotationEndpointField = "endpointId";
private static final String zoneField = "zone";
private static final String environmentField = "environment";
private static final String regionField = "region";
private static final String deployTimeField = "deployTime";
private static final String applicationBuildNumberField = "applicationBuildNumber";
private static final String applicationPackageRevisionField = "applicationPackageRevision";
private static final String sourceRevisionField = "sourceRevision";
private static final String repositoryField = "repositoryField";
private static final String branchField = "branchField";
private static final String commitField = "commitField";
private static final String authorEmailField = "authorEmailField";
private static final String compileVersionField = "compileVersion";
private static final String buildTimeField = "buildTime";
private static final String lastQueriedField = "lastQueried";
private static final String lastWrittenField = "lastWritten";
private static final String lastQueriesPerSecondField = "lastQueriesPerSecond";
private static final String lastWritesPerSecondField = "lastWritesPerSecond";
private static final String jobStatusField = "jobStatus";
private static final String jobTypeField = "jobType";
private static final String errorField = "jobError";
private static final String lastTriggeredField = "lastTriggered";
private static final String lastCompletedField = "lastCompleted";
private static final String firstFailingField = "firstFailing";
private static final String lastSuccessField = "lastSuccess";
private static final String pausedUntilField = "pausedUntil";
private static final String jobRunIdField = "id";
private static final String versionField = "version";
private static final String revisionField = "revision";
private static final String sourceVersionField = "sourceVersion";
private static final String sourceApplicationField = "sourceRevision";
private static final String reasonField = "reason";
private static final String atField = "at";
private static final String clusterInfoField = "clusterInfo";
private static final String clusterInfoFlavorField = "flavor";
private static final String clusterInfoCostField = "cost";
private static final String clusterInfoCpuField = "flavorCpu";
private static final String clusterInfoMemField = "flavorMem";
private static final String clusterInfoDiskField = "flavorDisk";
private static final String clusterInfoTypeField = "clusterType";
private static final String clusterInfoHostnamesField = "hostnames";
private static final String clusterUtilsField = "clusterUtils";
private static final String clusterUtilsCpuField = "cpu";
private static final String clusterUtilsMemField = "mem";
private static final String clusterUtilsDiskField = "disk";
private static final String clusterUtilsDiskBusyField = "diskbusy";
private static final String deploymentMetricsField = "metrics";
private static final String deploymentMetricsQPSField = "queriesPerSecond";
private static final String deploymentMetricsWPSField = "writesPerSecond";
private static final String deploymentMetricsDocsField = "documentCount";
private static final String deploymentMetricsQueryLatencyField = "queryLatencyMillis";
private static final String deploymentMetricsWriteLatencyField = "writeLatencyMillis";
private static final String deploymentMetricsUpdateTime = "lastUpdated";
private static final String deploymentMetricsWarningsField = "warnings";
private static final String rotationStatusField = "rotationStatus2";
private static final String rotationIdField = "rotationId";
private static final String rotationStateField = "state";
private static final String statusField = "status";
public Slime toSlime(Application application) {
Slime slime = new Slime();
Cursor root = slime.setObject();
root.setString(idField, application.id().serialized());
root.setLong(createdAtField, application.createdAt().toEpochMilli());
root.setString(deploymentSpecField, application.deploymentSpec().xmlForm());
root.setString(validationOverridesField, application.validationOverrides().xmlForm());
application.projectId().ifPresent(projectId -> root.setLong(projectIdField, projectId));
application.deploymentIssueId().ifPresent(jiraIssueId -> root.setString(deploymentIssueField, jiraIssueId.value()));
application.ownershipIssueId().ifPresent(issueId -> root.setString(ownershipIssueIdField, issueId.value()));
root.setBool(builtInternallyField, application.internal());
toSlime(application.change(), root, deployingField);
toSlime(application.outstandingChange(), root, outstandingChangeField);
application.owner().ifPresent(owner -> root.setString(ownerField, owner.username()));
application.majorVersion().ifPresent(majorVersion -> root.setLong(majorVersionField, majorVersion));
root.setDouble(queryQualityField, application.metrics().queryServiceQuality());
root.setDouble(writeQualityField, application.metrics().writeServiceQuality());
deployKeysToSlime(application.pemDeployKeys().stream(), root.setArray(pemDeployKeysField));
instancesToSlime(application, root.setArray(instancesField));
return slime;
}
private void instancesToSlime(Application application, Cursor array) {
for (Instance instance : application.instances().values()) {
Cursor instanceObject = array.addObject();
instanceObject.setString(instanceNameField, instance.name().value());
deploymentsToSlime(instance.deployments().values(), instanceObject.setArray(deploymentsField));
toSlime(instance.deploymentJobs(), instanceObject.setObject(deploymentJobsField));
assignedRotationsToSlime(instance.rotations(), instanceObject, assignedRotationsField);
toSlime(instance.rotationStatus(), instanceObject.setArray(rotationStatusField));
}
}
private void deployKeysToSlime(Stream<String> pemDeployKeys, Cursor array) {
pemDeployKeys.forEach(array::addString);
}
private void deploymentsToSlime(Collection<Deployment> deployments, Cursor array) {
for (Deployment deployment : deployments)
deploymentToSlime(deployment, array.addObject());
}
private void deploymentToSlime(Deployment deployment, Cursor object) {
zoneIdToSlime(deployment.zone(), object.setObject(zoneField));
object.setString(versionField, deployment.version().toString());
object.setLong(deployTimeField, deployment.at().toEpochMilli());
toSlime(deployment.applicationVersion(), object.setObject(applicationPackageRevisionField));
clusterInfoToSlime(deployment.clusterInfo(), object);
clusterUtilsToSlime(deployment.clusterUtils(), object);
deploymentMetricsToSlime(deployment.metrics(), object);
deployment.activity().lastQueried().ifPresent(instant -> object.setLong(lastQueriedField, instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> object.setLong(lastWrittenField, instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> object.setDouble(lastQueriesPerSecondField, value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> object.setDouble(lastWritesPerSecondField, value));
}
private void deploymentMetricsToSlime(DeploymentMetrics metrics, Cursor object) {
Cursor root = object.setObject(deploymentMetricsField);
root.setDouble(deploymentMetricsQPSField, metrics.queriesPerSecond());
root.setDouble(deploymentMetricsWPSField, metrics.writesPerSecond());
root.setDouble(deploymentMetricsDocsField, metrics.documentCount());
root.setDouble(deploymentMetricsQueryLatencyField, metrics.queryLatencyMillis());
root.setDouble(deploymentMetricsWriteLatencyField, metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> root.setLong(deploymentMetricsUpdateTime, instant.toEpochMilli()));
if (!metrics.warnings().isEmpty()) {
Cursor warningsObject = root.setObject(deploymentMetricsWarningsField);
metrics.warnings().forEach((warning, count) -> warningsObject.setLong(warning.name(), count));
}
}
private void clusterInfoToSlime(Map<ClusterSpec.Id, ClusterInfo> clusters, Cursor object) {
Cursor root = object.setObject(clusterInfoField);
for (Map.Entry<ClusterSpec.Id, ClusterInfo> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterInfo info, Cursor object) {
object.setString(clusterInfoFlavorField, info.getFlavor());
object.setLong(clusterInfoCostField, info.getFlavorCost());
object.setDouble(clusterInfoCpuField, info.getFlavorCPU());
object.setDouble(clusterInfoMemField, info.getFlavorMem());
object.setDouble(clusterInfoDiskField, info.getFlavorDisk());
object.setString(clusterInfoTypeField, info.getClusterType().name());
Cursor array = object.setArray(clusterInfoHostnamesField);
for (String host : info.getHostnames()) {
array.addString(host);
}
}
private void clusterUtilsToSlime(Map<ClusterSpec.Id, ClusterUtilization> clusters, Cursor object) {
Cursor root = object.setObject(clusterUtilsField);
for (Map.Entry<ClusterSpec.Id, ClusterUtilization> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterUtilization utils, Cursor object) {
object.setDouble(clusterUtilsCpuField, utils.getCpu());
object.setDouble(clusterUtilsMemField, utils.getMemory());
object.setDouble(clusterUtilsDiskField, utils.getDisk());
object.setDouble(clusterUtilsDiskBusyField, utils.getDiskBusy());
}
private void zoneIdToSlime(ZoneId zone, Cursor object) {
object.setString(environmentField, zone.environment().value());
object.setString(regionField, zone.region().value());
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if (applicationVersion.buildNumber().isPresent() && applicationVersion.source().isPresent()) {
object.setLong(applicationBuildNumberField, applicationVersion.buildNumber().getAsLong());
toSlime(applicationVersion.source().get(), object.setObject(sourceRevisionField));
applicationVersion.authorEmail().ifPresent(email -> object.setString(authorEmailField, email));
applicationVersion.compileVersion().ifPresent(version -> object.setString(compileVersionField, version.toString()));
applicationVersion.buildTime().ifPresent(time -> object.setLong(buildTimeField, time.toEpochMilli()));
}
}
private void toSlime(SourceRevision sourceRevision, Cursor object) {
object.setString(repositoryField, sourceRevision.repository());
object.setString(branchField, sourceRevision.branch());
object.setString(commitField, sourceRevision.commit());
}
private void toSlime(DeploymentJobs deploymentJobs, Cursor cursor) {
jobStatusToSlime(deploymentJobs.jobStatus().values(), cursor.setArray(jobStatusField));
}
private void jobStatusToSlime(Collection<JobStatus> jobStatuses, Cursor jobStatusArray) {
for (JobStatus jobStatus : jobStatuses)
toSlime(jobStatus, jobStatusArray.addObject());
}
private void toSlime(JobStatus jobStatus, Cursor object) {
object.setString(jobTypeField, jobStatus.type().jobName());
if (jobStatus.jobError().isPresent())
object.setString(errorField, jobStatus.jobError().get().name());
jobStatus.lastTriggered().ifPresent(run -> jobRunToSlime(run, object, lastTriggeredField));
jobStatus.lastCompleted().ifPresent(run -> jobRunToSlime(run, object, lastCompletedField));
jobStatus.lastSuccess().ifPresent(run -> jobRunToSlime(run, object, lastSuccessField));
jobStatus.firstFailing().ifPresent(run -> jobRunToSlime(run, object, firstFailingField));
jobStatus.pausedUntil().ifPresent(until -> object.setLong(pausedUntilField, until));
}
private void jobRunToSlime(JobStatus.JobRun jobRun, Cursor parent, String jobRunObjectName) {
Cursor object = parent.setObject(jobRunObjectName);
object.setLong(jobRunIdField, jobRun.id());
object.setString(versionField, jobRun.platform().toString());
toSlime(jobRun.application(), object.setObject(revisionField));
jobRun.sourcePlatform().ifPresent(version -> object.setString(sourceVersionField, version.toString()));
jobRun.sourceApplication().ifPresent(version -> toSlime(version, object.setObject(sourceApplicationField)));
object.setString(reasonField, jobRun.reason());
object.setLong(atField, jobRun.at().toEpochMilli());
}
private void toSlime(Change deploying, Cursor parentObject, String fieldName) {
if (deploying.isEmpty()) return;
Cursor object = parentObject.setObject(fieldName);
if (deploying.platform().isPresent())
object.setString(versionField, deploying.platform().get().toString());
if (deploying.application().isPresent())
toSlime(deploying.application().get(), object);
if (deploying.isPinned())
object.setBool(pinnedField, true);
}
private void toSlime(RotationStatus status, Cursor array) {
status.asMap().forEach((rotationId, zoneStatus) -> {
Cursor rotationObject = array.addObject();
rotationObject.setString(rotationIdField, rotationId.asString());
Cursor statusArray = rotationObject.setArray(statusField);
zoneStatus.forEach((zone, state) -> {
Cursor statusObject = statusArray.addObject();
zoneIdToSlime(zone, statusObject);
statusObject.setString(rotationStateField, state.name());
});
});
}
private void assignedRotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) {
var rotationsArray = parent.setArray(fieldName);
for (var rotation : rotations) {
var object = rotationsArray.addObject();
object.setString(assignedRotationEndpointField, rotation.endpointId().id());
object.setString(assignedRotationRotationField, rotation.rotationId().asString());
object.setString(assignedRotationClusterField, rotation.clusterId().value());
}
}
private List<Instance> instancesFromSlime(TenantAndApplicationId id, DeploymentSpec deploymentSpec, Inspector field) {
List<Instance> instances = new ArrayList<>();
field.traverse((ArrayTraverser) (name, object) -> {
InstanceName instanceName = InstanceName.from(object.field(instanceNameField).asString());
List<Deployment> deployments = deploymentsFromSlime(object.field(deploymentsField));
DeploymentJobs deploymentJobs = deploymentJobsFromSlime(object.field(deploymentJobsField));
List<AssignedRotation> assignedRotations = assignedRotationsFromSlime(deploymentSpec, object);
RotationStatus rotationStatus = rotationStatusFromSlime(object);
instances.add(new Instance(id.instance(instanceName),
deployments,
deploymentJobs,
assignedRotations,
rotationStatus));
});
return instances;
}
private List<String> pemDeployKeysFromSlime(Inspector array) {
List<String> keys = new ArrayList<>();
array.traverse((ArrayTraverser) (__, key) -> keys.add(key.asString()));
return keys;
}
private List<Deployment> deploymentsFromSlime(Inspector array) {
List<Deployment> deployments = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> deployments.add(deploymentFromSlime(item)));
return deployments;
}
private Deployment deploymentFromSlime(Inspector deploymentObject) {
return new Deployment(zoneIdFromSlime(deploymentObject.field(zoneField)),
applicationVersionFromSlime(deploymentObject.field(applicationPackageRevisionField)),
Version.fromString(deploymentObject.field(versionField).asString()),
Instant.ofEpochMilli(deploymentObject.field(deployTimeField).asLong()),
clusterUtilsMapFromSlime(deploymentObject.field(clusterUtilsField)),
clusterInfoMapFromSlime(deploymentObject.field(clusterInfoField)),
deploymentMetricsFromSlime(deploymentObject.field(deploymentMetricsField)),
DeploymentActivity.create(Serializers.optionalInstant(deploymentObject.field(lastQueriedField)),
Serializers.optionalInstant(deploymentObject.field(lastWrittenField)),
Serializers.optionalDouble(deploymentObject.field(lastQueriesPerSecondField)),
Serializers.optionalDouble(deploymentObject.field(lastWritesPerSecondField))));
}
private DeploymentMetrics deploymentMetricsFromSlime(Inspector object) {
Optional<Instant> instant = object.field(deploymentMetricsUpdateTime).valid() ?
Optional.of(Instant.ofEpochMilli(object.field(deploymentMetricsUpdateTime).asLong())) :
Optional.empty();
return new DeploymentMetrics(object.field(deploymentMetricsQPSField).asDouble(),
object.field(deploymentMetricsWPSField).asDouble(),
object.field(deploymentMetricsDocsField).asDouble(),
object.field(deploymentMetricsQueryLatencyField).asDouble(),
object.field(deploymentMetricsWriteLatencyField).asDouble(),
instant,
deploymentWarningsFrom(object.field(deploymentMetricsWarningsField)));
}
private Map<DeploymentMetrics.Warning, Integer> deploymentWarningsFrom(Inspector object) {
Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>();
object.traverse((ObjectTraverser) (name, value) -> warnings.put(DeploymentMetrics.Warning.valueOf(name),
(int) value.asLong()));
return Collections.unmodifiableMap(warnings);
}
private RotationStatus rotationStatusFromSlime(Inspector parentObject) {
var object = parentObject.field(rotationStatusField);
var statusMap = new LinkedHashMap<RotationId, Map<ZoneId, RotationState>>();
object.traverse((ArrayTraverser) (idx, statusObject) -> statusMap.put(new RotationId(statusObject.field(rotationIdField).asString()),
singleRotationStatusFromSlime(statusObject.field(statusField))));
return RotationStatus.from(statusMap);
}
private Map<ZoneId, RotationState> singleRotationStatusFromSlime(Inspector object) {
if (!object.valid()) {
return Collections.emptyMap();
}
Map<ZoneId, RotationState> rotationStatus = new LinkedHashMap<>();
object.traverse((ArrayTraverser) (idx, statusObject) -> {
var zone = zoneIdFromSlime(statusObject);
var status = RotationState.valueOf(statusObject.field(rotationStateField).asString());
rotationStatus.put(zone, status);
});
return Collections.unmodifiableMap(rotationStatus);
}
private Map<ClusterSpec.Id, ClusterInfo> clusterInfoMapFromSlime (Inspector object) {
Map<ClusterSpec.Id, ClusterInfo> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterInfoFromSlime(value)));
return map;
}
private Map<ClusterSpec.Id, ClusterUtilization> clusterUtilsMapFromSlime(Inspector object) {
Map<ClusterSpec.Id, ClusterUtilization> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterUtililzationFromSlime(value)));
return map;
}
private ClusterUtilization clusterUtililzationFromSlime(Inspector object) {
double cpu = object.field(clusterUtilsCpuField).asDouble();
double mem = object.field(clusterUtilsMemField).asDouble();
double disk = object.field(clusterUtilsDiskField).asDouble();
double diskBusy = object.field(clusterUtilsDiskBusyField).asDouble();
return new ClusterUtilization(mem, cpu, disk, diskBusy);
}
private ClusterInfo clusterInfoFromSlime(Inspector inspector) {
String flavor = inspector.field(clusterInfoFlavorField).asString();
int cost = (int)inspector.field(clusterInfoCostField).asLong();
String type = inspector.field(clusterInfoTypeField).asString();
double flavorCpu = inspector.field(clusterInfoCpuField).asDouble();
double flavorMem = inspector.field(clusterInfoMemField).asDouble();
double flavorDisk = inspector.field(clusterInfoDiskField).asDouble();
List<String> hostnames = new ArrayList<>();
inspector.field(clusterInfoHostnamesField).traverse((ArrayTraverser)(int index, Inspector value) -> hostnames.add(value.asString()));
return new ClusterInfo(flavor, cost, flavorCpu, flavorMem, flavorDisk, ClusterSpec.Type.from(type), hostnames);
}
private ZoneId zoneIdFromSlime(Inspector object) {
return ZoneId.from(object.field(environmentField).asString(), object.field(regionField).asString());
}
private ApplicationVersion applicationVersionFromSlime(Inspector object) {
if ( ! object.valid()) return ApplicationVersion.unknown;
OptionalLong applicationBuildNumber = Serializers.optionalLong(object.field(applicationBuildNumberField));
Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField));
if (sourceRevision.isEmpty() || applicationBuildNumber.isEmpty()) {
return ApplicationVersion.unknown;
}
Optional<String> authorEmail = Serializers.optionalString(object.field(authorEmailField));
Optional<Version> compileVersion = Serializers.optionalString(object.field(compileVersionField)).map(Version::fromString);
Optional<Instant> buildTime = Serializers.optionalInstant(object.field(buildTimeField));
if (authorEmail.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong());
if (compileVersion.isEmpty() || buildTime.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get());
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get(),
compileVersion.get(), buildTime.get());
}
private Optional<SourceRevision> sourceRevisionFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new SourceRevision(object.field(repositoryField).asString(),
object.field(branchField).asString(),
object.field(commitField).asString()));
}
private DeploymentJobs deploymentJobsFromSlime(Inspector object) {
List<JobStatus> jobStatusList = jobStatusListFromSlime(object.field(jobStatusField));
return new DeploymentJobs(jobStatusList);
}
private Change changeFromSlime(Inspector object) {
if ( ! object.valid()) return Change.empty();
Inspector versionFieldValue = object.field(versionField);
Change change = Change.empty();
if (versionFieldValue.valid())
change = Change.of(Version.fromString(versionFieldValue.asString()));
if (object.field(applicationBuildNumberField).valid())
change = change.with(applicationVersionFromSlime(object));
if (object.field(pinnedField).asBool())
change = change.withPin();
return change;
}
private List<JobStatus> jobStatusListFromSlime(Inspector array) {
List<JobStatus> jobStatusList = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> jobStatusFromSlime(item).ifPresent(jobStatusList::add));
return jobStatusList;
}
private Optional<JobStatus> jobStatusFromSlime(Inspector object) {
Optional<JobType> jobType =
JobType.fromOptionalJobName(object.field(jobTypeField).asString());
if (jobType.isEmpty()) return Optional.empty();
Optional<JobError> jobError = Optional.empty();
if (object.field(errorField).valid())
jobError = Optional.of(JobError.valueOf(object.field(errorField).asString()));
return Optional.of(new JobStatus(jobType.get(),
jobError,
jobRunFromSlime(object.field(lastTriggeredField)),
jobRunFromSlime(object.field(lastCompletedField)),
jobRunFromSlime(object.field(firstFailingField)),
jobRunFromSlime(object.field(lastSuccessField)),
Serializers.optionalLong(object.field(pausedUntilField))));
}
private Optional<JobStatus.JobRun> jobRunFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new JobStatus.JobRun(object.field(jobRunIdField).asLong(),
new Version(object.field(versionField).asString()),
applicationVersionFromSlime(object.field(revisionField)),
Serializers.optionalString(object.field(sourceVersionField)).map(Version::fromString),
Optional.of(object.field(sourceApplicationField)).filter(Inspector::valid).map(this::applicationVersionFromSlime),
object.field(reasonField).asString(),
Instant.ofEpochMilli(object.field(atField).asLong())));
}
private List<AssignedRotation> assignedRotationsFromSlime(DeploymentSpec deploymentSpec, Inspector root) {
var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>();
root.field(assignedRotationsField).traverse((ArrayTraverser) (idx, inspector) -> {
var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString());
var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString());
var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString());
var regions = deploymentSpec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
} | class ApplicationSerializer {
private static final String idField = "id";
private static final String createdAtField = "createdAt";
private static final String deploymentSpecField = "deploymentSpecField";
private static final String validationOverridesField = "validationOverrides";
private static final String instancesField = "instances";
private static final String deployingField = "deployingField";
private static final String projectIdField = "projectId";
private static final String builtInternallyField = "builtInternally";
private static final String pinnedField = "pinned";
private static final String outstandingChangeField = "outstandingChangeField";
private static final String deploymentIssueField = "deploymentIssueId";
private static final String ownershipIssueIdField = "ownershipIssueId";
private static final String ownerField = "confirmedOwner";
private static final String majorVersionField = "majorVersion";
private static final String writeQualityField = "writeQuality";
private static final String queryQualityField = "queryQuality";
private static final String pemDeployKeysField = "pemDeployKeys";
private static final String assignedRotationClusterField = "clusterId";
private static final String assignedRotationRotationField = "rotationId";
private static final String applicationCertificateField = "applicationCertificate";
private static final String instanceNameField = "instanceName";
private static final String deploymentsField = "deployments";
private static final String deploymentJobsField = "deploymentJobs";
private static final String assignedRotationsField = "assignedRotations";
private static final String assignedRotationEndpointField = "endpointId";
private static final String zoneField = "zone";
private static final String environmentField = "environment";
private static final String regionField = "region";
private static final String deployTimeField = "deployTime";
private static final String applicationBuildNumberField = "applicationBuildNumber";
private static final String applicationPackageRevisionField = "applicationPackageRevision";
private static final String sourceRevisionField = "sourceRevision";
private static final String repositoryField = "repositoryField";
private static final String branchField = "branchField";
private static final String commitField = "commitField";
private static final String authorEmailField = "authorEmailField";
private static final String compileVersionField = "compileVersion";
private static final String buildTimeField = "buildTime";
private static final String lastQueriedField = "lastQueried";
private static final String lastWrittenField = "lastWritten";
private static final String lastQueriesPerSecondField = "lastQueriesPerSecond";
private static final String lastWritesPerSecondField = "lastWritesPerSecond";
private static final String jobStatusField = "jobStatus";
private static final String jobTypeField = "jobType";
private static final String errorField = "jobError";
private static final String lastTriggeredField = "lastTriggered";
private static final String lastCompletedField = "lastCompleted";
private static final String firstFailingField = "firstFailing";
private static final String lastSuccessField = "lastSuccess";
private static final String pausedUntilField = "pausedUntil";
private static final String jobRunIdField = "id";
private static final String versionField = "version";
private static final String revisionField = "revision";
private static final String sourceVersionField = "sourceVersion";
private static final String sourceApplicationField = "sourceRevision";
private static final String reasonField = "reason";
private static final String atField = "at";
private static final String clusterInfoField = "clusterInfo";
private static final String clusterInfoFlavorField = "flavor";
private static final String clusterInfoCostField = "cost";
private static final String clusterInfoCpuField = "flavorCpu";
private static final String clusterInfoMemField = "flavorMem";
private static final String clusterInfoDiskField = "flavorDisk";
private static final String clusterInfoTypeField = "clusterType";
private static final String clusterInfoHostnamesField = "hostnames";
private static final String clusterUtilsField = "clusterUtils";
private static final String clusterUtilsCpuField = "cpu";
private static final String clusterUtilsMemField = "mem";
private static final String clusterUtilsDiskField = "disk";
private static final String clusterUtilsDiskBusyField = "diskbusy";
private static final String deploymentMetricsField = "metrics";
private static final String deploymentMetricsQPSField = "queriesPerSecond";
private static final String deploymentMetricsWPSField = "writesPerSecond";
private static final String deploymentMetricsDocsField = "documentCount";
private static final String deploymentMetricsQueryLatencyField = "queryLatencyMillis";
private static final String deploymentMetricsWriteLatencyField = "writeLatencyMillis";
private static final String deploymentMetricsUpdateTime = "lastUpdated";
private static final String deploymentMetricsWarningsField = "warnings";
private static final String rotationStatusField = "rotationStatus2";
private static final String rotationIdField = "rotationId";
private static final String rotationStateField = "state";
private static final String statusField = "status";
public Slime toSlime(Application application) {
Slime slime = new Slime();
Cursor root = slime.setObject();
root.setString(idField, application.id().serialized());
root.setLong(createdAtField, application.createdAt().toEpochMilli());
root.setString(deploymentSpecField, application.deploymentSpec().xmlForm());
root.setString(validationOverridesField, application.validationOverrides().xmlForm());
application.projectId().ifPresent(projectId -> root.setLong(projectIdField, projectId));
application.deploymentIssueId().ifPresent(jiraIssueId -> root.setString(deploymentIssueField, jiraIssueId.value()));
application.ownershipIssueId().ifPresent(issueId -> root.setString(ownershipIssueIdField, issueId.value()));
root.setBool(builtInternallyField, application.internal());
toSlime(application.change(), root, deployingField);
toSlime(application.outstandingChange(), root, outstandingChangeField);
application.owner().ifPresent(owner -> root.setString(ownerField, owner.username()));
application.majorVersion().ifPresent(majorVersion -> root.setLong(majorVersionField, majorVersion));
root.setDouble(queryQualityField, application.metrics().queryServiceQuality());
root.setDouble(writeQualityField, application.metrics().writeServiceQuality());
deployKeysToSlime(application.pemDeployKeys().stream(), root.setArray(pemDeployKeysField));
instancesToSlime(application, root.setArray(instancesField));
return slime;
}
private void instancesToSlime(Application application, Cursor array) {
for (Instance instance : application.instances().values()) {
Cursor instanceObject = array.addObject();
instanceObject.setString(instanceNameField, instance.name().value());
deploymentsToSlime(instance.deployments().values(), instanceObject.setArray(deploymentsField));
toSlime(instance.deploymentJobs(), instanceObject.setObject(deploymentJobsField));
assignedRotationsToSlime(instance.rotations(), instanceObject, assignedRotationsField);
toSlime(instance.rotationStatus(), instanceObject.setArray(rotationStatusField));
}
}
private void deployKeysToSlime(Stream<String> pemDeployKeys, Cursor array) {
pemDeployKeys.forEach(array::addString);
}
private void deploymentsToSlime(Collection<Deployment> deployments, Cursor array) {
for (Deployment deployment : deployments)
deploymentToSlime(deployment, array.addObject());
}
private void deploymentToSlime(Deployment deployment, Cursor object) {
zoneIdToSlime(deployment.zone(), object.setObject(zoneField));
object.setString(versionField, deployment.version().toString());
object.setLong(deployTimeField, deployment.at().toEpochMilli());
toSlime(deployment.applicationVersion(), object.setObject(applicationPackageRevisionField));
clusterInfoToSlime(deployment.clusterInfo(), object);
clusterUtilsToSlime(deployment.clusterUtils(), object);
deploymentMetricsToSlime(deployment.metrics(), object);
deployment.activity().lastQueried().ifPresent(instant -> object.setLong(lastQueriedField, instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> object.setLong(lastWrittenField, instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> object.setDouble(lastQueriesPerSecondField, value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> object.setDouble(lastWritesPerSecondField, value));
}
private void deploymentMetricsToSlime(DeploymentMetrics metrics, Cursor object) {
Cursor root = object.setObject(deploymentMetricsField);
root.setDouble(deploymentMetricsQPSField, metrics.queriesPerSecond());
root.setDouble(deploymentMetricsWPSField, metrics.writesPerSecond());
root.setDouble(deploymentMetricsDocsField, metrics.documentCount());
root.setDouble(deploymentMetricsQueryLatencyField, metrics.queryLatencyMillis());
root.setDouble(deploymentMetricsWriteLatencyField, metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> root.setLong(deploymentMetricsUpdateTime, instant.toEpochMilli()));
if (!metrics.warnings().isEmpty()) {
Cursor warningsObject = root.setObject(deploymentMetricsWarningsField);
metrics.warnings().forEach((warning, count) -> warningsObject.setLong(warning.name(), count));
}
}
private void clusterInfoToSlime(Map<ClusterSpec.Id, ClusterInfo> clusters, Cursor object) {
Cursor root = object.setObject(clusterInfoField);
for (Map.Entry<ClusterSpec.Id, ClusterInfo> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterInfo info, Cursor object) {
object.setString(clusterInfoFlavorField, info.getFlavor());
object.setLong(clusterInfoCostField, info.getFlavorCost());
object.setDouble(clusterInfoCpuField, info.getFlavorCPU());
object.setDouble(clusterInfoMemField, info.getFlavorMem());
object.setDouble(clusterInfoDiskField, info.getFlavorDisk());
object.setString(clusterInfoTypeField, info.getClusterType().name());
Cursor array = object.setArray(clusterInfoHostnamesField);
for (String host : info.getHostnames()) {
array.addString(host);
}
}
private void clusterUtilsToSlime(Map<ClusterSpec.Id, ClusterUtilization> clusters, Cursor object) {
Cursor root = object.setObject(clusterUtilsField);
for (Map.Entry<ClusterSpec.Id, ClusterUtilization> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterUtilization utils, Cursor object) {
object.setDouble(clusterUtilsCpuField, utils.getCpu());
object.setDouble(clusterUtilsMemField, utils.getMemory());
object.setDouble(clusterUtilsDiskField, utils.getDisk());
object.setDouble(clusterUtilsDiskBusyField, utils.getDiskBusy());
}
private void zoneIdToSlime(ZoneId zone, Cursor object) {
object.setString(environmentField, zone.environment().value());
object.setString(regionField, zone.region().value());
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if (applicationVersion.buildNumber().isPresent() && applicationVersion.source().isPresent()) {
object.setLong(applicationBuildNumberField, applicationVersion.buildNumber().getAsLong());
toSlime(applicationVersion.source().get(), object.setObject(sourceRevisionField));
applicationVersion.authorEmail().ifPresent(email -> object.setString(authorEmailField, email));
applicationVersion.compileVersion().ifPresent(version -> object.setString(compileVersionField, version.toString()));
applicationVersion.buildTime().ifPresent(time -> object.setLong(buildTimeField, time.toEpochMilli()));
}
}
private void toSlime(SourceRevision sourceRevision, Cursor object) {
object.setString(repositoryField, sourceRevision.repository());
object.setString(branchField, sourceRevision.branch());
object.setString(commitField, sourceRevision.commit());
}
private void toSlime(DeploymentJobs deploymentJobs, Cursor cursor) {
jobStatusToSlime(deploymentJobs.jobStatus().values(), cursor.setArray(jobStatusField));
}
private void jobStatusToSlime(Collection<JobStatus> jobStatuses, Cursor jobStatusArray) {
for (JobStatus jobStatus : jobStatuses)
toSlime(jobStatus, jobStatusArray.addObject());
}
private void toSlime(JobStatus jobStatus, Cursor object) {
object.setString(jobTypeField, jobStatus.type().jobName());
if (jobStatus.jobError().isPresent())
object.setString(errorField, jobStatus.jobError().get().name());
jobStatus.lastTriggered().ifPresent(run -> jobRunToSlime(run, object, lastTriggeredField));
jobStatus.lastCompleted().ifPresent(run -> jobRunToSlime(run, object, lastCompletedField));
jobStatus.lastSuccess().ifPresent(run -> jobRunToSlime(run, object, lastSuccessField));
jobStatus.firstFailing().ifPresent(run -> jobRunToSlime(run, object, firstFailingField));
jobStatus.pausedUntil().ifPresent(until -> object.setLong(pausedUntilField, until));
}
private void jobRunToSlime(JobStatus.JobRun jobRun, Cursor parent, String jobRunObjectName) {
Cursor object = parent.setObject(jobRunObjectName);
object.setLong(jobRunIdField, jobRun.id());
object.setString(versionField, jobRun.platform().toString());
toSlime(jobRun.application(), object.setObject(revisionField));
jobRun.sourcePlatform().ifPresent(version -> object.setString(sourceVersionField, version.toString()));
jobRun.sourceApplication().ifPresent(version -> toSlime(version, object.setObject(sourceApplicationField)));
object.setString(reasonField, jobRun.reason());
object.setLong(atField, jobRun.at().toEpochMilli());
}
private void toSlime(Change deploying, Cursor parentObject, String fieldName) {
if (deploying.isEmpty()) return;
Cursor object = parentObject.setObject(fieldName);
if (deploying.platform().isPresent())
object.setString(versionField, deploying.platform().get().toString());
if (deploying.application().isPresent())
toSlime(deploying.application().get(), object);
if (deploying.isPinned())
object.setBool(pinnedField, true);
}
private void toSlime(RotationStatus status, Cursor array) {
status.asMap().forEach((rotationId, zoneStatus) -> {
Cursor rotationObject = array.addObject();
rotationObject.setString(rotationIdField, rotationId.asString());
Cursor statusArray = rotationObject.setArray(statusField);
zoneStatus.forEach((zone, state) -> {
Cursor statusObject = statusArray.addObject();
zoneIdToSlime(zone, statusObject);
statusObject.setString(rotationStateField, state.name());
});
});
}
private void assignedRotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) {
var rotationsArray = parent.setArray(fieldName);
for (var rotation : rotations) {
var object = rotationsArray.addObject();
object.setString(assignedRotationEndpointField, rotation.endpointId().id());
object.setString(assignedRotationRotationField, rotation.rotationId().asString());
object.setString(assignedRotationClusterField, rotation.clusterId().value());
}
}
private List<Instance> instancesFromSlime(TenantAndApplicationId id, DeploymentSpec deploymentSpec, Inspector field) {
List<Instance> instances = new ArrayList<>();
field.traverse((ArrayTraverser) (name, object) -> {
InstanceName instanceName = InstanceName.from(object.field(instanceNameField).asString());
List<Deployment> deployments = deploymentsFromSlime(object.field(deploymentsField));
DeploymentJobs deploymentJobs = deploymentJobsFromSlime(object.field(deploymentJobsField));
List<AssignedRotation> assignedRotations = assignedRotationsFromSlime(deploymentSpec, object);
RotationStatus rotationStatus = rotationStatusFromSlime(object);
instances.add(new Instance(id.instance(instanceName),
deployments,
deploymentJobs,
assignedRotations,
rotationStatus));
});
return instances;
}
private Set<String> pemDeployKeysFromSlime(Inspector array) {
Set<String> keys = new LinkedHashSet<>();
array.traverse((ArrayTraverser) (__, key) -> keys.add(key.asString()));
return keys;
}
private List<Deployment> deploymentsFromSlime(Inspector array) {
List<Deployment> deployments = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> deployments.add(deploymentFromSlime(item)));
return deployments;
}
private Deployment deploymentFromSlime(Inspector deploymentObject) {
return new Deployment(zoneIdFromSlime(deploymentObject.field(zoneField)),
applicationVersionFromSlime(deploymentObject.field(applicationPackageRevisionField)),
Version.fromString(deploymentObject.field(versionField).asString()),
Instant.ofEpochMilli(deploymentObject.field(deployTimeField).asLong()),
clusterUtilsMapFromSlime(deploymentObject.field(clusterUtilsField)),
clusterInfoMapFromSlime(deploymentObject.field(clusterInfoField)),
deploymentMetricsFromSlime(deploymentObject.field(deploymentMetricsField)),
DeploymentActivity.create(Serializers.optionalInstant(deploymentObject.field(lastQueriedField)),
Serializers.optionalInstant(deploymentObject.field(lastWrittenField)),
Serializers.optionalDouble(deploymentObject.field(lastQueriesPerSecondField)),
Serializers.optionalDouble(deploymentObject.field(lastWritesPerSecondField))));
}
private DeploymentMetrics deploymentMetricsFromSlime(Inspector object) {
Optional<Instant> instant = object.field(deploymentMetricsUpdateTime).valid() ?
Optional.of(Instant.ofEpochMilli(object.field(deploymentMetricsUpdateTime).asLong())) :
Optional.empty();
return new DeploymentMetrics(object.field(deploymentMetricsQPSField).asDouble(),
object.field(deploymentMetricsWPSField).asDouble(),
object.field(deploymentMetricsDocsField).asDouble(),
object.field(deploymentMetricsQueryLatencyField).asDouble(),
object.field(deploymentMetricsWriteLatencyField).asDouble(),
instant,
deploymentWarningsFrom(object.field(deploymentMetricsWarningsField)));
}
private Map<DeploymentMetrics.Warning, Integer> deploymentWarningsFrom(Inspector object) {
Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>();
object.traverse((ObjectTraverser) (name, value) -> warnings.put(DeploymentMetrics.Warning.valueOf(name),
(int) value.asLong()));
return Collections.unmodifiableMap(warnings);
}
private RotationStatus rotationStatusFromSlime(Inspector parentObject) {
var object = parentObject.field(rotationStatusField);
var statusMap = new LinkedHashMap<RotationId, Map<ZoneId, RotationState>>();
object.traverse((ArrayTraverser) (idx, statusObject) -> statusMap.put(new RotationId(statusObject.field(rotationIdField).asString()),
singleRotationStatusFromSlime(statusObject.field(statusField))));
return RotationStatus.from(statusMap);
}
private Map<ZoneId, RotationState> singleRotationStatusFromSlime(Inspector object) {
if (!object.valid()) {
return Collections.emptyMap();
}
Map<ZoneId, RotationState> rotationStatus = new LinkedHashMap<>();
object.traverse((ArrayTraverser) (idx, statusObject) -> {
var zone = zoneIdFromSlime(statusObject);
var status = RotationState.valueOf(statusObject.field(rotationStateField).asString());
rotationStatus.put(zone, status);
});
return Collections.unmodifiableMap(rotationStatus);
}
private Map<ClusterSpec.Id, ClusterInfo> clusterInfoMapFromSlime (Inspector object) {
Map<ClusterSpec.Id, ClusterInfo> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterInfoFromSlime(value)));
return map;
}
private Map<ClusterSpec.Id, ClusterUtilization> clusterUtilsMapFromSlime(Inspector object) {
Map<ClusterSpec.Id, ClusterUtilization> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterUtililzationFromSlime(value)));
return map;
}
private ClusterUtilization clusterUtililzationFromSlime(Inspector object) {
double cpu = object.field(clusterUtilsCpuField).asDouble();
double mem = object.field(clusterUtilsMemField).asDouble();
double disk = object.field(clusterUtilsDiskField).asDouble();
double diskBusy = object.field(clusterUtilsDiskBusyField).asDouble();
return new ClusterUtilization(mem, cpu, disk, diskBusy);
}
private ClusterInfo clusterInfoFromSlime(Inspector inspector) {
String flavor = inspector.field(clusterInfoFlavorField).asString();
int cost = (int)inspector.field(clusterInfoCostField).asLong();
String type = inspector.field(clusterInfoTypeField).asString();
double flavorCpu = inspector.field(clusterInfoCpuField).asDouble();
double flavorMem = inspector.field(clusterInfoMemField).asDouble();
double flavorDisk = inspector.field(clusterInfoDiskField).asDouble();
List<String> hostnames = new ArrayList<>();
inspector.field(clusterInfoHostnamesField).traverse((ArrayTraverser)(int index, Inspector value) -> hostnames.add(value.asString()));
return new ClusterInfo(flavor, cost, flavorCpu, flavorMem, flavorDisk, ClusterSpec.Type.from(type), hostnames);
}
private ZoneId zoneIdFromSlime(Inspector object) {
return ZoneId.from(object.field(environmentField).asString(), object.field(regionField).asString());
}
private ApplicationVersion applicationVersionFromSlime(Inspector object) {
if ( ! object.valid()) return ApplicationVersion.unknown;
OptionalLong applicationBuildNumber = Serializers.optionalLong(object.field(applicationBuildNumberField));
Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField));
if (sourceRevision.isEmpty() || applicationBuildNumber.isEmpty()) {
return ApplicationVersion.unknown;
}
Optional<String> authorEmail = Serializers.optionalString(object.field(authorEmailField));
Optional<Version> compileVersion = Serializers.optionalString(object.field(compileVersionField)).map(Version::fromString);
Optional<Instant> buildTime = Serializers.optionalInstant(object.field(buildTimeField));
if (authorEmail.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong());
if (compileVersion.isEmpty() || buildTime.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get());
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get(),
compileVersion.get(), buildTime.get());
}
private Optional<SourceRevision> sourceRevisionFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new SourceRevision(object.field(repositoryField).asString(),
object.field(branchField).asString(),
object.field(commitField).asString()));
}
private DeploymentJobs deploymentJobsFromSlime(Inspector object) {
List<JobStatus> jobStatusList = jobStatusListFromSlime(object.field(jobStatusField));
return new DeploymentJobs(jobStatusList);
}
private Change changeFromSlime(Inspector object) {
if ( ! object.valid()) return Change.empty();
Inspector versionFieldValue = object.field(versionField);
Change change = Change.empty();
if (versionFieldValue.valid())
change = Change.of(Version.fromString(versionFieldValue.asString()));
if (object.field(applicationBuildNumberField).valid())
change = change.with(applicationVersionFromSlime(object));
if (object.field(pinnedField).asBool())
change = change.withPin();
return change;
}
private List<JobStatus> jobStatusListFromSlime(Inspector array) {
List<JobStatus> jobStatusList = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> jobStatusFromSlime(item).ifPresent(jobStatusList::add));
return jobStatusList;
}
private Optional<JobStatus> jobStatusFromSlime(Inspector object) {
Optional<JobType> jobType =
JobType.fromOptionalJobName(object.field(jobTypeField).asString());
if (jobType.isEmpty()) return Optional.empty();
Optional<JobError> jobError = Optional.empty();
if (object.field(errorField).valid())
jobError = Optional.of(JobError.valueOf(object.field(errorField).asString()));
return Optional.of(new JobStatus(jobType.get(),
jobError,
jobRunFromSlime(object.field(lastTriggeredField)),
jobRunFromSlime(object.field(lastCompletedField)),
jobRunFromSlime(object.field(firstFailingField)),
jobRunFromSlime(object.field(lastSuccessField)),
Serializers.optionalLong(object.field(pausedUntilField))));
}
private Optional<JobStatus.JobRun> jobRunFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new JobStatus.JobRun(object.field(jobRunIdField).asLong(),
new Version(object.field(versionField).asString()),
applicationVersionFromSlime(object.field(revisionField)),
Serializers.optionalString(object.field(sourceVersionField)).map(Version::fromString),
Optional.of(object.field(sourceApplicationField)).filter(Inspector::valid).map(this::applicationVersionFromSlime),
object.field(reasonField).asString(),
Instant.ofEpochMilli(object.field(atField).asLong())));
}
private List<AssignedRotation> assignedRotationsFromSlime(DeploymentSpec deploymentSpec, Inspector root) {
var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>();
root.field(assignedRotationsField).traverse((ArrayTraverser) (idx, inspector) -> {
var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString());
var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString());
var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString());
var regions = deploymentSpec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
} |
If only the standard library exposed their throwingMerger >_< | public DeploymentJobs(Collection<JobStatus> jobStatusEntries) {
this.status = ImmutableMap.copyOf((Iterable<Map.Entry<JobType, JobStatus>>)
jobStatusEntries.stream()
.map(job -> Map.entry(job.type(), job))::iterator);
} | .map(job -> Map.entry(job.type(), job))::iterator); | public DeploymentJobs(Collection<JobStatus> jobStatusEntries) {
this.status = ImmutableMap.copyOf((Iterable<Map.Entry<JobType, JobStatus>>)
jobStatusEntries.stream()
.map(job -> Map.entry(job.type(), job))::iterator);
} | class DeploymentJobs {
private final ImmutableMap<JobType, JobStatus> status;
/** Return a new instance with the given job update applied. */
public DeploymentJobs withUpdate(JobType jobType, UnaryOperator<JobStatus> update) {
Map<JobType, JobStatus> status = new LinkedHashMap<>(this.status);
status.compute(jobType, (type, job) -> {
if (job == null) job = JobStatus.initial(jobType);
return update.apply(job);
});
return new DeploymentJobs(status.values());
}
/** Return a new instance with the given completion */
public DeploymentJobs withCompletion(JobType jobType, JobStatus.JobRun completion, Optional<JobError> jobError) {
return withUpdate(jobType, job -> job.withCompletion(completion, jobError));
}
public DeploymentJobs withTriggering(JobType jobType, JobStatus.JobRun jobRun) {
return withUpdate(jobType, job -> job.withTriggering(jobRun));
}
public DeploymentJobs withPause(JobType jobType, OptionalLong pausedUntil) {
return withUpdate(jobType, job -> job.withPause(pausedUntil));
}
public DeploymentJobs without(JobType job) {
Map<JobType, JobStatus> status = new LinkedHashMap<>(this.status);
status.remove(job);
return new DeploymentJobs(status.values());
}
/** Returns an immutable map of the status entries in this */
public Map<JobType, JobStatus> jobStatus() { return status; }
/** Returns whether this has some job status which is not a success */
public boolean hasFailures() {
return ! JobList.from(status.values())
.failing()
.not().failingBecause(JobError.outOfCapacity)
.isEmpty();
}
/** Returns the JobStatus of the given JobType, or empty. */
public Optional<JobStatus> statusOf(JobType jobType) {
return Optional.ofNullable(jobStatus().get(jobType));
}
/** A job report. This class is immutable. */
public static class JobReport {
private final ApplicationId applicationId;
private final JobType jobType;
private final long projectId;
private final long buildNumber;
private final Optional<ApplicationVersion> version;
private final Optional<JobError> jobError;
private JobReport(ApplicationId applicationId, JobType jobType, long projectId, long buildNumber,
Optional<JobError> jobError, Optional<ApplicationVersion> version) {
Objects.requireNonNull(applicationId, "applicationId cannot be null");
Objects.requireNonNull(jobType, "jobType cannot be null");
Objects.requireNonNull(jobError, "jobError cannot be null");
Objects.requireNonNull(version, "version cannot be null");
if (version.isPresent() && version.get().buildNumber().isPresent() && version.get().buildNumber().getAsLong() != buildNumber)
throw new IllegalArgumentException("Build number in application version must match the one given here.");
this.applicationId = applicationId;
this.projectId = projectId;
this.buildNumber = buildNumber;
this.jobType = jobType;
this.jobError = jobError;
this.version = version;
}
public static JobReport ofComponent(ApplicationId applicationId, long projectId, long buildNumber,
Optional<JobError> jobError, SourceRevision sourceRevision) {
return new JobReport(applicationId, JobType.component, projectId, buildNumber,
jobError, Optional.of(ApplicationVersion.from(sourceRevision, buildNumber)));
}
public static JobReport ofSubmission(ApplicationId applicationId, long projectId, ApplicationVersion version) {
return new JobReport(applicationId, JobType.component, projectId, version.buildNumber().getAsLong(),
Optional.empty(), Optional.of(version));
}
public static JobReport ofJob(ApplicationId applicationId, JobType jobType, long buildNumber, Optional<JobError> jobError) {
return new JobReport(applicationId, jobType, -1, buildNumber, jobError, Optional.empty());
}
public ApplicationId applicationId() { return applicationId; }
public JobType jobType() { return jobType; }
public long projectId() { return projectId; }
public long buildNumber() { return buildNumber; }
public boolean success() { return ! jobError.isPresent(); }
public Optional<ApplicationVersion> version() { return version; }
public Optional<JobError> jobError() { return jobError; }
public BuildService.BuildJob buildJob() { return BuildService.BuildJob.of(applicationId, projectId, jobType.jobName()); }
}
public enum JobError {
unknown,
outOfCapacity
}
} | class DeploymentJobs {
private final ImmutableMap<JobType, JobStatus> status;
/** Return a new instance with the given job update applied. */
public DeploymentJobs withUpdate(JobType jobType, UnaryOperator<JobStatus> update) {
Map<JobType, JobStatus> status = new LinkedHashMap<>(this.status);
status.compute(jobType, (type, job) -> {
if (job == null) job = JobStatus.initial(jobType);
return update.apply(job);
});
return new DeploymentJobs(status.values());
}
/** Return a new instance with the given completion */
public DeploymentJobs withCompletion(JobType jobType, JobStatus.JobRun completion, Optional<JobError> jobError) {
return withUpdate(jobType, job -> job.withCompletion(completion, jobError));
}
public DeploymentJobs withTriggering(JobType jobType, JobStatus.JobRun jobRun) {
return withUpdate(jobType, job -> job.withTriggering(jobRun));
}
public DeploymentJobs withPause(JobType jobType, OptionalLong pausedUntil) {
return withUpdate(jobType, job -> job.withPause(pausedUntil));
}
public DeploymentJobs without(JobType job) {
Map<JobType, JobStatus> status = new LinkedHashMap<>(this.status);
status.remove(job);
return new DeploymentJobs(status.values());
}
/** Returns an immutable map of the status entries in this */
public Map<JobType, JobStatus> jobStatus() { return status; }
/** Returns whether this has some job status which is not a success */
public boolean hasFailures() {
return ! JobList.from(status.values())
.failing()
.not().failingBecause(JobError.outOfCapacity)
.isEmpty();
}
/** Returns the JobStatus of the given JobType, or empty. */
public Optional<JobStatus> statusOf(JobType jobType) {
return Optional.ofNullable(jobStatus().get(jobType));
}
/** A job report. This class is immutable. */
public static class JobReport {
private final ApplicationId applicationId;
private final JobType jobType;
private final long projectId;
private final long buildNumber;
private final Optional<ApplicationVersion> version;
private final Optional<JobError> jobError;
private JobReport(ApplicationId applicationId, JobType jobType, long projectId, long buildNumber,
Optional<JobError> jobError, Optional<ApplicationVersion> version) {
Objects.requireNonNull(applicationId, "applicationId cannot be null");
Objects.requireNonNull(jobType, "jobType cannot be null");
Objects.requireNonNull(jobError, "jobError cannot be null");
Objects.requireNonNull(version, "version cannot be null");
if (version.isPresent() && version.get().buildNumber().isPresent() && version.get().buildNumber().getAsLong() != buildNumber)
throw new IllegalArgumentException("Build number in application version must match the one given here.");
this.applicationId = applicationId;
this.projectId = projectId;
this.buildNumber = buildNumber;
this.jobType = jobType;
this.jobError = jobError;
this.version = version;
}
public static JobReport ofComponent(ApplicationId applicationId, long projectId, long buildNumber,
Optional<JobError> jobError, SourceRevision sourceRevision) {
return new JobReport(applicationId, JobType.component, projectId, buildNumber,
jobError, Optional.of(ApplicationVersion.from(sourceRevision, buildNumber)));
}
public static JobReport ofSubmission(ApplicationId applicationId, long projectId, ApplicationVersion version) {
return new JobReport(applicationId, JobType.component, projectId, version.buildNumber().getAsLong(),
Optional.empty(), Optional.of(version));
}
public static JobReport ofJob(ApplicationId applicationId, JobType jobType, long buildNumber, Optional<JobError> jobError) {
return new JobReport(applicationId, jobType, -1, buildNumber, jobError, Optional.empty());
}
public ApplicationId applicationId() { return applicationId; }
public JobType jobType() { return jobType; }
public long projectId() { return projectId; }
public long buildNumber() { return buildNumber; }
public boolean success() { return ! jobError.isPresent(); }
public Optional<ApplicationVersion> version() { return version; }
public Optional<JobError> jobError() { return jobError; }
public BuildService.BuildJob buildJob() { return BuildService.BuildJob.of(applicationId, projectId, jobType.jobName()); }
}
public enum JobError {
unknown,
outOfCapacity
}
} |
Yes. | public LockedApplication withPemDeployKey(String pemDeployKey) {
List<String> keys = new ArrayList<>(pemDeployKeys);
keys.remove(pemDeployKey);
keys.add(pemDeployKey);
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, keys,
projectId, internal, instances);
} | keys.remove(pemDeployKey); | public LockedApplication withPemDeployKey(String pemDeployKey) {
Set<String> keys = new LinkedHashSet<>(pemDeployKeys);
keys.add(pemDeployKey);
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, keys,
projectId, internal, instances);
} | class LockedApplication {
private final Lock lock;
private final TenantAndApplicationId id;
private final Instant createdAt;
private final DeploymentSpec deploymentSpec;
private final ValidationOverrides validationOverrides;
private final Change change;
private final Change outstandingChange;
private final Optional<IssueId> deploymentIssueId;
private final Optional<IssueId> ownershipIssueId;
private final Optional<User> owner;
private final OptionalInt majorVersion;
private final ApplicationMetrics metrics;
private final List<String> pemDeployKeys;
private final OptionalLong projectId;
private final boolean internal;
private final Map<InstanceName, Instance> instances;
/**
* Used to create a locked application
*
* @param application The application to lock.
* @param lock The lock for the application.
*/
LockedApplication(Application application, Lock lock) {
this(Objects.requireNonNull(lock, "lock cannot be null"), application.id(), application.createdAt(),
application.deploymentSpec(), application.validationOverrides(), application.change(),
application.outstandingChange(), application.deploymentIssueId(), application.ownershipIssueId(),
application.owner(), application.majorVersion(), application.metrics(), application.pemDeployKeys(),
application.projectId(), application.internal(), application.instances());
}
private LockedApplication(Lock lock, TenantAndApplicationId id, Instant createdAt, DeploymentSpec deploymentSpec,
ValidationOverrides validationOverrides, Change change, Change outstandingChange,
Optional<IssueId> deploymentIssueId, Optional<IssueId> ownershipIssueId, Optional<User> owner,
OptionalInt majorVersion, ApplicationMetrics metrics, List<String> pemDeployKeys,
OptionalLong projectId, boolean internal, Map<InstanceName, Instance> instances) {
this.lock = lock;
this.id = id;
this.createdAt = createdAt;
this.deploymentSpec = deploymentSpec;
this.validationOverrides = validationOverrides;
this.change = change;
this.outstandingChange = outstandingChange;
this.deploymentIssueId = deploymentIssueId;
this.ownershipIssueId = ownershipIssueId;
this.owner = owner;
this.majorVersion = majorVersion;
this.metrics = metrics;
this.pemDeployKeys = pemDeployKeys;
this.projectId = projectId;
this.internal = internal;
this.instances = Map.copyOf(instances);
}
/** Returns a read-only copy of this */
public Application get() {
return new Application(id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances.values());
}
public LockedApplication withNewInstance(InstanceName instance) {
var instances = new HashMap<>(this.instances);
instances.put(instance, new Instance(id.instance(instance)));
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication with(InstanceName instance, UnaryOperator<Instance> modification) {
var instances = new HashMap<>(this.instances);
instances.put(instance, modification.apply(instances.get(instance)));
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication without(InstanceName instance) {
var instances = new HashMap<>(this.instances);
instances.remove(instance);
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withBuiltInternally(boolean builtInternally) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, builtInternally, instances);
}
public LockedApplication withProjectId(OptionalLong projectId) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withDeploymentIssueId(IssueId issueId) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
Optional.ofNullable(issueId), ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication with(DeploymentSpec deploymentSpec) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication with(ValidationOverrides validationOverrides) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withChange(Change change) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withOutstandingChange(Change outstandingChange) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withOwnershipIssueId(IssueId issueId) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, Optional.of(issueId), owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withOwner(User owner) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, Optional.of(owner), majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
/** Set a major version for this, or set to null to remove any major version override */
public LockedApplication withMajorVersion(Integer majorVersion) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner,
majorVersion == null ? OptionalInt.empty() : OptionalInt.of(majorVersion),
metrics, pemDeployKeys, projectId, internal, instances);
}
public LockedApplication with(ApplicationMetrics metrics) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withoutPemDeployKey(String pemDeployKey) {
List<String> keys = new ArrayList<>(pemDeployKeys);
keys.remove(pemDeployKey);
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, keys,
projectId, internal, instances);
}
@Override
public String toString() {
return "application '" + id + "'";
}
} | class LockedApplication {
private final Lock lock;
private final TenantAndApplicationId id;
private final Instant createdAt;
private final DeploymentSpec deploymentSpec;
private final ValidationOverrides validationOverrides;
private final Change change;
private final Change outstandingChange;
private final Optional<IssueId> deploymentIssueId;
private final Optional<IssueId> ownershipIssueId;
private final Optional<User> owner;
private final OptionalInt majorVersion;
private final ApplicationMetrics metrics;
private final Set<String> pemDeployKeys;
private final OptionalLong projectId;
private final boolean internal;
private final Map<InstanceName, Instance> instances;
/**
* Used to create a locked application
*
* @param application The application to lock.
* @param lock The lock for the application.
*/
LockedApplication(Application application, Lock lock) {
this(Objects.requireNonNull(lock, "lock cannot be null"), application.id(), application.createdAt(),
application.deploymentSpec(), application.validationOverrides(), application.change(),
application.outstandingChange(), application.deploymentIssueId(), application.ownershipIssueId(),
application.owner(), application.majorVersion(), application.metrics(), application.pemDeployKeys(),
application.projectId(), application.internal(), application.instances());
}
private LockedApplication(Lock lock, TenantAndApplicationId id, Instant createdAt, DeploymentSpec deploymentSpec,
ValidationOverrides validationOverrides, Change change, Change outstandingChange,
Optional<IssueId> deploymentIssueId, Optional<IssueId> ownershipIssueId, Optional<User> owner,
OptionalInt majorVersion, ApplicationMetrics metrics, Set<String> pemDeployKeys,
OptionalLong projectId, boolean internal,
Map<InstanceName, Instance> instances) {
this.lock = lock;
this.id = id;
this.createdAt = createdAt;
this.deploymentSpec = deploymentSpec;
this.validationOverrides = validationOverrides;
this.change = change;
this.outstandingChange = outstandingChange;
this.deploymentIssueId = deploymentIssueId;
this.ownershipIssueId = ownershipIssueId;
this.owner = owner;
this.majorVersion = majorVersion;
this.metrics = metrics;
this.pemDeployKeys = pemDeployKeys;
this.projectId = projectId;
this.internal = internal;
this.instances = Map.copyOf(instances);
}
/** Returns a read-only copy of this */
public Application get() {
return new Application(id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances.values());
}
public LockedApplication withNewInstance(InstanceName instance) {
var instances = new HashMap<>(this.instances);
instances.put(instance, new Instance(id.instance(instance)));
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication with(InstanceName instance, UnaryOperator<Instance> modification) {
var instances = new HashMap<>(this.instances);
instances.put(instance, modification.apply(instances.get(instance)));
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication without(InstanceName instance) {
var instances = new HashMap<>(this.instances);
instances.remove(instance);
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withBuiltInternally(boolean builtInternally) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, builtInternally, instances);
}
public LockedApplication withProjectId(OptionalLong projectId) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withDeploymentIssueId(IssueId issueId) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
Optional.ofNullable(issueId), ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication with(DeploymentSpec deploymentSpec) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication with(ValidationOverrides validationOverrides) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withChange(Change change) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withOutstandingChange(Change outstandingChange) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withOwnershipIssueId(IssueId issueId) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, Optional.of(issueId), owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withOwner(User owner) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, Optional.of(owner), majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
/** Set a major version for this, or set to null to remove any major version override */
public LockedApplication withMajorVersion(Integer majorVersion) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner,
majorVersion == null ? OptionalInt.empty() : OptionalInt.of(majorVersion),
metrics, pemDeployKeys, projectId, internal, instances);
}
public LockedApplication with(ApplicationMetrics metrics) {
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, pemDeployKeys,
projectId, internal, instances);
}
public LockedApplication withoutPemDeployKey(String pemDeployKey) {
Set<String> keys = new LinkedHashSet<>(pemDeployKeys);
keys.remove(pemDeployKey);
return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides, change, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics, keys,
projectId, internal, instances);
}
@Override
public String toString() {
return "application '" + id + "'";
}
} |
Just a name change of the variable, not the field :) | public Application fromSlime(Slime slime) {
Inspector root = slime.get();
TenantAndApplicationId id = TenantAndApplicationId.fromSerialized(root.field(idField).asString());
Instant createdAt = Instant.ofEpochMilli(root.field(createdAtField).asLong());
DeploymentSpec deploymentSpec = DeploymentSpec.fromXml(root.field(deploymentSpecField).asString(), false);
ValidationOverrides validationOverrides = ValidationOverrides.fromXml(root.field(validationOverridesField).asString());
Change deploying = changeFromSlime(root.field(deployingField));
Change outstandingChange = changeFromSlime(root.field(outstandingChangeField));
Optional<IssueId> deploymentIssueId = Serializers.optionalString(root.field(deploymentIssueField)).map(IssueId::from);
Optional<IssueId> ownershipIssueId = Serializers.optionalString(root.field(ownershipIssueIdField)).map(IssueId::from);
Optional<User> owner = Serializers.optionalString(root.field(ownerField)).map(User::from);
OptionalInt majorVersion = Serializers.optionalInteger(root.field(majorVersionField));
ApplicationMetrics metrics = new ApplicationMetrics(root.field(queryQualityField).asDouble(),
root.field(writeQualityField).asDouble());
List<String> pemDeployKeys = pemDeployKeysFromSlime(root.field(pemDeployKeysField));
List<Instance> instances = instancesFromSlime(id, deploymentSpec, root.field(instancesField));
OptionalLong projectId = Serializers.optionalLong(root.field(projectIdField));
boolean builtInternally = root.field(builtInternallyField).asBool();
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
pemDeployKeys, projectId, builtInternally, instances);
} | List<String> pemDeployKeys = pemDeployKeysFromSlime(root.field(pemDeployKeysField)); | public Application fromSlime(Slime slime) {
Inspector root = slime.get();
TenantAndApplicationId id = TenantAndApplicationId.fromSerialized(root.field(idField).asString());
Instant createdAt = Instant.ofEpochMilli(root.field(createdAtField).asLong());
DeploymentSpec deploymentSpec = DeploymentSpec.fromXml(root.field(deploymentSpecField).asString(), false);
ValidationOverrides validationOverrides = ValidationOverrides.fromXml(root.field(validationOverridesField).asString());
Change deploying = changeFromSlime(root.field(deployingField));
Change outstandingChange = changeFromSlime(root.field(outstandingChangeField));
Optional<IssueId> deploymentIssueId = Serializers.optionalString(root.field(deploymentIssueField)).map(IssueId::from);
Optional<IssueId> ownershipIssueId = Serializers.optionalString(root.field(ownershipIssueIdField)).map(IssueId::from);
Optional<User> owner = Serializers.optionalString(root.field(ownerField)).map(User::from);
OptionalInt majorVersion = Serializers.optionalInteger(root.field(majorVersionField));
ApplicationMetrics metrics = new ApplicationMetrics(root.field(queryQualityField).asDouble(),
root.field(writeQualityField).asDouble());
Set<String> pemDeployKeys = pemDeployKeysFromSlime(root.field(pemDeployKeysField));
List<Instance> instances = instancesFromSlime(id, deploymentSpec, root.field(instancesField));
OptionalLong projectId = Serializers.optionalLong(root.field(projectIdField));
boolean builtInternally = root.field(builtInternallyField).asBool();
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
pemDeployKeys, projectId, builtInternally, instances);
} | class ApplicationSerializer {
private static final String idField = "id";
private static final String createdAtField = "createdAt";
private static final String deploymentSpecField = "deploymentSpecField";
private static final String validationOverridesField = "validationOverrides";
private static final String instancesField = "instances";
private static final String deployingField = "deployingField";
private static final String projectIdField = "projectId";
private static final String builtInternallyField = "builtInternally";
private static final String pinnedField = "pinned";
private static final String outstandingChangeField = "outstandingChangeField";
private static final String deploymentIssueField = "deploymentIssueId";
private static final String ownershipIssueIdField = "ownershipIssueId";
private static final String ownerField = "confirmedOwner";
private static final String majorVersionField = "majorVersion";
private static final String writeQualityField = "writeQuality";
private static final String queryQualityField = "queryQuality";
private static final String pemDeployKeysField = "pemDeployKeys";
private static final String assignedRotationClusterField = "clusterId";
private static final String assignedRotationRotationField = "rotationId";
private static final String applicationCertificateField = "applicationCertificate";
private static final String instanceNameField = "instanceName";
private static final String deploymentsField = "deployments";
private static final String deploymentJobsField = "deploymentJobs";
private static final String assignedRotationsField = "assignedRotations";
private static final String assignedRotationEndpointField = "endpointId";
private static final String zoneField = "zone";
private static final String environmentField = "environment";
private static final String regionField = "region";
private static final String deployTimeField = "deployTime";
private static final String applicationBuildNumberField = "applicationBuildNumber";
private static final String applicationPackageRevisionField = "applicationPackageRevision";
private static final String sourceRevisionField = "sourceRevision";
private static final String repositoryField = "repositoryField";
private static final String branchField = "branchField";
private static final String commitField = "commitField";
private static final String authorEmailField = "authorEmailField";
private static final String compileVersionField = "compileVersion";
private static final String buildTimeField = "buildTime";
private static final String lastQueriedField = "lastQueried";
private static final String lastWrittenField = "lastWritten";
private static final String lastQueriesPerSecondField = "lastQueriesPerSecond";
private static final String lastWritesPerSecondField = "lastWritesPerSecond";
private static final String jobStatusField = "jobStatus";
private static final String jobTypeField = "jobType";
private static final String errorField = "jobError";
private static final String lastTriggeredField = "lastTriggered";
private static final String lastCompletedField = "lastCompleted";
private static final String firstFailingField = "firstFailing";
private static final String lastSuccessField = "lastSuccess";
private static final String pausedUntilField = "pausedUntil";
private static final String jobRunIdField = "id";
private static final String versionField = "version";
private static final String revisionField = "revision";
private static final String sourceVersionField = "sourceVersion";
private static final String sourceApplicationField = "sourceRevision";
private static final String reasonField = "reason";
private static final String atField = "at";
private static final String clusterInfoField = "clusterInfo";
private static final String clusterInfoFlavorField = "flavor";
private static final String clusterInfoCostField = "cost";
private static final String clusterInfoCpuField = "flavorCpu";
private static final String clusterInfoMemField = "flavorMem";
private static final String clusterInfoDiskField = "flavorDisk";
private static final String clusterInfoTypeField = "clusterType";
private static final String clusterInfoHostnamesField = "hostnames";
private static final String clusterUtilsField = "clusterUtils";
private static final String clusterUtilsCpuField = "cpu";
private static final String clusterUtilsMemField = "mem";
private static final String clusterUtilsDiskField = "disk";
private static final String clusterUtilsDiskBusyField = "diskbusy";
private static final String deploymentMetricsField = "metrics";
private static final String deploymentMetricsQPSField = "queriesPerSecond";
private static final String deploymentMetricsWPSField = "writesPerSecond";
private static final String deploymentMetricsDocsField = "documentCount";
private static final String deploymentMetricsQueryLatencyField = "queryLatencyMillis";
private static final String deploymentMetricsWriteLatencyField = "writeLatencyMillis";
private static final String deploymentMetricsUpdateTime = "lastUpdated";
private static final String deploymentMetricsWarningsField = "warnings";
private static final String rotationStatusField = "rotationStatus2";
private static final String rotationIdField = "rotationId";
private static final String rotationStateField = "state";
private static final String statusField = "status";
public Slime toSlime(Application application) {
Slime slime = new Slime();
Cursor root = slime.setObject();
root.setString(idField, application.id().serialized());
root.setLong(createdAtField, application.createdAt().toEpochMilli());
root.setString(deploymentSpecField, application.deploymentSpec().xmlForm());
root.setString(validationOverridesField, application.validationOverrides().xmlForm());
application.projectId().ifPresent(projectId -> root.setLong(projectIdField, projectId));
application.deploymentIssueId().ifPresent(jiraIssueId -> root.setString(deploymentIssueField, jiraIssueId.value()));
application.ownershipIssueId().ifPresent(issueId -> root.setString(ownershipIssueIdField, issueId.value()));
root.setBool(builtInternallyField, application.internal());
toSlime(application.change(), root, deployingField);
toSlime(application.outstandingChange(), root, outstandingChangeField);
application.owner().ifPresent(owner -> root.setString(ownerField, owner.username()));
application.majorVersion().ifPresent(majorVersion -> root.setLong(majorVersionField, majorVersion));
root.setDouble(queryQualityField, application.metrics().queryServiceQuality());
root.setDouble(writeQualityField, application.metrics().writeServiceQuality());
deployKeysToSlime(application.pemDeployKeys().stream(), root.setArray(pemDeployKeysField));
instancesToSlime(application, root.setArray(instancesField));
return slime;
}
private void instancesToSlime(Application application, Cursor array) {
for (Instance instance : application.instances().values()) {
Cursor instanceObject = array.addObject();
instanceObject.setString(instanceNameField, instance.name().value());
deploymentsToSlime(instance.deployments().values(), instanceObject.setArray(deploymentsField));
toSlime(instance.deploymentJobs(), instanceObject.setObject(deploymentJobsField));
assignedRotationsToSlime(instance.rotations(), instanceObject, assignedRotationsField);
toSlime(instance.rotationStatus(), instanceObject.setArray(rotationStatusField));
}
}
private void deployKeysToSlime(Stream<String> pemDeployKeys, Cursor array) {
pemDeployKeys.forEach(array::addString);
}
private void deploymentsToSlime(Collection<Deployment> deployments, Cursor array) {
for (Deployment deployment : deployments)
deploymentToSlime(deployment, array.addObject());
}
private void deploymentToSlime(Deployment deployment, Cursor object) {
zoneIdToSlime(deployment.zone(), object.setObject(zoneField));
object.setString(versionField, deployment.version().toString());
object.setLong(deployTimeField, deployment.at().toEpochMilli());
toSlime(deployment.applicationVersion(), object.setObject(applicationPackageRevisionField));
clusterInfoToSlime(deployment.clusterInfo(), object);
clusterUtilsToSlime(deployment.clusterUtils(), object);
deploymentMetricsToSlime(deployment.metrics(), object);
deployment.activity().lastQueried().ifPresent(instant -> object.setLong(lastQueriedField, instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> object.setLong(lastWrittenField, instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> object.setDouble(lastQueriesPerSecondField, value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> object.setDouble(lastWritesPerSecondField, value));
}
private void deploymentMetricsToSlime(DeploymentMetrics metrics, Cursor object) {
Cursor root = object.setObject(deploymentMetricsField);
root.setDouble(deploymentMetricsQPSField, metrics.queriesPerSecond());
root.setDouble(deploymentMetricsWPSField, metrics.writesPerSecond());
root.setDouble(deploymentMetricsDocsField, metrics.documentCount());
root.setDouble(deploymentMetricsQueryLatencyField, metrics.queryLatencyMillis());
root.setDouble(deploymentMetricsWriteLatencyField, metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> root.setLong(deploymentMetricsUpdateTime, instant.toEpochMilli()));
if (!metrics.warnings().isEmpty()) {
Cursor warningsObject = root.setObject(deploymentMetricsWarningsField);
metrics.warnings().forEach((warning, count) -> warningsObject.setLong(warning.name(), count));
}
}
private void clusterInfoToSlime(Map<ClusterSpec.Id, ClusterInfo> clusters, Cursor object) {
Cursor root = object.setObject(clusterInfoField);
for (Map.Entry<ClusterSpec.Id, ClusterInfo> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterInfo info, Cursor object) {
object.setString(clusterInfoFlavorField, info.getFlavor());
object.setLong(clusterInfoCostField, info.getFlavorCost());
object.setDouble(clusterInfoCpuField, info.getFlavorCPU());
object.setDouble(clusterInfoMemField, info.getFlavorMem());
object.setDouble(clusterInfoDiskField, info.getFlavorDisk());
object.setString(clusterInfoTypeField, info.getClusterType().name());
Cursor array = object.setArray(clusterInfoHostnamesField);
for (String host : info.getHostnames()) {
array.addString(host);
}
}
private void clusterUtilsToSlime(Map<ClusterSpec.Id, ClusterUtilization> clusters, Cursor object) {
Cursor root = object.setObject(clusterUtilsField);
for (Map.Entry<ClusterSpec.Id, ClusterUtilization> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterUtilization utils, Cursor object) {
object.setDouble(clusterUtilsCpuField, utils.getCpu());
object.setDouble(clusterUtilsMemField, utils.getMemory());
object.setDouble(clusterUtilsDiskField, utils.getDisk());
object.setDouble(clusterUtilsDiskBusyField, utils.getDiskBusy());
}
private void zoneIdToSlime(ZoneId zone, Cursor object) {
object.setString(environmentField, zone.environment().value());
object.setString(regionField, zone.region().value());
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if (applicationVersion.buildNumber().isPresent() && applicationVersion.source().isPresent()) {
object.setLong(applicationBuildNumberField, applicationVersion.buildNumber().getAsLong());
toSlime(applicationVersion.source().get(), object.setObject(sourceRevisionField));
applicationVersion.authorEmail().ifPresent(email -> object.setString(authorEmailField, email));
applicationVersion.compileVersion().ifPresent(version -> object.setString(compileVersionField, version.toString()));
applicationVersion.buildTime().ifPresent(time -> object.setLong(buildTimeField, time.toEpochMilli()));
}
}
private void toSlime(SourceRevision sourceRevision, Cursor object) {
object.setString(repositoryField, sourceRevision.repository());
object.setString(branchField, sourceRevision.branch());
object.setString(commitField, sourceRevision.commit());
}
private void toSlime(DeploymentJobs deploymentJobs, Cursor cursor) {
jobStatusToSlime(deploymentJobs.jobStatus().values(), cursor.setArray(jobStatusField));
}
private void jobStatusToSlime(Collection<JobStatus> jobStatuses, Cursor jobStatusArray) {
for (JobStatus jobStatus : jobStatuses)
toSlime(jobStatus, jobStatusArray.addObject());
}
private void toSlime(JobStatus jobStatus, Cursor object) {
object.setString(jobTypeField, jobStatus.type().jobName());
if (jobStatus.jobError().isPresent())
object.setString(errorField, jobStatus.jobError().get().name());
jobStatus.lastTriggered().ifPresent(run -> jobRunToSlime(run, object, lastTriggeredField));
jobStatus.lastCompleted().ifPresent(run -> jobRunToSlime(run, object, lastCompletedField));
jobStatus.lastSuccess().ifPresent(run -> jobRunToSlime(run, object, lastSuccessField));
jobStatus.firstFailing().ifPresent(run -> jobRunToSlime(run, object, firstFailingField));
jobStatus.pausedUntil().ifPresent(until -> object.setLong(pausedUntilField, until));
}
private void jobRunToSlime(JobStatus.JobRun jobRun, Cursor parent, String jobRunObjectName) {
Cursor object = parent.setObject(jobRunObjectName);
object.setLong(jobRunIdField, jobRun.id());
object.setString(versionField, jobRun.platform().toString());
toSlime(jobRun.application(), object.setObject(revisionField));
jobRun.sourcePlatform().ifPresent(version -> object.setString(sourceVersionField, version.toString()));
jobRun.sourceApplication().ifPresent(version -> toSlime(version, object.setObject(sourceApplicationField)));
object.setString(reasonField, jobRun.reason());
object.setLong(atField, jobRun.at().toEpochMilli());
}
private void toSlime(Change deploying, Cursor parentObject, String fieldName) {
if (deploying.isEmpty()) return;
Cursor object = parentObject.setObject(fieldName);
if (deploying.platform().isPresent())
object.setString(versionField, deploying.platform().get().toString());
if (deploying.application().isPresent())
toSlime(deploying.application().get(), object);
if (deploying.isPinned())
object.setBool(pinnedField, true);
}
private void toSlime(RotationStatus status, Cursor array) {
status.asMap().forEach((rotationId, zoneStatus) -> {
Cursor rotationObject = array.addObject();
rotationObject.setString(rotationIdField, rotationId.asString());
Cursor statusArray = rotationObject.setArray(statusField);
zoneStatus.forEach((zone, state) -> {
Cursor statusObject = statusArray.addObject();
zoneIdToSlime(zone, statusObject);
statusObject.setString(rotationStateField, state.name());
});
});
}
private void assignedRotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) {
var rotationsArray = parent.setArray(fieldName);
for (var rotation : rotations) {
var object = rotationsArray.addObject();
object.setString(assignedRotationEndpointField, rotation.endpointId().id());
object.setString(assignedRotationRotationField, rotation.rotationId().asString());
object.setString(assignedRotationClusterField, rotation.clusterId().value());
}
}
private List<Instance> instancesFromSlime(TenantAndApplicationId id, DeploymentSpec deploymentSpec, Inspector field) {
List<Instance> instances = new ArrayList<>();
field.traverse((ArrayTraverser) (name, object) -> {
InstanceName instanceName = InstanceName.from(object.field(instanceNameField).asString());
List<Deployment> deployments = deploymentsFromSlime(object.field(deploymentsField));
DeploymentJobs deploymentJobs = deploymentJobsFromSlime(object.field(deploymentJobsField));
List<AssignedRotation> assignedRotations = assignedRotationsFromSlime(deploymentSpec, object);
RotationStatus rotationStatus = rotationStatusFromSlime(object);
instances.add(new Instance(id.instance(instanceName),
deployments,
deploymentJobs,
assignedRotations,
rotationStatus));
});
return instances;
}
private List<String> pemDeployKeysFromSlime(Inspector array) {
List<String> keys = new ArrayList<>();
array.traverse((ArrayTraverser) (__, key) -> keys.add(key.asString()));
return keys;
}
private List<Deployment> deploymentsFromSlime(Inspector array) {
List<Deployment> deployments = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> deployments.add(deploymentFromSlime(item)));
return deployments;
}
private Deployment deploymentFromSlime(Inspector deploymentObject) {
return new Deployment(zoneIdFromSlime(deploymentObject.field(zoneField)),
applicationVersionFromSlime(deploymentObject.field(applicationPackageRevisionField)),
Version.fromString(deploymentObject.field(versionField).asString()),
Instant.ofEpochMilli(deploymentObject.field(deployTimeField).asLong()),
clusterUtilsMapFromSlime(deploymentObject.field(clusterUtilsField)),
clusterInfoMapFromSlime(deploymentObject.field(clusterInfoField)),
deploymentMetricsFromSlime(deploymentObject.field(deploymentMetricsField)),
DeploymentActivity.create(Serializers.optionalInstant(deploymentObject.field(lastQueriedField)),
Serializers.optionalInstant(deploymentObject.field(lastWrittenField)),
Serializers.optionalDouble(deploymentObject.field(lastQueriesPerSecondField)),
Serializers.optionalDouble(deploymentObject.field(lastWritesPerSecondField))));
}
private DeploymentMetrics deploymentMetricsFromSlime(Inspector object) {
Optional<Instant> instant = object.field(deploymentMetricsUpdateTime).valid() ?
Optional.of(Instant.ofEpochMilli(object.field(deploymentMetricsUpdateTime).asLong())) :
Optional.empty();
return new DeploymentMetrics(object.field(deploymentMetricsQPSField).asDouble(),
object.field(deploymentMetricsWPSField).asDouble(),
object.field(deploymentMetricsDocsField).asDouble(),
object.field(deploymentMetricsQueryLatencyField).asDouble(),
object.field(deploymentMetricsWriteLatencyField).asDouble(),
instant,
deploymentWarningsFrom(object.field(deploymentMetricsWarningsField)));
}
private Map<DeploymentMetrics.Warning, Integer> deploymentWarningsFrom(Inspector object) {
Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>();
object.traverse((ObjectTraverser) (name, value) -> warnings.put(DeploymentMetrics.Warning.valueOf(name),
(int) value.asLong()));
return Collections.unmodifiableMap(warnings);
}
private RotationStatus rotationStatusFromSlime(Inspector parentObject) {
var object = parentObject.field(rotationStatusField);
var statusMap = new LinkedHashMap<RotationId, Map<ZoneId, RotationState>>();
object.traverse((ArrayTraverser) (idx, statusObject) -> statusMap.put(new RotationId(statusObject.field(rotationIdField).asString()),
singleRotationStatusFromSlime(statusObject.field(statusField))));
return RotationStatus.from(statusMap);
}
private Map<ZoneId, RotationState> singleRotationStatusFromSlime(Inspector object) {
if (!object.valid()) {
return Collections.emptyMap();
}
Map<ZoneId, RotationState> rotationStatus = new LinkedHashMap<>();
object.traverse((ArrayTraverser) (idx, statusObject) -> {
var zone = zoneIdFromSlime(statusObject);
var status = RotationState.valueOf(statusObject.field(rotationStateField).asString());
rotationStatus.put(zone, status);
});
return Collections.unmodifiableMap(rotationStatus);
}
private Map<ClusterSpec.Id, ClusterInfo> clusterInfoMapFromSlime (Inspector object) {
Map<ClusterSpec.Id, ClusterInfo> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterInfoFromSlime(value)));
return map;
}
private Map<ClusterSpec.Id, ClusterUtilization> clusterUtilsMapFromSlime(Inspector object) {
Map<ClusterSpec.Id, ClusterUtilization> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterUtililzationFromSlime(value)));
return map;
}
private ClusterUtilization clusterUtililzationFromSlime(Inspector object) {
double cpu = object.field(clusterUtilsCpuField).asDouble();
double mem = object.field(clusterUtilsMemField).asDouble();
double disk = object.field(clusterUtilsDiskField).asDouble();
double diskBusy = object.field(clusterUtilsDiskBusyField).asDouble();
return new ClusterUtilization(mem, cpu, disk, diskBusy);
}
private ClusterInfo clusterInfoFromSlime(Inspector inspector) {
String flavor = inspector.field(clusterInfoFlavorField).asString();
int cost = (int)inspector.field(clusterInfoCostField).asLong();
String type = inspector.field(clusterInfoTypeField).asString();
double flavorCpu = inspector.field(clusterInfoCpuField).asDouble();
double flavorMem = inspector.field(clusterInfoMemField).asDouble();
double flavorDisk = inspector.field(clusterInfoDiskField).asDouble();
List<String> hostnames = new ArrayList<>();
inspector.field(clusterInfoHostnamesField).traverse((ArrayTraverser)(int index, Inspector value) -> hostnames.add(value.asString()));
return new ClusterInfo(flavor, cost, flavorCpu, flavorMem, flavorDisk, ClusterSpec.Type.from(type), hostnames);
}
private ZoneId zoneIdFromSlime(Inspector object) {
return ZoneId.from(object.field(environmentField).asString(), object.field(regionField).asString());
}
private ApplicationVersion applicationVersionFromSlime(Inspector object) {
if ( ! object.valid()) return ApplicationVersion.unknown;
OptionalLong applicationBuildNumber = Serializers.optionalLong(object.field(applicationBuildNumberField));
Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField));
if (sourceRevision.isEmpty() || applicationBuildNumber.isEmpty()) {
return ApplicationVersion.unknown;
}
Optional<String> authorEmail = Serializers.optionalString(object.field(authorEmailField));
Optional<Version> compileVersion = Serializers.optionalString(object.field(compileVersionField)).map(Version::fromString);
Optional<Instant> buildTime = Serializers.optionalInstant(object.field(buildTimeField));
if (authorEmail.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong());
if (compileVersion.isEmpty() || buildTime.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get());
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get(),
compileVersion.get(), buildTime.get());
}
private Optional<SourceRevision> sourceRevisionFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new SourceRevision(object.field(repositoryField).asString(),
object.field(branchField).asString(),
object.field(commitField).asString()));
}
private DeploymentJobs deploymentJobsFromSlime(Inspector object) {
List<JobStatus> jobStatusList = jobStatusListFromSlime(object.field(jobStatusField));
return new DeploymentJobs(jobStatusList);
}
private Change changeFromSlime(Inspector object) {
if ( ! object.valid()) return Change.empty();
Inspector versionFieldValue = object.field(versionField);
Change change = Change.empty();
if (versionFieldValue.valid())
change = Change.of(Version.fromString(versionFieldValue.asString()));
if (object.field(applicationBuildNumberField).valid())
change = change.with(applicationVersionFromSlime(object));
if (object.field(pinnedField).asBool())
change = change.withPin();
return change;
}
private List<JobStatus> jobStatusListFromSlime(Inspector array) {
List<JobStatus> jobStatusList = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> jobStatusFromSlime(item).ifPresent(jobStatusList::add));
return jobStatusList;
}
private Optional<JobStatus> jobStatusFromSlime(Inspector object) {
Optional<JobType> jobType =
JobType.fromOptionalJobName(object.field(jobTypeField).asString());
if (jobType.isEmpty()) return Optional.empty();
Optional<JobError> jobError = Optional.empty();
if (object.field(errorField).valid())
jobError = Optional.of(JobError.valueOf(object.field(errorField).asString()));
return Optional.of(new JobStatus(jobType.get(),
jobError,
jobRunFromSlime(object.field(lastTriggeredField)),
jobRunFromSlime(object.field(lastCompletedField)),
jobRunFromSlime(object.field(firstFailingField)),
jobRunFromSlime(object.field(lastSuccessField)),
Serializers.optionalLong(object.field(pausedUntilField))));
}
private Optional<JobStatus.JobRun> jobRunFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new JobStatus.JobRun(object.field(jobRunIdField).asLong(),
new Version(object.field(versionField).asString()),
applicationVersionFromSlime(object.field(revisionField)),
Serializers.optionalString(object.field(sourceVersionField)).map(Version::fromString),
Optional.of(object.field(sourceApplicationField)).filter(Inspector::valid).map(this::applicationVersionFromSlime),
object.field(reasonField).asString(),
Instant.ofEpochMilli(object.field(atField).asLong())));
}
private List<AssignedRotation> assignedRotationsFromSlime(DeploymentSpec deploymentSpec, Inspector root) {
var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>();
root.field(assignedRotationsField).traverse((ArrayTraverser) (idx, inspector) -> {
var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString());
var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString());
var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString());
var regions = deploymentSpec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
} | class ApplicationSerializer {
private static final String idField = "id";
private static final String createdAtField = "createdAt";
private static final String deploymentSpecField = "deploymentSpecField";
private static final String validationOverridesField = "validationOverrides";
private static final String instancesField = "instances";
private static final String deployingField = "deployingField";
private static final String projectIdField = "projectId";
private static final String builtInternallyField = "builtInternally";
private static final String pinnedField = "pinned";
private static final String outstandingChangeField = "outstandingChangeField";
private static final String deploymentIssueField = "deploymentIssueId";
private static final String ownershipIssueIdField = "ownershipIssueId";
private static final String ownerField = "confirmedOwner";
private static final String majorVersionField = "majorVersion";
private static final String writeQualityField = "writeQuality";
private static final String queryQualityField = "queryQuality";
private static final String pemDeployKeysField = "pemDeployKeys";
private static final String assignedRotationClusterField = "clusterId";
private static final String assignedRotationRotationField = "rotationId";
private static final String applicationCertificateField = "applicationCertificate";
private static final String instanceNameField = "instanceName";
private static final String deploymentsField = "deployments";
private static final String deploymentJobsField = "deploymentJobs";
private static final String assignedRotationsField = "assignedRotations";
private static final String assignedRotationEndpointField = "endpointId";
private static final String zoneField = "zone";
private static final String environmentField = "environment";
private static final String regionField = "region";
private static final String deployTimeField = "deployTime";
private static final String applicationBuildNumberField = "applicationBuildNumber";
private static final String applicationPackageRevisionField = "applicationPackageRevision";
private static final String sourceRevisionField = "sourceRevision";
private static final String repositoryField = "repositoryField";
private static final String branchField = "branchField";
private static final String commitField = "commitField";
private static final String authorEmailField = "authorEmailField";
private static final String compileVersionField = "compileVersion";
private static final String buildTimeField = "buildTime";
private static final String lastQueriedField = "lastQueried";
private static final String lastWrittenField = "lastWritten";
private static final String lastQueriesPerSecondField = "lastQueriesPerSecond";
private static final String lastWritesPerSecondField = "lastWritesPerSecond";
private static final String jobStatusField = "jobStatus";
private static final String jobTypeField = "jobType";
private static final String errorField = "jobError";
private static final String lastTriggeredField = "lastTriggered";
private static final String lastCompletedField = "lastCompleted";
private static final String firstFailingField = "firstFailing";
private static final String lastSuccessField = "lastSuccess";
private static final String pausedUntilField = "pausedUntil";
private static final String jobRunIdField = "id";
private static final String versionField = "version";
private static final String revisionField = "revision";
private static final String sourceVersionField = "sourceVersion";
private static final String sourceApplicationField = "sourceRevision";
private static final String reasonField = "reason";
private static final String atField = "at";
private static final String clusterInfoField = "clusterInfo";
private static final String clusterInfoFlavorField = "flavor";
private static final String clusterInfoCostField = "cost";
private static final String clusterInfoCpuField = "flavorCpu";
private static final String clusterInfoMemField = "flavorMem";
private static final String clusterInfoDiskField = "flavorDisk";
private static final String clusterInfoTypeField = "clusterType";
private static final String clusterInfoHostnamesField = "hostnames";
private static final String clusterUtilsField = "clusterUtils";
private static final String clusterUtilsCpuField = "cpu";
private static final String clusterUtilsMemField = "mem";
private static final String clusterUtilsDiskField = "disk";
private static final String clusterUtilsDiskBusyField = "diskbusy";
private static final String deploymentMetricsField = "metrics";
private static final String deploymentMetricsQPSField = "queriesPerSecond";
private static final String deploymentMetricsWPSField = "writesPerSecond";
private static final String deploymentMetricsDocsField = "documentCount";
private static final String deploymentMetricsQueryLatencyField = "queryLatencyMillis";
private static final String deploymentMetricsWriteLatencyField = "writeLatencyMillis";
private static final String deploymentMetricsUpdateTime = "lastUpdated";
private static final String deploymentMetricsWarningsField = "warnings";
private static final String rotationStatusField = "rotationStatus2";
private static final String rotationIdField = "rotationId";
private static final String rotationStateField = "state";
private static final String statusField = "status";
public Slime toSlime(Application application) {
Slime slime = new Slime();
Cursor root = slime.setObject();
root.setString(idField, application.id().serialized());
root.setLong(createdAtField, application.createdAt().toEpochMilli());
root.setString(deploymentSpecField, application.deploymentSpec().xmlForm());
root.setString(validationOverridesField, application.validationOverrides().xmlForm());
application.projectId().ifPresent(projectId -> root.setLong(projectIdField, projectId));
application.deploymentIssueId().ifPresent(jiraIssueId -> root.setString(deploymentIssueField, jiraIssueId.value()));
application.ownershipIssueId().ifPresent(issueId -> root.setString(ownershipIssueIdField, issueId.value()));
root.setBool(builtInternallyField, application.internal());
toSlime(application.change(), root, deployingField);
toSlime(application.outstandingChange(), root, outstandingChangeField);
application.owner().ifPresent(owner -> root.setString(ownerField, owner.username()));
application.majorVersion().ifPresent(majorVersion -> root.setLong(majorVersionField, majorVersion));
root.setDouble(queryQualityField, application.metrics().queryServiceQuality());
root.setDouble(writeQualityField, application.metrics().writeServiceQuality());
deployKeysToSlime(application.pemDeployKeys().stream(), root.setArray(pemDeployKeysField));
instancesToSlime(application, root.setArray(instancesField));
return slime;
}
private void instancesToSlime(Application application, Cursor array) {
for (Instance instance : application.instances().values()) {
Cursor instanceObject = array.addObject();
instanceObject.setString(instanceNameField, instance.name().value());
deploymentsToSlime(instance.deployments().values(), instanceObject.setArray(deploymentsField));
toSlime(instance.deploymentJobs(), instanceObject.setObject(deploymentJobsField));
assignedRotationsToSlime(instance.rotations(), instanceObject, assignedRotationsField);
toSlime(instance.rotationStatus(), instanceObject.setArray(rotationStatusField));
}
}
private void deployKeysToSlime(Stream<String> pemDeployKeys, Cursor array) {
pemDeployKeys.forEach(array::addString);
}
private void deploymentsToSlime(Collection<Deployment> deployments, Cursor array) {
for (Deployment deployment : deployments)
deploymentToSlime(deployment, array.addObject());
}
private void deploymentToSlime(Deployment deployment, Cursor object) {
zoneIdToSlime(deployment.zone(), object.setObject(zoneField));
object.setString(versionField, deployment.version().toString());
object.setLong(deployTimeField, deployment.at().toEpochMilli());
toSlime(deployment.applicationVersion(), object.setObject(applicationPackageRevisionField));
clusterInfoToSlime(deployment.clusterInfo(), object);
clusterUtilsToSlime(deployment.clusterUtils(), object);
deploymentMetricsToSlime(deployment.metrics(), object);
deployment.activity().lastQueried().ifPresent(instant -> object.setLong(lastQueriedField, instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> object.setLong(lastWrittenField, instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> object.setDouble(lastQueriesPerSecondField, value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> object.setDouble(lastWritesPerSecondField, value));
}
private void deploymentMetricsToSlime(DeploymentMetrics metrics, Cursor object) {
Cursor root = object.setObject(deploymentMetricsField);
root.setDouble(deploymentMetricsQPSField, metrics.queriesPerSecond());
root.setDouble(deploymentMetricsWPSField, metrics.writesPerSecond());
root.setDouble(deploymentMetricsDocsField, metrics.documentCount());
root.setDouble(deploymentMetricsQueryLatencyField, metrics.queryLatencyMillis());
root.setDouble(deploymentMetricsWriteLatencyField, metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> root.setLong(deploymentMetricsUpdateTime, instant.toEpochMilli()));
if (!metrics.warnings().isEmpty()) {
Cursor warningsObject = root.setObject(deploymentMetricsWarningsField);
metrics.warnings().forEach((warning, count) -> warningsObject.setLong(warning.name(), count));
}
}
private void clusterInfoToSlime(Map<ClusterSpec.Id, ClusterInfo> clusters, Cursor object) {
Cursor root = object.setObject(clusterInfoField);
for (Map.Entry<ClusterSpec.Id, ClusterInfo> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterInfo info, Cursor object) {
object.setString(clusterInfoFlavorField, info.getFlavor());
object.setLong(clusterInfoCostField, info.getFlavorCost());
object.setDouble(clusterInfoCpuField, info.getFlavorCPU());
object.setDouble(clusterInfoMemField, info.getFlavorMem());
object.setDouble(clusterInfoDiskField, info.getFlavorDisk());
object.setString(clusterInfoTypeField, info.getClusterType().name());
Cursor array = object.setArray(clusterInfoHostnamesField);
for (String host : info.getHostnames()) {
array.addString(host);
}
}
private void clusterUtilsToSlime(Map<ClusterSpec.Id, ClusterUtilization> clusters, Cursor object) {
Cursor root = object.setObject(clusterUtilsField);
for (Map.Entry<ClusterSpec.Id, ClusterUtilization> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterUtilization utils, Cursor object) {
object.setDouble(clusterUtilsCpuField, utils.getCpu());
object.setDouble(clusterUtilsMemField, utils.getMemory());
object.setDouble(clusterUtilsDiskField, utils.getDisk());
object.setDouble(clusterUtilsDiskBusyField, utils.getDiskBusy());
}
private void zoneIdToSlime(ZoneId zone, Cursor object) {
object.setString(environmentField, zone.environment().value());
object.setString(regionField, zone.region().value());
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if (applicationVersion.buildNumber().isPresent() && applicationVersion.source().isPresent()) {
object.setLong(applicationBuildNumberField, applicationVersion.buildNumber().getAsLong());
toSlime(applicationVersion.source().get(), object.setObject(sourceRevisionField));
applicationVersion.authorEmail().ifPresent(email -> object.setString(authorEmailField, email));
applicationVersion.compileVersion().ifPresent(version -> object.setString(compileVersionField, version.toString()));
applicationVersion.buildTime().ifPresent(time -> object.setLong(buildTimeField, time.toEpochMilli()));
}
}
private void toSlime(SourceRevision sourceRevision, Cursor object) {
object.setString(repositoryField, sourceRevision.repository());
object.setString(branchField, sourceRevision.branch());
object.setString(commitField, sourceRevision.commit());
}
private void toSlime(DeploymentJobs deploymentJobs, Cursor cursor) {
jobStatusToSlime(deploymentJobs.jobStatus().values(), cursor.setArray(jobStatusField));
}
private void jobStatusToSlime(Collection<JobStatus> jobStatuses, Cursor jobStatusArray) {
for (JobStatus jobStatus : jobStatuses)
toSlime(jobStatus, jobStatusArray.addObject());
}
private void toSlime(JobStatus jobStatus, Cursor object) {
object.setString(jobTypeField, jobStatus.type().jobName());
if (jobStatus.jobError().isPresent())
object.setString(errorField, jobStatus.jobError().get().name());
jobStatus.lastTriggered().ifPresent(run -> jobRunToSlime(run, object, lastTriggeredField));
jobStatus.lastCompleted().ifPresent(run -> jobRunToSlime(run, object, lastCompletedField));
jobStatus.lastSuccess().ifPresent(run -> jobRunToSlime(run, object, lastSuccessField));
jobStatus.firstFailing().ifPresent(run -> jobRunToSlime(run, object, firstFailingField));
jobStatus.pausedUntil().ifPresent(until -> object.setLong(pausedUntilField, until));
}
private void jobRunToSlime(JobStatus.JobRun jobRun, Cursor parent, String jobRunObjectName) {
Cursor object = parent.setObject(jobRunObjectName);
object.setLong(jobRunIdField, jobRun.id());
object.setString(versionField, jobRun.platform().toString());
toSlime(jobRun.application(), object.setObject(revisionField));
jobRun.sourcePlatform().ifPresent(version -> object.setString(sourceVersionField, version.toString()));
jobRun.sourceApplication().ifPresent(version -> toSlime(version, object.setObject(sourceApplicationField)));
object.setString(reasonField, jobRun.reason());
object.setLong(atField, jobRun.at().toEpochMilli());
}
private void toSlime(Change deploying, Cursor parentObject, String fieldName) {
if (deploying.isEmpty()) return;
Cursor object = parentObject.setObject(fieldName);
if (deploying.platform().isPresent())
object.setString(versionField, deploying.platform().get().toString());
if (deploying.application().isPresent())
toSlime(deploying.application().get(), object);
if (deploying.isPinned())
object.setBool(pinnedField, true);
}
private void toSlime(RotationStatus status, Cursor array) {
status.asMap().forEach((rotationId, zoneStatus) -> {
Cursor rotationObject = array.addObject();
rotationObject.setString(rotationIdField, rotationId.asString());
Cursor statusArray = rotationObject.setArray(statusField);
zoneStatus.forEach((zone, state) -> {
Cursor statusObject = statusArray.addObject();
zoneIdToSlime(zone, statusObject);
statusObject.setString(rotationStateField, state.name());
});
});
}
private void assignedRotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) {
var rotationsArray = parent.setArray(fieldName);
for (var rotation : rotations) {
var object = rotationsArray.addObject();
object.setString(assignedRotationEndpointField, rotation.endpointId().id());
object.setString(assignedRotationRotationField, rotation.rotationId().asString());
object.setString(assignedRotationClusterField, rotation.clusterId().value());
}
}
private List<Instance> instancesFromSlime(TenantAndApplicationId id, DeploymentSpec deploymentSpec, Inspector field) {
List<Instance> instances = new ArrayList<>();
field.traverse((ArrayTraverser) (name, object) -> {
InstanceName instanceName = InstanceName.from(object.field(instanceNameField).asString());
List<Deployment> deployments = deploymentsFromSlime(object.field(deploymentsField));
DeploymentJobs deploymentJobs = deploymentJobsFromSlime(object.field(deploymentJobsField));
List<AssignedRotation> assignedRotations = assignedRotationsFromSlime(deploymentSpec, object);
RotationStatus rotationStatus = rotationStatusFromSlime(object);
instances.add(new Instance(id.instance(instanceName),
deployments,
deploymentJobs,
assignedRotations,
rotationStatus));
});
return instances;
}
private Set<String> pemDeployKeysFromSlime(Inspector array) {
Set<String> keys = new LinkedHashSet<>();
array.traverse((ArrayTraverser) (__, key) -> keys.add(key.asString()));
return keys;
}
private List<Deployment> deploymentsFromSlime(Inspector array) {
List<Deployment> deployments = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> deployments.add(deploymentFromSlime(item)));
return deployments;
}
private Deployment deploymentFromSlime(Inspector deploymentObject) {
return new Deployment(zoneIdFromSlime(deploymentObject.field(zoneField)),
applicationVersionFromSlime(deploymentObject.field(applicationPackageRevisionField)),
Version.fromString(deploymentObject.field(versionField).asString()),
Instant.ofEpochMilli(deploymentObject.field(deployTimeField).asLong()),
clusterUtilsMapFromSlime(deploymentObject.field(clusterUtilsField)),
clusterInfoMapFromSlime(deploymentObject.field(clusterInfoField)),
deploymentMetricsFromSlime(deploymentObject.field(deploymentMetricsField)),
DeploymentActivity.create(Serializers.optionalInstant(deploymentObject.field(lastQueriedField)),
Serializers.optionalInstant(deploymentObject.field(lastWrittenField)),
Serializers.optionalDouble(deploymentObject.field(lastQueriesPerSecondField)),
Serializers.optionalDouble(deploymentObject.field(lastWritesPerSecondField))));
}
private DeploymentMetrics deploymentMetricsFromSlime(Inspector object) {
Optional<Instant> instant = object.field(deploymentMetricsUpdateTime).valid() ?
Optional.of(Instant.ofEpochMilli(object.field(deploymentMetricsUpdateTime).asLong())) :
Optional.empty();
return new DeploymentMetrics(object.field(deploymentMetricsQPSField).asDouble(),
object.field(deploymentMetricsWPSField).asDouble(),
object.field(deploymentMetricsDocsField).asDouble(),
object.field(deploymentMetricsQueryLatencyField).asDouble(),
object.field(deploymentMetricsWriteLatencyField).asDouble(),
instant,
deploymentWarningsFrom(object.field(deploymentMetricsWarningsField)));
}
private Map<DeploymentMetrics.Warning, Integer> deploymentWarningsFrom(Inspector object) {
Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>();
object.traverse((ObjectTraverser) (name, value) -> warnings.put(DeploymentMetrics.Warning.valueOf(name),
(int) value.asLong()));
return Collections.unmodifiableMap(warnings);
}
private RotationStatus rotationStatusFromSlime(Inspector parentObject) {
var object = parentObject.field(rotationStatusField);
var statusMap = new LinkedHashMap<RotationId, Map<ZoneId, RotationState>>();
object.traverse((ArrayTraverser) (idx, statusObject) -> statusMap.put(new RotationId(statusObject.field(rotationIdField).asString()),
singleRotationStatusFromSlime(statusObject.field(statusField))));
return RotationStatus.from(statusMap);
}
private Map<ZoneId, RotationState> singleRotationStatusFromSlime(Inspector object) {
if (!object.valid()) {
return Collections.emptyMap();
}
Map<ZoneId, RotationState> rotationStatus = new LinkedHashMap<>();
object.traverse((ArrayTraverser) (idx, statusObject) -> {
var zone = zoneIdFromSlime(statusObject);
var status = RotationState.valueOf(statusObject.field(rotationStateField).asString());
rotationStatus.put(zone, status);
});
return Collections.unmodifiableMap(rotationStatus);
}
private Map<ClusterSpec.Id, ClusterInfo> clusterInfoMapFromSlime (Inspector object) {
Map<ClusterSpec.Id, ClusterInfo> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterInfoFromSlime(value)));
return map;
}
private Map<ClusterSpec.Id, ClusterUtilization> clusterUtilsMapFromSlime(Inspector object) {
Map<ClusterSpec.Id, ClusterUtilization> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterUtililzationFromSlime(value)));
return map;
}
private ClusterUtilization clusterUtililzationFromSlime(Inspector object) {
double cpu = object.field(clusterUtilsCpuField).asDouble();
double mem = object.field(clusterUtilsMemField).asDouble();
double disk = object.field(clusterUtilsDiskField).asDouble();
double diskBusy = object.field(clusterUtilsDiskBusyField).asDouble();
return new ClusterUtilization(mem, cpu, disk, diskBusy);
}
private ClusterInfo clusterInfoFromSlime(Inspector inspector) {
String flavor = inspector.field(clusterInfoFlavorField).asString();
int cost = (int)inspector.field(clusterInfoCostField).asLong();
String type = inspector.field(clusterInfoTypeField).asString();
double flavorCpu = inspector.field(clusterInfoCpuField).asDouble();
double flavorMem = inspector.field(clusterInfoMemField).asDouble();
double flavorDisk = inspector.field(clusterInfoDiskField).asDouble();
List<String> hostnames = new ArrayList<>();
inspector.field(clusterInfoHostnamesField).traverse((ArrayTraverser)(int index, Inspector value) -> hostnames.add(value.asString()));
return new ClusterInfo(flavor, cost, flavorCpu, flavorMem, flavorDisk, ClusterSpec.Type.from(type), hostnames);
}
private ZoneId zoneIdFromSlime(Inspector object) {
return ZoneId.from(object.field(environmentField).asString(), object.field(regionField).asString());
}
private ApplicationVersion applicationVersionFromSlime(Inspector object) {
if ( ! object.valid()) return ApplicationVersion.unknown;
OptionalLong applicationBuildNumber = Serializers.optionalLong(object.field(applicationBuildNumberField));
Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField));
if (sourceRevision.isEmpty() || applicationBuildNumber.isEmpty()) {
return ApplicationVersion.unknown;
}
Optional<String> authorEmail = Serializers.optionalString(object.field(authorEmailField));
Optional<Version> compileVersion = Serializers.optionalString(object.field(compileVersionField)).map(Version::fromString);
Optional<Instant> buildTime = Serializers.optionalInstant(object.field(buildTimeField));
if (authorEmail.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong());
if (compileVersion.isEmpty() || buildTime.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get());
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get(),
compileVersion.get(), buildTime.get());
}
private Optional<SourceRevision> sourceRevisionFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new SourceRevision(object.field(repositoryField).asString(),
object.field(branchField).asString(),
object.field(commitField).asString()));
}
private DeploymentJobs deploymentJobsFromSlime(Inspector object) {
List<JobStatus> jobStatusList = jobStatusListFromSlime(object.field(jobStatusField));
return new DeploymentJobs(jobStatusList);
}
private Change changeFromSlime(Inspector object) {
if ( ! object.valid()) return Change.empty();
Inspector versionFieldValue = object.field(versionField);
Change change = Change.empty();
if (versionFieldValue.valid())
change = Change.of(Version.fromString(versionFieldValue.asString()));
if (object.field(applicationBuildNumberField).valid())
change = change.with(applicationVersionFromSlime(object));
if (object.field(pinnedField).asBool())
change = change.withPin();
return change;
}
private List<JobStatus> jobStatusListFromSlime(Inspector array) {
List<JobStatus> jobStatusList = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> jobStatusFromSlime(item).ifPresent(jobStatusList::add));
return jobStatusList;
}
private Optional<JobStatus> jobStatusFromSlime(Inspector object) {
Optional<JobType> jobType =
JobType.fromOptionalJobName(object.field(jobTypeField).asString());
if (jobType.isEmpty()) return Optional.empty();
Optional<JobError> jobError = Optional.empty();
if (object.field(errorField).valid())
jobError = Optional.of(JobError.valueOf(object.field(errorField).asString()));
return Optional.of(new JobStatus(jobType.get(),
jobError,
jobRunFromSlime(object.field(lastTriggeredField)),
jobRunFromSlime(object.field(lastCompletedField)),
jobRunFromSlime(object.field(firstFailingField)),
jobRunFromSlime(object.field(lastSuccessField)),
Serializers.optionalLong(object.field(pausedUntilField))));
}
private Optional<JobStatus.JobRun> jobRunFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new JobStatus.JobRun(object.field(jobRunIdField).asLong(),
new Version(object.field(versionField).asString()),
applicationVersionFromSlime(object.field(revisionField)),
Serializers.optionalString(object.field(sourceVersionField)).map(Version::fromString),
Optional.of(object.field(sourceApplicationField)).filter(Inspector::valid).map(this::applicationVersionFromSlime),
object.field(reasonField).asString(),
Instant.ofEpochMilli(object.field(atField).asLong())));
}
private List<AssignedRotation> assignedRotationsFromSlime(DeploymentSpec deploymentSpec, Inspector root) {
var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>();
root.field(assignedRotationsField).traverse((ArrayTraverser) (idx, inspector) -> {
var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString());
var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString());
var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString());
var regions = deploymentSpec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
} |
Nit: It's generally better to have the constructor guarantee immutability, rather than individual methods. | public Cloud withPemDeveloperKey(String pemKey, Principal principal) {
ImmutableBiMap.Builder<String, Principal> keys = ImmutableBiMap.builder();
pemDeveloperKeys.forEach((key, user) -> {
if ( ! user.equals(principal))
keys.put(key, user);
});
keys.put(pemKey, principal);
return new Cloud(name, billingInfo, keys.build());
} | ImmutableBiMap.Builder<String, Principal> keys = ImmutableBiMap.builder(); | public Cloud withPemDeveloperKey(String pemKey, Principal principal) {
ImmutableBiMap.Builder<String, Principal> keys = ImmutableBiMap.builder();
pemDeveloperKeys.forEach((key, user) -> {
if ( ! user.equals(principal))
keys.put(key, user);
});
keys.put(pemKey, principal);
return new Cloud(name, billingInfo, keys.build());
} | class Cloud extends LockedTenant {
private final BillingInfo billingInfo;
private final BiMap<String, Principal> pemDeveloperKeys;
private Cloud(TenantName name, BillingInfo billingInfo, BiMap<String, Principal> pemDeveloperKeys) {
super(name);
this.billingInfo = billingInfo;
this.pemDeveloperKeys = pemDeveloperKeys;
}
private Cloud(CloudTenant tenant) {
this(tenant.name(), tenant.billingInfo(), tenant.pemDeveloperKeys());
}
@Override
public CloudTenant get() {
return new CloudTenant(name, billingInfo, pemDeveloperKeys);
}
public Cloud with(BillingInfo billingInfo) {
return new Cloud(name, billingInfo, pemDeveloperKeys);
}
public Cloud withoutPemDeveloperKey(String pemKey) {
ImmutableBiMap.Builder<String, Principal> keys = ImmutableBiMap.builder();
pemDeveloperKeys.forEach((key, user) -> {
if ( ! key.equals(pemKey))
keys.put(key, user);
});
return new Cloud(name, billingInfo, keys.build());
}
} | class Cloud extends LockedTenant {
private final BillingInfo billingInfo;
private final BiMap<String, Principal> pemDeveloperKeys;
private Cloud(TenantName name, BillingInfo billingInfo, BiMap<String, Principal> pemDeveloperKeys) {
super(name);
this.billingInfo = billingInfo;
this.pemDeveloperKeys = pemDeveloperKeys;
}
private Cloud(CloudTenant tenant) {
this(tenant.name(), tenant.billingInfo(), tenant.pemDeveloperKeys());
}
@Override
public CloudTenant get() {
return new CloudTenant(name, billingInfo, pemDeveloperKeys);
}
public Cloud with(BillingInfo billingInfo) {
return new Cloud(name, billingInfo, pemDeveloperKeys);
}
public Cloud withoutPemDeveloperKey(String pemKey) {
ImmutableBiMap.Builder<String, Principal> keys = ImmutableBiMap.builder();
pemDeveloperKeys.forEach((key, user) -> {
if ( ! key.equals(pemKey))
keys.put(key, user);
});
return new Cloud(name, billingInfo, keys.build());
}
} |
I agree. I didn't realise the `HashBiMap` also preserves iteration order, but I see it does. Will change in a later PR. | public Cloud withPemDeveloperKey(String pemKey, Principal principal) {
ImmutableBiMap.Builder<String, Principal> keys = ImmutableBiMap.builder();
pemDeveloperKeys.forEach((key, user) -> {
if ( ! user.equals(principal))
keys.put(key, user);
});
keys.put(pemKey, principal);
return new Cloud(name, billingInfo, keys.build());
} | ImmutableBiMap.Builder<String, Principal> keys = ImmutableBiMap.builder(); | public Cloud withPemDeveloperKey(String pemKey, Principal principal) {
ImmutableBiMap.Builder<String, Principal> keys = ImmutableBiMap.builder();
pemDeveloperKeys.forEach((key, user) -> {
if ( ! user.equals(principal))
keys.put(key, user);
});
keys.put(pemKey, principal);
return new Cloud(name, billingInfo, keys.build());
} | class Cloud extends LockedTenant {
private final BillingInfo billingInfo;
private final BiMap<String, Principal> pemDeveloperKeys;
private Cloud(TenantName name, BillingInfo billingInfo, BiMap<String, Principal> pemDeveloperKeys) {
super(name);
this.billingInfo = billingInfo;
this.pemDeveloperKeys = pemDeveloperKeys;
}
private Cloud(CloudTenant tenant) {
this(tenant.name(), tenant.billingInfo(), tenant.pemDeveloperKeys());
}
@Override
public CloudTenant get() {
return new CloudTenant(name, billingInfo, pemDeveloperKeys);
}
public Cloud with(BillingInfo billingInfo) {
return new Cloud(name, billingInfo, pemDeveloperKeys);
}
public Cloud withoutPemDeveloperKey(String pemKey) {
ImmutableBiMap.Builder<String, Principal> keys = ImmutableBiMap.builder();
pemDeveloperKeys.forEach((key, user) -> {
if ( ! key.equals(pemKey))
keys.put(key, user);
});
return new Cloud(name, billingInfo, keys.build());
}
} | class Cloud extends LockedTenant {
private final BillingInfo billingInfo;
private final BiMap<String, Principal> pemDeveloperKeys;
private Cloud(TenantName name, BillingInfo billingInfo, BiMap<String, Principal> pemDeveloperKeys) {
super(name);
this.billingInfo = billingInfo;
this.pemDeveloperKeys = pemDeveloperKeys;
}
private Cloud(CloudTenant tenant) {
this(tenant.name(), tenant.billingInfo(), tenant.pemDeveloperKeys());
}
@Override
public CloudTenant get() {
return new CloudTenant(name, billingInfo, pemDeveloperKeys);
}
public Cloud with(BillingInfo billingInfo) {
return new Cloud(name, billingInfo, pemDeveloperKeys);
}
public Cloud withoutPemDeveloperKey(String pemKey) {
ImmutableBiMap.Builder<String, Principal> keys = ImmutableBiMap.builder();
pemDeveloperKeys.forEach((key, user) -> {
if ( ! key.equals(pemKey))
keys.put(key, user);
});
return new Cloud(name, billingInfo, keys.build());
}
} |
I think this can be removed now (dependency of now removed `Zone`). | private static String servicesXml() {
return "<container version='1.0'>\n" +
" <config name=\"container.handler.threadpool\">\n" +
" <maxthreads>10</maxthreads>\n" +
" </config>\n" +
"<config name='vespa.hosted.athenz.instanceproviderservice.config.athenz-provider-service'>\n" +
" <athenzCaTrustStore>/path/to/file</athenzCaTrustStore>\n" +
" <domain>vespa.external</domain>\n" +
" <serviceName>servicename</serviceName>\n" +
" <secretName>secretname</secretName>\n" +
" <secretVersion>0</secretVersion>\n" +
" <certDnsSuffix>suffix</certDnsSuffix>\n" +
" <ztsUrl>https:
" " +
"</config>\n" +
"<component id='com.yahoo.vespa.hosted.provision.testutils.MockNodeFlavors'/>\n" +
" <component id='com.yahoo.vespa.hosted.ca.restapi.mock.SecretStoreMock'/>\n" +
" <handler id='com.yahoo.vespa.hosted.ca.restapi.CertificateAuthorityApiHandler'>\n" +
" <binding>http:
" </handler>\n" +
" <http>\n" +
" <server id='default' port='12345'/>\n" +
" </http>\n" +
"</container>";
} | "<component id='com.yahoo.vespa.hosted.provision.testutils.MockNodeFlavors'/>\n" + | private static String servicesXml() {
return "<container version='1.0'>\n" +
" <config name=\"container.handler.threadpool\">\n" +
" <maxthreads>10</maxthreads>\n" +
" </config>\n" +
" <config name='vespa.hosted.athenz.instanceproviderservice.config.athenz-provider-service'>\n" +
" <athenzCaTrustStore>/path/to/file</athenzCaTrustStore>\n" +
" <domain>vespa.external</domain>\n" +
" <serviceName>servicename</serviceName>\n" +
" <secretName>secretname</secretName>\n" +
" <secretVersion>0</secretVersion>\n" +
" <certDnsSuffix>suffix</certDnsSuffix>\n" +
" <ztsUrl>https:
" </config>\n" +
" <component id='com.yahoo.vespa.hosted.ca.restapi.mock.SecretStoreMock'/>\n" +
" <handler id='com.yahoo.vespa.hosted.ca.restapi.CertificateAuthorityApiHandler'>\n" +
" <binding>http:
" </handler>\n" +
" <http>\n" +
" <server id='default' port='12345'/>\n" +
" </http>\n" +
"</container>";
} | class ContainerTester {
private JDisc container;
@Before
public void startContainer() {
container = JDisc.fromServicesXml(servicesXml(), Networking.enable);
}
@After
public void stopContainer() {
container.close();
}
public SecretStoreMock secretStore() {
return (SecretStoreMock) container.components().getComponent(SecretStoreMock.class.getName());
}
public void assertResponse(int expectedStatus, String expectedBody, Request request) {
assertResponse(expectedStatus, (body) -> assertEquals(expectedBody, body), request);
}
public void assertResponse(int expectedStatus, Consumer<String> bodyAsserter, Request request) {
var response = container.handleRequest(request);
try {
bodyAsserter.accept(response.getBodyAsString());
} catch (CharacterCodingException e) {
throw new UncheckedIOException(e);
}
assertEquals(expectedStatus, response.getStatus());
assertEquals("application/json; charset=UTF-8", response.getHeaders().getFirst("Content-Type"));
}
} | class ContainerTester {
private JDisc container;
@Before
public void startContainer() {
container = JDisc.fromServicesXml(servicesXml(), Networking.enable);
}
@After
public void stopContainer() {
container.close();
}
public SecretStoreMock secretStore() {
return (SecretStoreMock) container.components().getComponent(SecretStoreMock.class.getName());
}
public void assertResponse(int expectedStatus, String expectedBody, Request request) {
assertResponse(expectedStatus, (body) -> assertEquals(expectedBody, body), request);
}
public void assertResponse(int expectedStatus, Consumer<String> bodyAsserter, Request request) {
var response = container.handleRequest(request);
try {
bodyAsserter.accept(response.getBodyAsString());
} catch (CharacterCodingException e) {
throw new UncheckedIOException(e);
}
assertEquals(expectedStatus, response.getStatus());
assertEquals("application/json; charset=UTF-8", response.getHeaders().getFirst("Content-Type"));
}
} |
Still needed? | private VespaVersion vespaVersionFromSlime(Inspector object) {
return new VespaVersion(deploymentStatisticsFromSlime(object.field(deploymentStatisticsField)),
object.field(releaseCommitField).asString(),
Instant.ofEpochMilli(object.field(committedAtField).asLong()),
object.field(isControllerVersionField).asBool(),
object.field(isSystemVersionField).asBool(),
!object.field(isReleasedField).valid() || object.field(isReleasedField).asBool(),
nodeVersionsFromSlime(object),
VespaVersion.Confidence.valueOf(object.field(confidenceField).asString())
);
} | !object.field(isReleasedField).valid() || object.field(isReleasedField).asBool(), | private VespaVersion vespaVersionFromSlime(Inspector object) {
var deploymentStatistics = deploymentStatisticsFromSlime(object.field(deploymentStatisticsField));
return new VespaVersion(deploymentStatistics,
object.field(releaseCommitField).asString(),
Instant.ofEpochMilli(object.field(committedAtField).asLong()),
object.field(isControllerVersionField).asBool(),
object.field(isSystemVersionField).asBool(),
object.field(isReleasedField).asBool(),
nodeVersionsFromSlime(object, deploymentStatistics.version()),
VespaVersion.Confidence.valueOf(object.field(confidenceField).asString())
);
} | class VersionStatusSerializer {
private static final String versionsField = "versions";
private static final String releaseCommitField = "releaseCommit";
private static final String committedAtField = "releasedAt";
private static final String isControllerVersionField = "isCurrentControllerVersion";
private static final String isSystemVersionField = "isCurrentSystemVersion";
private static final String isReleasedField = "isReleased";
private static final String deploymentStatisticsField = "deploymentStatistics";
private static final String confidenceField = "confidence";
private static final String configServersField = "configServerHostnames";
private static final String nodeVersionsField = "nodeVersions";
private static final String hostnameField = "hostname";
private static final String changedAtField = "changedAt";
private static final String versionField = "version";
private static final String failingField = "failing";
private static final String productionField = "production";
private static final String deployingField = "deploying";
public Slime toSlime(VersionStatus status) {
Slime slime = new Slime();
Cursor root = slime.setObject();
versionsToSlime(status.versions(), root.setArray(versionsField));
return slime;
}
public VersionStatus fromSlime(Slime slime) {
Inspector root = slime.get();
return new VersionStatus(vespaVersionsFromSlime(root.field(versionsField)));
}
private void versionsToSlime(List<VespaVersion> versions, Cursor array) {
versions.forEach(version -> vespaVersionToSlime(version, array.addObject()));
}
private void vespaVersionToSlime(VespaVersion version, Cursor object) {
object.setString(releaseCommitField, version.releaseCommit());
object.setLong(committedAtField, version.committedAt().toEpochMilli());
object.setBool(isControllerVersionField, version.isControllerVersion());
object.setBool(isSystemVersionField, version.isSystemVersion());
object.setBool(isReleasedField, version.isReleased());
deploymentStatisticsToSlime(version.statistics(), object.setObject(deploymentStatisticsField));
object.setString(confidenceField, version.confidence().name());
configServersToSlime(version.nodeVersions().hostnames(), object.setArray(configServersField));
nodeVersionsToSlime(version.nodeVersions(), object.setArray(nodeVersionsField));
}
private void nodeVersionsToSlime(NodeVersions nodeVersions, Cursor array) {
for (NodeVersion nodeVersion : nodeVersions.asMap().values()) {
var nodeVersionObject = array.addObject();
nodeVersionObject.setString(hostnameField, nodeVersion.hostname().value());
nodeVersionObject.setString(versionField, nodeVersion.version().toFullString());
nodeVersionObject.setLong(changedAtField, nodeVersion.changedAt().toEpochMilli());
}
}
private void configServersToSlime(Set<HostName> configServerHostnames, Cursor array) {
configServerHostnames.stream().map(HostName::value).forEach(array::addString);
}
private void deploymentStatisticsToSlime(DeploymentStatistics statistics, Cursor object) {
object.setString(versionField, statistics.version().toString());
applicationsToSlime(statistics.failing(), object.setArray(failingField));
applicationsToSlime(statistics.production(), object.setArray(productionField));
applicationsToSlime(statistics.deploying(), object.setArray(deployingField));
}
private void applicationsToSlime(Collection<ApplicationId> applications, Cursor array) {
applications.forEach(application -> array.addString(application.serializedForm()));
}
private List<VespaVersion> vespaVersionsFromSlime(Inspector array) {
List<VespaVersion> versions = new ArrayList<>();
array.traverse((ArrayTraverser) (i, object) -> versions.add(vespaVersionFromSlime(object)));
return Collections.unmodifiableList(versions);
}
private NodeVersions nodeVersionsFromSlime(Inspector root) {
var nodeVersions = new LinkedHashMap<HostName, NodeVersion>();
var nodeVersionsRoot = root.field(nodeVersionsField);
if (nodeVersionsRoot.valid()) {
nodeVersionsRoot.traverse((ArrayTraverser) (i, entry) -> {
var hostname = HostName.from(entry.field(hostnameField).asString());
var version = Version.fromString(entry.field(versionField).asString());
var changedAt = Instant.ofEpochMilli(entry.field(changedAtField).asLong());
nodeVersions.put(hostname, new NodeVersion(hostname, version, changedAt));
});
} else {
var configServerHostnames = configServersFromSlime(root.field(configServersField));
for (var hostname : configServerHostnames) {
nodeVersions.put(hostname, NodeVersion.empty(hostname));
}
}
return new NodeVersions(nodeVersions);
}
private Set<HostName> configServersFromSlime(Inspector array) {
Set<HostName> configServerHostnames = new LinkedHashSet<>();
array.traverse((ArrayTraverser) (i, entry) -> configServerHostnames.add(HostName.from(entry.asString())));
return Collections.unmodifiableSet(configServerHostnames);
}
private DeploymentStatistics deploymentStatisticsFromSlime(Inspector object) {
return new DeploymentStatistics(Version.fromString(object.field(versionField).asString()),
applicationsFromSlime(object.field(failingField)),
applicationsFromSlime(object.field(productionField)),
applicationsFromSlime(object.field(deployingField)));
}
private List<ApplicationId> applicationsFromSlime(Inspector array) {
List<ApplicationId> applications = new ArrayList<>();
array.traverse((ArrayTraverser) (i, entry) -> applications.add(
ApplicationId.fromSerializedForm(entry.asString()))
);
return Collections.unmodifiableList(applications);
}
} | class VersionStatusSerializer {
private static final String versionsField = "versions";
private static final String releaseCommitField = "releaseCommit";
private static final String committedAtField = "releasedAt";
private static final String isControllerVersionField = "isCurrentControllerVersion";
private static final String isSystemVersionField = "isCurrentSystemVersion";
private static final String isReleasedField = "isReleased";
private static final String deploymentStatisticsField = "deploymentStatistics";
private static final String confidenceField = "confidence";
private static final String configServersField = "configServerHostnames";
private static final String nodeVersionsField = "nodeVersions";
private static final String hostnameField = "hostname";
private static final String wantedVersionField = "wantedVersion";
private static final String changedAtField = "changedAt";
private static final String versionField = "version";
private static final String failingField = "failing";
private static final String productionField = "production";
private static final String deployingField = "deploying";
public Slime toSlime(VersionStatus status) {
Slime slime = new Slime();
Cursor root = slime.setObject();
versionsToSlime(status.versions(), root.setArray(versionsField));
return slime;
}
public VersionStatus fromSlime(Slime slime) {
Inspector root = slime.get();
return new VersionStatus(vespaVersionsFromSlime(root.field(versionsField)));
}
private void versionsToSlime(List<VespaVersion> versions, Cursor array) {
versions.forEach(version -> vespaVersionToSlime(version, array.addObject()));
}
private void vespaVersionToSlime(VespaVersion version, Cursor object) {
object.setString(releaseCommitField, version.releaseCommit());
object.setLong(committedAtField, version.committedAt().toEpochMilli());
object.setBool(isControllerVersionField, version.isControllerVersion());
object.setBool(isSystemVersionField, version.isSystemVersion());
object.setBool(isReleasedField, version.isReleased());
deploymentStatisticsToSlime(version.statistics(), object.setObject(deploymentStatisticsField));
object.setString(confidenceField, version.confidence().name());
configServersToSlime(version.nodeVersions().hostnames(), object.setArray(configServersField));
nodeVersionsToSlime(version.nodeVersions(), object.setArray(nodeVersionsField));
}
private void nodeVersionsToSlime(NodeVersions nodeVersions, Cursor array) {
for (NodeVersion nodeVersion : nodeVersions.asMap().values()) {
var nodeVersionObject = array.addObject();
nodeVersionObject.setString(hostnameField, nodeVersion.hostname().value());
nodeVersionObject.setString(wantedVersionField, nodeVersion.wantedVersion().toFullString());
nodeVersionObject.setLong(changedAtField, nodeVersion.changedAt().toEpochMilli());
}
}
private void configServersToSlime(Set<HostName> configServerHostnames, Cursor array) {
configServerHostnames.stream().map(HostName::value).forEach(array::addString);
}
private void deploymentStatisticsToSlime(DeploymentStatistics statistics, Cursor object) {
object.setString(versionField, statistics.version().toString());
applicationsToSlime(statistics.failing(), object.setArray(failingField));
applicationsToSlime(statistics.production(), object.setArray(productionField));
applicationsToSlime(statistics.deploying(), object.setArray(deployingField));
}
private void applicationsToSlime(Collection<ApplicationId> applications, Cursor array) {
applications.forEach(application -> array.addString(application.serializedForm()));
}
private List<VespaVersion> vespaVersionsFromSlime(Inspector array) {
List<VespaVersion> versions = new ArrayList<>();
array.traverse((ArrayTraverser) (i, object) -> versions.add(vespaVersionFromSlime(object)));
return Collections.unmodifiableList(versions);
}
private NodeVersions nodeVersionsFromSlime(Inspector root, Version version) {
var nodeVersions = ImmutableMap.<HostName, NodeVersion>builder();
var nodeVersionsRoot = root.field(nodeVersionsField);
if (nodeVersionsRoot.valid()) {
nodeVersionsRoot.traverse((ArrayTraverser) (i, entry) -> {
var hostname = HostName.from(entry.field(hostnameField).asString());
var wantedVersion = Version.fromString(entry.field(wantedVersionField).asString());
var changedAt = Instant.ofEpochMilli(entry.field(changedAtField).asLong());
nodeVersions.put(hostname, new NodeVersion(hostname, version, wantedVersion, changedAt));
});
} else {
var configServerHostnames = configServersFromSlime(root.field(configServersField));
for (var hostname : configServerHostnames) {
nodeVersions.put(hostname, NodeVersion.empty(hostname));
}
}
return new NodeVersions(nodeVersions.build());
}
private Set<HostName> configServersFromSlime(Inspector array) {
Set<HostName> configServerHostnames = new LinkedHashSet<>();
array.traverse((ArrayTraverser) (i, entry) -> configServerHostnames.add(HostName.from(entry.asString())));
return Collections.unmodifiableSet(configServerHostnames);
}
private DeploymentStatistics deploymentStatisticsFromSlime(Inspector object) {
return new DeploymentStatistics(Version.fromString(object.field(versionField).asString()),
applicationsFromSlime(object.field(failingField)),
applicationsFromSlime(object.field(productionField)),
applicationsFromSlime(object.field(deployingField)));
}
private List<ApplicationId> applicationsFromSlime(Inspector array) {
List<ApplicationId> applications = new ArrayList<>();
array.traverse((ArrayTraverser) (i, entry) -> applications.add(
ApplicationId.fromSerializedForm(entry.asString()))
);
return Collections.unmodifiableList(applications);
}
} |
```suggestion assertEquals(version1, tester.controller().systemVersion()); // Some time passes, and the upgrade scenario repeats tester.clock().advance(Duration.ofDays(1)); var version2 = Version.fromString("7.2"); tester.upgradeController(version2); reporter.maintain(); assertEquals(0, getNodesFailingUpgrade()); // Some time passes, but only a subset of nodes upgrade within timeout tester.clock().advance(Duration.ofMinutes(30)); tester.upgradeSystemApplications(version2, List.of(SystemApplication.configServerHost)); reporter.maintain(); assertEquals(0, getNodesFailingUpgrade()); tester.clock().advance(Duration.ofMinutes(30).plus(Duration.ofSeconds(1))); reporter.maintain(); assertEquals(48, getNodesFailingUpgrade()); // Some nodes are repaired and upgrade tester.upgradeSystemApplications(version2, List.of(SystemApplication.configServer)); reporter.maintain(); assertEquals(36, getNodesFailingUpgrade()); // All nodes are repaired and system upgrades tester.upgradeSystem(version2); reporter.maintain(); assertEquals(0, getNodesFailingUpgrade()); assertEquals(version2, tester.controller().systemVersion()); } ``` Next upgrade fails. | public void test_nodes_failing_system_upgrade() {
var tester = new DeploymentTester();
var reporter = createReporter(tester.controller());
var version0 = Version.fromString("7.0");
tester.upgradeSystem(version0);
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
var version1 = Version.fromString("7.1");
tester.upgradeController(version1);
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
tester.clock().advance(Duration.ofMinutes(30));
tester.upgradeSystemApplications(version1, List.of(SystemApplication.configServerHost));
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
tester.clock().advance(Duration.ofMinutes(30).plus(Duration.ofSeconds(1)));
reporter.maintain();
assertEquals(48, getNodesFailingUpgrade());
tester.upgradeSystemApplications(version1, List.of(SystemApplication.configServer));
reporter.maintain();
assertEquals(36, getNodesFailingUpgrade());
tester.upgradeSystem(version1);
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
} | } | public void test_nodes_failing_system_upgrade() {
var tester = new DeploymentTester();
var reporter = createReporter(tester.controller());
var zone1 = ZoneApiMock.fromId("prod.eu-west-1");
tester.controllerTester().zoneRegistry().setUpgradePolicy(UpgradePolicy.create().upgrade(zone1));
var systemUpgrader = new SystemUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.controllerTester().curator()));
tester.configServer().bootstrap(List.of(zone1.getId()), SystemApplication.configServer);
var version0 = Version.fromString("7.0");
tester.upgradeSystem(version0);
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
for (var version : List.of(Version.fromString("7.1"), Version.fromString("7.2"))) {
tester.upgradeController(version);
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
systemUpgrader.maintain();
tester.clock().advance(Duration.ofMinutes(30));
tester.computeVersionStatus();
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
tester.configServer().setVersion(SystemApplication.configServer.id(), zone1.getId(), version, 1);
tester.clock().advance(Duration.ofMinutes(30).plus(Duration.ofSeconds(1)));
tester.computeVersionStatus();
reporter.maintain();
assertEquals(2, getNodesFailingUpgrade());
tester.configServer().setVersion(SystemApplication.configServer.id(), zone1.getId(), version);
tester.computeVersionStatus();
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
assertEquals(version, tester.controller().systemVersion());
}
} | class MetricsReporterTest {
private final MetricsMock metrics = new MetricsMock();
@Test
public void test_deployment_fail_ratio() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter metricsReporter = createReporter(tester.controller());
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
Application app1 = tester.createApplication("app1", "tenant1", 1, 11L);
Application app2 = tester.createApplication("app2", "tenant1", 2, 22L);
Application app3 = tester.createApplication("app3", "tenant1", 3, 33L);
Application app4 = tester.createApplication("app4", "tenant1", 4, 44L);
tester.deployCompletely(app1, applicationPackage);
tester.deployCompletely(app2, applicationPackage);
tester.deployCompletely(app3, applicationPackage);
tester.deployCompletely(app4, applicationPackage);
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
tester.jobCompletion(component).application(app4).nextBuildNumber().uploadArtifact(applicationPackage).submit();
tester.deployAndNotify(app4.id().defaultInstance(), Optional.of(applicationPackage), false, systemTest);
metricsReporter.maintain();
assertEquals(25.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
}
@Test
public void test_deployment_average_duration() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application app = tester.createApplication("app1", "tenant1", 1, 11L);
tester.deployCompletely(app, applicationPackage);
reporter.maintain();
assertEquals(Duration.ZERO, getAverageDeploymentDuration(app.id().defaultInstance()));
tester.jobCompletion(component).application(app).nextBuildNumber().uploadArtifact(applicationPackage).submit();
tester.clock().advance(Duration.ofHours(1));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, systemTest);
tester.clock().advance(Duration.ofMinutes(30));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, stagingTest);
tester.clock().advance(Duration.ofMinutes(90));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, productionUsWest1);
reporter.maintain();
assertEquals(Duration.ofMinutes(80), getAverageDeploymentDuration(app.id().defaultInstance()));
tester.jobCompletion(component).application(app).nextBuildNumber(2).uploadArtifact(applicationPackage).submit();
tester.clock().advance(Duration.ofHours(12));
reporter.maintain();
assertEquals(Duration.ofHours(12)
.plus(Duration.ofHours(12))
.plus(Duration.ofMinutes(90))
.dividedBy(3),
getAverageDeploymentDuration(app.id().defaultInstance()));
}
@Test
public void test_deployments_failing_upgrade() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application app = tester.createApplication("app1", "tenant1", 1, 11L);
tester.deployCompletely(app, applicationPackage);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.jobCompletion(component).application(app).nextBuildNumber().uploadArtifact(applicationPackage).submit();
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, systemTest);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, systemTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, stagingTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, productionUsWest1);
assertFalse("Change deployed", tester.controller().applications().requireApplication(app.id()).change().hasTargets());
Version version = Version.fromString("7.1");
tester.upgradeSystem(version);
tester.upgrader().maintain();
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, systemTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, stagingTest);
reporter.maintain();
assertEquals(2, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, systemTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, stagingTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, productionUsWest1);
reporter.maintain();
assertEquals(1, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, productionUsWest1);
assertFalse("Upgrade deployed", tester.controller().applications().requireApplication(app.id()).change().hasTargets());
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
}
@Test
public void test_deployment_warnings_metric() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application application = tester.createApplication("app1", "tenant1", 1, 11L);
tester.configServer().generateWarnings(new DeploymentId(application.id().defaultInstance(), ZoneId.from("prod", "us-west-1")), 3);
tester.configServer().generateWarnings(new DeploymentId(application.id().defaultInstance(), ZoneId.from("prod", "us-east-3")), 4);
tester.deployCompletely(application, applicationPackage);
reporter.maintain();
assertEquals(4, getDeploymentWarnings(application.id().defaultInstance()));
}
@Test
public void test_build_time_reporting() {
InternalDeploymentTester tester = new InternalDeploymentTester();
ApplicationVersion version = tester.deployNewSubmission();
assertEquals(1000, version.buildTime().get().toEpochMilli());
MetricsReporter reporter = createReporter(tester.tester().controller());
reporter.maintain();
assertEquals(tester.clock().instant().getEpochSecond() - 1,
getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, tester.instance().id()));
}
@Test
public void test_name_service_queue_size_metric() {
DeploymentTester tester = new DeploymentTester(new ControllerTester(), false);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("default")
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application application = tester.createApplication("app1", "tenant1", 1, 11L);
reporter.maintain();
assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
tester.deployCompletely(application, applicationPackage);
reporter.maintain();
assertEquals("Deployment queues name services requests", 6, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
tester.flushDnsRequests();
reporter.maintain();
assertEquals("Queue consumed", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
}
@Test
private Duration getAverageDeploymentDuration(ApplicationId id) {
return Duration.ofSeconds(getMetric(MetricsReporter.DEPLOYMENT_AVERAGE_DURATION, id).longValue());
}
private int getDeploymentsFailingUpgrade(ApplicationId id) {
return getMetric(MetricsReporter.DEPLOYMENT_FAILING_UPGRADES, id).intValue();
}
private int getDeploymentWarnings(ApplicationId id) {
return getMetric(MetricsReporter.DEPLOYMENT_WARNINGS, id).intValue();
}
private int getNodesFailingUpgrade() {
return metrics.getMetric(MetricsReporter.NODES_FAILING_SYSTEM_UPGRADE).intValue();
}
private Number getMetric(String name, ApplicationId id) {
return metrics.getMetric((dimensions) -> id.tenant().value().equals(dimensions.get("tenant")) &&
appDimension(id).equals(dimensions.get("app")),
name)
.orElseThrow(() -> new RuntimeException("Expected metric to exist for " + id));
}
private MetricsReporter createReporter(Controller controller) {
return new MetricsReporter(controller, metrics, new JobControl(new MockCuratorDb()));
}
private static String appDimension(ApplicationId id) {
return id.application().value() + "." + id.instance().value();
}
} | class MetricsReporterTest {
private final MetricsMock metrics = new MetricsMock();
@Test
public void test_deployment_fail_ratio() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter metricsReporter = createReporter(tester.controller());
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
Application app1 = tester.createApplication("app1", "tenant1", 1, 11L);
Application app2 = tester.createApplication("app2", "tenant1", 2, 22L);
Application app3 = tester.createApplication("app3", "tenant1", 3, 33L);
Application app4 = tester.createApplication("app4", "tenant1", 4, 44L);
tester.deployCompletely(app1, applicationPackage);
tester.deployCompletely(app2, applicationPackage);
tester.deployCompletely(app3, applicationPackage);
tester.deployCompletely(app4, applicationPackage);
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
tester.jobCompletion(component).application(app4).nextBuildNumber().uploadArtifact(applicationPackage).submit();
tester.deployAndNotify(app4.id().defaultInstance(), Optional.of(applicationPackage), false, systemTest);
metricsReporter.maintain();
assertEquals(25.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
}
@Test
public void test_deployment_average_duration() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application app = tester.createApplication("app1", "tenant1", 1, 11L);
tester.deployCompletely(app, applicationPackage);
reporter.maintain();
assertEquals(Duration.ZERO, getAverageDeploymentDuration(app.id().defaultInstance()));
tester.jobCompletion(component).application(app).nextBuildNumber().uploadArtifact(applicationPackage).submit();
tester.clock().advance(Duration.ofHours(1));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, systemTest);
tester.clock().advance(Duration.ofMinutes(30));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, stagingTest);
tester.clock().advance(Duration.ofMinutes(90));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, productionUsWest1);
reporter.maintain();
assertEquals(Duration.ofMinutes(80), getAverageDeploymentDuration(app.id().defaultInstance()));
tester.jobCompletion(component).application(app).nextBuildNumber(2).uploadArtifact(applicationPackage).submit();
tester.clock().advance(Duration.ofHours(12));
reporter.maintain();
assertEquals(Duration.ofHours(12)
.plus(Duration.ofHours(12))
.plus(Duration.ofMinutes(90))
.dividedBy(3),
getAverageDeploymentDuration(app.id().defaultInstance()));
}
@Test
public void test_deployments_failing_upgrade() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application app = tester.createApplication("app1", "tenant1", 1, 11L);
tester.deployCompletely(app, applicationPackage);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.jobCompletion(component).application(app).nextBuildNumber().uploadArtifact(applicationPackage).submit();
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, systemTest);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, systemTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, stagingTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, productionUsWest1);
assertFalse("Change deployed", tester.controller().applications().requireApplication(app.id()).change().hasTargets());
Version version = Version.fromString("7.1");
tester.upgradeSystem(version);
tester.upgrader().maintain();
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, systemTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, stagingTest);
reporter.maintain();
assertEquals(2, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, systemTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, stagingTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, productionUsWest1);
reporter.maintain();
assertEquals(1, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, productionUsWest1);
assertFalse("Upgrade deployed", tester.controller().applications().requireApplication(app.id()).change().hasTargets());
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
}
@Test
public void test_deployment_warnings_metric() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application application = tester.createApplication("app1", "tenant1", 1, 11L);
tester.configServer().generateWarnings(new DeploymentId(application.id().defaultInstance(), ZoneId.from("prod", "us-west-1")), 3);
tester.configServer().generateWarnings(new DeploymentId(application.id().defaultInstance(), ZoneId.from("prod", "us-east-3")), 4);
tester.deployCompletely(application, applicationPackage);
reporter.maintain();
assertEquals(4, getDeploymentWarnings(application.id().defaultInstance()));
}
@Test
public void test_build_time_reporting() {
InternalDeploymentTester tester = new InternalDeploymentTester();
ApplicationVersion version = tester.deployNewSubmission();
assertEquals(1000, version.buildTime().get().toEpochMilli());
MetricsReporter reporter = createReporter(tester.tester().controller());
reporter.maintain();
assertEquals(tester.clock().instant().getEpochSecond() - 1,
getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, tester.instance().id()));
}
@Test
public void test_name_service_queue_size_metric() {
DeploymentTester tester = new DeploymentTester(new ControllerTester(), false);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("default")
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application application = tester.createApplication("app1", "tenant1", 1, 11L);
reporter.maintain();
assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
tester.deployCompletely(application, applicationPackage);
reporter.maintain();
assertEquals("Deployment queues name services requests", 6, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
tester.flushDnsRequests();
reporter.maintain();
assertEquals("Queue consumed", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
}
@Test
private Duration getAverageDeploymentDuration(ApplicationId id) {
return Duration.ofSeconds(getMetric(MetricsReporter.DEPLOYMENT_AVERAGE_DURATION, id).longValue());
}
private int getDeploymentsFailingUpgrade(ApplicationId id) {
return getMetric(MetricsReporter.DEPLOYMENT_FAILING_UPGRADES, id).intValue();
}
private int getDeploymentWarnings(ApplicationId id) {
return getMetric(MetricsReporter.DEPLOYMENT_WARNINGS, id).intValue();
}
private int getNodesFailingUpgrade() {
return metrics.getMetric(MetricsReporter.NODES_FAILING_SYSTEM_UPGRADE).intValue();
}
private Number getMetric(String name, ApplicationId id) {
return metrics.getMetric((dimensions) -> id.tenant().value().equals(dimensions.get("tenant")) &&
appDimension(id).equals(dimensions.get("app")),
name)
.orElseThrow(() -> new RuntimeException("Expected metric to exist for " + id));
}
private MetricsReporter createReporter(Controller controller) {
return new MetricsReporter(controller, metrics, new JobControl(new MockCuratorDb()));
}
private static String appDimension(ApplicationId id) {
return id.application().value() + "." + id.instance().value();
}
} |
Probably not an issue, but this makes runtime scale with the square of the number of nodes which have upgraded. Just storing the full `NodeVersion` object instead of the `hostnames`, and then creating the `NodeVersion` at the end, is a cheaper alternative. | private static NodeVersions findSystemApplicationVersions(Controller controller) {
var nodeVersions = controller.versionStatus().systemVersion()
.map(VespaVersion::nodeVersions)
.orElse(NodeVersions.EMPTY);
var hostnames = new HashSet<HostName>();
for (var zone : controller.zoneRegistry().zones().controllerUpgraded().zones()) {
for (var application : SystemApplication.all()) {
var nodes = controller.serviceRegistry().configServer().nodeRepository()
.list(zone.getId(), application.id()).stream()
.filter(SystemUpgrader::eligibleForUpgrade)
.collect(Collectors.toList());
if (nodes.isEmpty()) continue;
var configConverged = application.configConvergedIn(zone.getId(), controller, Optional.empty());
if (!configConverged) {
log.log(LogLevel.WARNING, "Config for " + application.id() + " in " + zone.getId() +
" has not converged");
}
var now = controller.clock().instant();
for (var node : nodes) {
Version version = configConverged ? node.currentVersion() : controller.systemVersion();
nodeVersions = nodeVersions.with(new NodeVersion(node.hostname(), version, now));
hostnames.add(node.hostname());
}
}
}
return nodeVersions.retainAll(hostnames);
} | nodeVersions = nodeVersions.with(new NodeVersion(node.hostname(), version, now)); | private static NodeVersions findSystemApplicationVersions(Controller controller) {
var nodeVersions = controller.versionStatus().systemVersion()
.map(VespaVersion::nodeVersions)
.orElse(NodeVersions.EMPTY);
var newNodeVersions = new ArrayList<NodeVersion>();
for (var zone : controller.zoneRegistry().zones().controllerUpgraded().zones()) {
for (var application : SystemApplication.all()) {
var nodes = controller.serviceRegistry().configServer().nodeRepository()
.list(zone.getId(), application.id()).stream()
.filter(SystemUpgrader::eligibleForUpgrade)
.collect(Collectors.toList());
if (nodes.isEmpty()) continue;
var configConverged = application.configConvergedIn(zone.getId(), controller, Optional.empty());
if (!configConverged) {
log.log(LogLevel.WARNING, "Config for " + application.id() + " in " + zone.getId() +
" has not converged");
}
var now = controller.clock().instant();
for (var node : nodes) {
Version version = configConverged ? node.currentVersion() : controller.systemVersion();
newNodeVersions.add(new NodeVersion(node.hostname(), version, node.wantedVersion(), now));
}
}
}
return nodeVersions.with(newNodeVersions);
} | class VersionStatus {
private static final Logger log = Logger.getLogger(VersionStatus.class.getName());
private final ImmutableList<VespaVersion> versions;
/** Create a version status. DO NOT USE: Public for testing and serialization only */
public VersionStatus(List<VespaVersion> versions) {
this.versions = ImmutableList.copyOf(versions);
}
/** Returns the current version of controllers in this system */
public Optional<VespaVersion> controllerVersion() {
return versions().stream().filter(VespaVersion::isControllerVersion).findFirst();
}
/**
* Returns the current Vespa version of the system controlled by this,
* or empty if we have not currently determined what the system version is in this status.
*/
public Optional<VespaVersion> systemVersion() {
return versions().stream().filter(VespaVersion::isSystemVersion).findFirst();
}
/** Returns whether the system is currently upgrading */
public boolean isUpgrading() {
return systemVersion().map(VespaVersion::versionNumber).orElse(Version.emptyVersion)
.isBefore(controllerVersion().map(VespaVersion::versionNumber)
.orElse(Version.emptyVersion));
}
/**
* Lists all currently active Vespa versions, with deployment statistics,
* sorted from lowest to highest version number.
* The returned list is immutable.
* Calling this is free, but the returned status is slightly out of date.
*/
public List<VespaVersion> versions() { return versions; }
/** Returns the given version, or null if it is not present */
public VespaVersion version(Version version) {
return versions.stream().filter(v -> v.versionNumber().equals(version)).findFirst().orElse(null);
}
/** Create the empty version status */
public static VersionStatus empty() { return new VersionStatus(ImmutableList.of()); }
/** Create a full, updated version status. This is expensive and should be done infrequently */
public static VersionStatus compute(Controller controller) {
var systemApplicationVersions = findSystemApplicationVersions(controller);
var controllerVersions = findControllerVersions(controller);
var infrastructureVersions = ArrayListMultimap.<Version, HostName>create();
for (var kv : controllerVersions.asMap().entrySet()) {
infrastructureVersions.putAll(kv.getKey().version(), kv.getValue());
}
infrastructureVersions.putAll(systemApplicationVersions.asVersionMap());
ControllerVersion controllerVersion = controllerVersions.keySet().stream()
.min(Comparator.naturalOrder())
.get();
Version newSystemVersion = infrastructureVersions.keySet().stream().min(Comparator.naturalOrder()).get();
Version systemVersion = controller.versionStatus().systemVersion()
.map(VespaVersion::versionNumber)
.orElse(newSystemVersion);
if (newSystemVersion.isBefore(systemVersion)) {
log.warning("Refusing to lower system version from " +
controller.systemVersion() +
" to " +
newSystemVersion +
", nodes on " + newSystemVersion + ": " +
infrastructureVersions.get(newSystemVersion).stream()
.map(HostName::value)
.collect(Collectors.joining(", ")));
} else {
systemVersion = newSystemVersion;
}
Collection<DeploymentStatistics> deploymentStatistics = computeDeploymentStatistics(infrastructureVersions.keySet(),
controller.applications().asList());
List<VespaVersion> versions = new ArrayList<>();
List<Version> releasedVersions = controller.mavenRepository().metadata().versions();
for (DeploymentStatistics statistics : deploymentStatistics) {
if (statistics.version().isEmpty()) continue;
try {
boolean isReleased = Collections.binarySearch(releasedVersions, statistics.version()) >= 0;
VespaVersion vespaVersion = createVersion(statistics,
controllerVersion,
systemVersion,
isReleased,
systemApplicationVersions.matching(statistics.version()),
controller);
versions.add(vespaVersion);
} catch (IllegalArgumentException e) {
log.log(Level.WARNING, "Unable to create VespaVersion for version " +
statistics.version().toFullString(), e);
}
}
Collections.sort(versions);
return new VersionStatus(versions);
}
private static ListMultimap<ControllerVersion, HostName> findControllerVersions(Controller controller) {
ListMultimap<ControllerVersion, HostName> versions = ArrayListMultimap.create();
if (controller.curator().cluster().isEmpty()) {
versions.put(ControllerVersion.CURRENT, controller.hostname());
} else {
for (HostName hostname : controller.curator().cluster()) {
versions.put(controller.curator().readControllerVersion(hostname), hostname);
}
}
return versions;
}
private static Collection<DeploymentStatistics> computeDeploymentStatistics(Set<Version> infrastructureVersions,
List<Application> instances) {
Map<Version, DeploymentStatistics> versionMap = new HashMap<>();
for (Version infrastructureVersion : infrastructureVersions) {
versionMap.put(infrastructureVersion, DeploymentStatistics.empty(infrastructureVersion));
}
for (Application application : ApplicationList.from(instances).withProductionDeployment().asList())
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.productionDeployments().values()) {
versionMap.computeIfAbsent(deployment.version(), DeploymentStatistics::empty);
}
JobList.from(instance)
.failing()
.not().failingApplicationChange()
.not().failingBecause(outOfCapacity)
.mapToList(job -> job.lastCompleted().get().platform())
.forEach(version -> versionMap
.put(version, versionMap.getOrDefault(version, DeploymentStatistics.empty(version))
.withFailing(instance.id())));
JobList.from(instance)
.lastSuccess().present()
.production()
.mapToList(job -> job.lastSuccess().get().platform())
.forEach(version -> versionMap
.put(version, versionMap.getOrDefault(version, DeploymentStatistics.empty(version))
.withProduction(instance.id())));
JobList.from(instance)
.upgrading()
.mapToList(job -> job.lastTriggered().get().platform())
.forEach(version -> versionMap
.put(version, versionMap.getOrDefault(version, DeploymentStatistics.empty(version))
.withDeploying(instance.id())));
}
return versionMap.values();
}
private static VespaVersion createVersion(DeploymentStatistics statistics,
ControllerVersion controllerVersion,
Version systemVersion,
boolean isReleased,
NodeVersions nodeVersions,
Controller controller) {
var isSystemVersion = statistics.version().equals(systemVersion);
var isControllerVersion = statistics.version().equals(controllerVersion.version());
var confidence = controller.curator().readConfidenceOverrides().get(statistics.version());
var confidenceIsOverridden = confidence != null;
var previousStatus = controller.versionStatus().version(statistics.version());
if (!confidenceIsOverridden) {
if (isSystemVersion || isControllerVersion) {
confidence = VespaVersion.confidenceFrom(statistics, controller);
} else {
confidence = getOrUpdateConfidence(statistics, controller);
}
}
var commitSha = controllerVersion.commitSha();
var commitDate = controllerVersion.commitDate();
if (previousStatus != null) {
commitSha = previousStatus.releaseCommit();
commitDate = previousStatus.committedAt();
if (!confidenceIsOverridden &&
!previousStatus.confidence().canChangeTo(confidence, controller.clock().instant())) {
confidence = previousStatus.confidence();
}
}
return new VespaVersion(statistics,
commitSha,
commitDate,
isControllerVersion,
isSystemVersion,
isReleased,
nodeVersions,
confidence);
}
/**
* Calculate confidence from given deployment statistics.
*
* @return previously calculated confidence for this version. If none exists, a new confidence will be calculated.
*/
private static VespaVersion.Confidence getOrUpdateConfidence(DeploymentStatistics statistics, Controller controller) {
return controller.versionStatus().versions().stream()
.filter(v -> statistics.version().equals(v.versionNumber()))
.map(VespaVersion::confidence)
.findFirst()
.orElseGet(() -> VespaVersion.confidenceFrom(statistics, controller));
}
} | class VersionStatus {
private static final Logger log = Logger.getLogger(VersionStatus.class.getName());
private final ImmutableList<VespaVersion> versions;
/** Create a version status. DO NOT USE: Public for testing and serialization only */
public VersionStatus(List<VespaVersion> versions) {
this.versions = ImmutableList.copyOf(versions);
}
/** Returns the current version of controllers in this system */
public Optional<VespaVersion> controllerVersion() {
return versions().stream().filter(VespaVersion::isControllerVersion).findFirst();
}
/**
* Returns the current Vespa version of the system controlled by this,
* or empty if we have not currently determined what the system version is in this status.
*/
public Optional<VespaVersion> systemVersion() {
return versions().stream().filter(VespaVersion::isSystemVersion).findFirst();
}
/** Returns whether the system is currently upgrading */
public boolean isUpgrading() {
return systemVersion().map(VespaVersion::versionNumber).orElse(Version.emptyVersion)
.isBefore(controllerVersion().map(VespaVersion::versionNumber)
.orElse(Version.emptyVersion));
}
/**
* Lists all currently active Vespa versions, with deployment statistics,
* sorted from lowest to highest version number.
* The returned list is immutable.
* Calling this is free, but the returned status is slightly out of date.
*/
public List<VespaVersion> versions() { return versions; }
/** Returns the given version, or null if it is not present */
public VespaVersion version(Version version) {
return versions.stream().filter(v -> v.versionNumber().equals(version)).findFirst().orElse(null);
}
/** Create the empty version status */
public static VersionStatus empty() { return new VersionStatus(ImmutableList.of()); }
/** Create a full, updated version status. This is expensive and should be done infrequently */
public static VersionStatus compute(Controller controller) {
var systemApplicationVersions = findSystemApplicationVersions(controller);
var controllerVersions = findControllerVersions(controller);
var infrastructureVersions = ArrayListMultimap.<Version, HostName>create();
for (var kv : controllerVersions.asMap().entrySet()) {
infrastructureVersions.putAll(kv.getKey().version(), kv.getValue());
}
infrastructureVersions.putAll(systemApplicationVersions.asVersionMap());
ControllerVersion controllerVersion = controllerVersions.keySet().stream()
.min(Comparator.naturalOrder())
.get();
Version newSystemVersion = infrastructureVersions.keySet().stream().min(Comparator.naturalOrder()).get();
Version systemVersion = controller.versionStatus().systemVersion()
.map(VespaVersion::versionNumber)
.orElse(newSystemVersion);
if (newSystemVersion.isBefore(systemVersion)) {
log.warning("Refusing to lower system version from " +
controller.systemVersion() +
" to " +
newSystemVersion +
", nodes on " + newSystemVersion + ": " +
infrastructureVersions.get(newSystemVersion).stream()
.map(HostName::value)
.collect(Collectors.joining(", ")));
} else {
systemVersion = newSystemVersion;
}
Collection<DeploymentStatistics> deploymentStatistics = computeDeploymentStatistics(infrastructureVersions.keySet(),
controller.applications().asList());
List<VespaVersion> versions = new ArrayList<>();
List<Version> releasedVersions = controller.mavenRepository().metadata().versions();
for (DeploymentStatistics statistics : deploymentStatistics) {
if (statistics.version().isEmpty()) continue;
try {
boolean isReleased = Collections.binarySearch(releasedVersions, statistics.version()) >= 0;
VespaVersion vespaVersion = createVersion(statistics,
controllerVersion,
systemVersion,
isReleased,
systemApplicationVersions.matching(statistics.version()),
controller);
versions.add(vespaVersion);
} catch (IllegalArgumentException e) {
log.log(Level.WARNING, "Unable to create VespaVersion for version " +
statistics.version().toFullString(), e);
}
}
Collections.sort(versions);
return new VersionStatus(versions);
}
private static ListMultimap<ControllerVersion, HostName> findControllerVersions(Controller controller) {
ListMultimap<ControllerVersion, HostName> versions = ArrayListMultimap.create();
if (controller.curator().cluster().isEmpty()) {
versions.put(ControllerVersion.CURRENT, controller.hostname());
} else {
for (HostName hostname : controller.curator().cluster()) {
versions.put(controller.curator().readControllerVersion(hostname), hostname);
}
}
return versions;
}
private static Collection<DeploymentStatistics> computeDeploymentStatistics(Set<Version> infrastructureVersions,
List<Application> instances) {
Map<Version, DeploymentStatistics> versionMap = new HashMap<>();
for (Version infrastructureVersion : infrastructureVersions) {
versionMap.put(infrastructureVersion, DeploymentStatistics.empty(infrastructureVersion));
}
for (Application application : ApplicationList.from(instances).withProductionDeployment().asList())
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.productionDeployments().values()) {
versionMap.computeIfAbsent(deployment.version(), DeploymentStatistics::empty);
}
JobList.from(instance)
.failing()
.not().failingApplicationChange()
.not().failingBecause(outOfCapacity)
.mapToList(job -> job.lastCompleted().get().platform())
.forEach(version -> versionMap
.put(version, versionMap.getOrDefault(version, DeploymentStatistics.empty(version))
.withFailing(instance.id())));
JobList.from(instance)
.lastSuccess().present()
.production()
.mapToList(job -> job.lastSuccess().get().platform())
.forEach(version -> versionMap
.put(version, versionMap.getOrDefault(version, DeploymentStatistics.empty(version))
.withProduction(instance.id())));
JobList.from(instance)
.upgrading()
.mapToList(job -> job.lastTriggered().get().platform())
.forEach(version -> versionMap
.put(version, versionMap.getOrDefault(version, DeploymentStatistics.empty(version))
.withDeploying(instance.id())));
}
return versionMap.values();
}
private static VespaVersion createVersion(DeploymentStatistics statistics,
ControllerVersion controllerVersion,
Version systemVersion,
boolean isReleased,
NodeVersions nodeVersions,
Controller controller) {
var isSystemVersion = statistics.version().equals(systemVersion);
var isControllerVersion = statistics.version().equals(controllerVersion.version());
var confidence = controller.curator().readConfidenceOverrides().get(statistics.version());
var confidenceIsOverridden = confidence != null;
var previousStatus = controller.versionStatus().version(statistics.version());
if (!confidenceIsOverridden) {
if (isSystemVersion || isControllerVersion) {
confidence = VespaVersion.confidenceFrom(statistics, controller);
} else {
confidence = getOrUpdateConfidence(statistics, controller);
}
}
var commitSha = controllerVersion.commitSha();
var commitDate = controllerVersion.commitDate();
if (previousStatus != null) {
commitSha = previousStatus.releaseCommit();
commitDate = previousStatus.committedAt();
if (!confidenceIsOverridden &&
!previousStatus.confidence().canChangeTo(confidence, controller.clock().instant())) {
confidence = previousStatus.confidence();
}
}
return new VespaVersion(statistics,
commitSha,
commitDate,
isControllerVersion,
isSystemVersion,
isReleased,
nodeVersions,
confidence);
}
/**
* Calculate confidence from given deployment statistics.
*
* @return previously calculated confidence for this version. If none exists, a new confidence will be calculated.
*/
private static VespaVersion.Confidence getOrUpdateConfidence(DeploymentStatistics statistics, Controller controller) {
return controller.versionStatus().versions().stream()
.filter(v -> statistics.version().equals(v.versionNumber()))
.map(VespaVersion::confidence)
.findFirst()
.orElseGet(() -> VespaVersion.confidenceFrom(statistics, controller));
}
} |
Probably not. Will remove. | private VespaVersion vespaVersionFromSlime(Inspector object) {
return new VespaVersion(deploymentStatisticsFromSlime(object.field(deploymentStatisticsField)),
object.field(releaseCommitField).asString(),
Instant.ofEpochMilli(object.field(committedAtField).asLong()),
object.field(isControllerVersionField).asBool(),
object.field(isSystemVersionField).asBool(),
!object.field(isReleasedField).valid() || object.field(isReleasedField).asBool(),
nodeVersionsFromSlime(object),
VespaVersion.Confidence.valueOf(object.field(confidenceField).asString())
);
} | !object.field(isReleasedField).valid() || object.field(isReleasedField).asBool(), | private VespaVersion vespaVersionFromSlime(Inspector object) {
var deploymentStatistics = deploymentStatisticsFromSlime(object.field(deploymentStatisticsField));
return new VespaVersion(deploymentStatistics,
object.field(releaseCommitField).asString(),
Instant.ofEpochMilli(object.field(committedAtField).asLong()),
object.field(isControllerVersionField).asBool(),
object.field(isSystemVersionField).asBool(),
object.field(isReleasedField).asBool(),
nodeVersionsFromSlime(object, deploymentStatistics.version()),
VespaVersion.Confidence.valueOf(object.field(confidenceField).asString())
);
} | class VersionStatusSerializer {
private static final String versionsField = "versions";
private static final String releaseCommitField = "releaseCommit";
private static final String committedAtField = "releasedAt";
private static final String isControllerVersionField = "isCurrentControllerVersion";
private static final String isSystemVersionField = "isCurrentSystemVersion";
private static final String isReleasedField = "isReleased";
private static final String deploymentStatisticsField = "deploymentStatistics";
private static final String confidenceField = "confidence";
private static final String configServersField = "configServerHostnames";
private static final String nodeVersionsField = "nodeVersions";
private static final String hostnameField = "hostname";
private static final String changedAtField = "changedAt";
private static final String versionField = "version";
private static final String failingField = "failing";
private static final String productionField = "production";
private static final String deployingField = "deploying";
public Slime toSlime(VersionStatus status) {
Slime slime = new Slime();
Cursor root = slime.setObject();
versionsToSlime(status.versions(), root.setArray(versionsField));
return slime;
}
public VersionStatus fromSlime(Slime slime) {
Inspector root = slime.get();
return new VersionStatus(vespaVersionsFromSlime(root.field(versionsField)));
}
private void versionsToSlime(List<VespaVersion> versions, Cursor array) {
versions.forEach(version -> vespaVersionToSlime(version, array.addObject()));
}
private void vespaVersionToSlime(VespaVersion version, Cursor object) {
object.setString(releaseCommitField, version.releaseCommit());
object.setLong(committedAtField, version.committedAt().toEpochMilli());
object.setBool(isControllerVersionField, version.isControllerVersion());
object.setBool(isSystemVersionField, version.isSystemVersion());
object.setBool(isReleasedField, version.isReleased());
deploymentStatisticsToSlime(version.statistics(), object.setObject(deploymentStatisticsField));
object.setString(confidenceField, version.confidence().name());
configServersToSlime(version.nodeVersions().hostnames(), object.setArray(configServersField));
nodeVersionsToSlime(version.nodeVersions(), object.setArray(nodeVersionsField));
}
private void nodeVersionsToSlime(NodeVersions nodeVersions, Cursor array) {
for (NodeVersion nodeVersion : nodeVersions.asMap().values()) {
var nodeVersionObject = array.addObject();
nodeVersionObject.setString(hostnameField, nodeVersion.hostname().value());
nodeVersionObject.setString(versionField, nodeVersion.version().toFullString());
nodeVersionObject.setLong(changedAtField, nodeVersion.changedAt().toEpochMilli());
}
}
private void configServersToSlime(Set<HostName> configServerHostnames, Cursor array) {
configServerHostnames.stream().map(HostName::value).forEach(array::addString);
}
private void deploymentStatisticsToSlime(DeploymentStatistics statistics, Cursor object) {
object.setString(versionField, statistics.version().toString());
applicationsToSlime(statistics.failing(), object.setArray(failingField));
applicationsToSlime(statistics.production(), object.setArray(productionField));
applicationsToSlime(statistics.deploying(), object.setArray(deployingField));
}
private void applicationsToSlime(Collection<ApplicationId> applications, Cursor array) {
applications.forEach(application -> array.addString(application.serializedForm()));
}
private List<VespaVersion> vespaVersionsFromSlime(Inspector array) {
List<VespaVersion> versions = new ArrayList<>();
array.traverse((ArrayTraverser) (i, object) -> versions.add(vespaVersionFromSlime(object)));
return Collections.unmodifiableList(versions);
}
private NodeVersions nodeVersionsFromSlime(Inspector root) {
var nodeVersions = new LinkedHashMap<HostName, NodeVersion>();
var nodeVersionsRoot = root.field(nodeVersionsField);
if (nodeVersionsRoot.valid()) {
nodeVersionsRoot.traverse((ArrayTraverser) (i, entry) -> {
var hostname = HostName.from(entry.field(hostnameField).asString());
var version = Version.fromString(entry.field(versionField).asString());
var changedAt = Instant.ofEpochMilli(entry.field(changedAtField).asLong());
nodeVersions.put(hostname, new NodeVersion(hostname, version, changedAt));
});
} else {
var configServerHostnames = configServersFromSlime(root.field(configServersField));
for (var hostname : configServerHostnames) {
nodeVersions.put(hostname, NodeVersion.empty(hostname));
}
}
return new NodeVersions(nodeVersions);
}
private Set<HostName> configServersFromSlime(Inspector array) {
Set<HostName> configServerHostnames = new LinkedHashSet<>();
array.traverse((ArrayTraverser) (i, entry) -> configServerHostnames.add(HostName.from(entry.asString())));
return Collections.unmodifiableSet(configServerHostnames);
}
private DeploymentStatistics deploymentStatisticsFromSlime(Inspector object) {
return new DeploymentStatistics(Version.fromString(object.field(versionField).asString()),
applicationsFromSlime(object.field(failingField)),
applicationsFromSlime(object.field(productionField)),
applicationsFromSlime(object.field(deployingField)));
}
private List<ApplicationId> applicationsFromSlime(Inspector array) {
List<ApplicationId> applications = new ArrayList<>();
array.traverse((ArrayTraverser) (i, entry) -> applications.add(
ApplicationId.fromSerializedForm(entry.asString()))
);
return Collections.unmodifiableList(applications);
}
} | class VersionStatusSerializer {
private static final String versionsField = "versions";
private static final String releaseCommitField = "releaseCommit";
private static final String committedAtField = "releasedAt";
private static final String isControllerVersionField = "isCurrentControllerVersion";
private static final String isSystemVersionField = "isCurrentSystemVersion";
private static final String isReleasedField = "isReleased";
private static final String deploymentStatisticsField = "deploymentStatistics";
private static final String confidenceField = "confidence";
private static final String configServersField = "configServerHostnames";
private static final String nodeVersionsField = "nodeVersions";
private static final String hostnameField = "hostname";
private static final String wantedVersionField = "wantedVersion";
private static final String changedAtField = "changedAt";
private static final String versionField = "version";
private static final String failingField = "failing";
private static final String productionField = "production";
private static final String deployingField = "deploying";
public Slime toSlime(VersionStatus status) {
Slime slime = new Slime();
Cursor root = slime.setObject();
versionsToSlime(status.versions(), root.setArray(versionsField));
return slime;
}
public VersionStatus fromSlime(Slime slime) {
Inspector root = slime.get();
return new VersionStatus(vespaVersionsFromSlime(root.field(versionsField)));
}
private void versionsToSlime(List<VespaVersion> versions, Cursor array) {
versions.forEach(version -> vespaVersionToSlime(version, array.addObject()));
}
private void vespaVersionToSlime(VespaVersion version, Cursor object) {
object.setString(releaseCommitField, version.releaseCommit());
object.setLong(committedAtField, version.committedAt().toEpochMilli());
object.setBool(isControllerVersionField, version.isControllerVersion());
object.setBool(isSystemVersionField, version.isSystemVersion());
object.setBool(isReleasedField, version.isReleased());
deploymentStatisticsToSlime(version.statistics(), object.setObject(deploymentStatisticsField));
object.setString(confidenceField, version.confidence().name());
configServersToSlime(version.nodeVersions().hostnames(), object.setArray(configServersField));
nodeVersionsToSlime(version.nodeVersions(), object.setArray(nodeVersionsField));
}
private void nodeVersionsToSlime(NodeVersions nodeVersions, Cursor array) {
for (NodeVersion nodeVersion : nodeVersions.asMap().values()) {
var nodeVersionObject = array.addObject();
nodeVersionObject.setString(hostnameField, nodeVersion.hostname().value());
nodeVersionObject.setString(wantedVersionField, nodeVersion.wantedVersion().toFullString());
nodeVersionObject.setLong(changedAtField, nodeVersion.changedAt().toEpochMilli());
}
}
private void configServersToSlime(Set<HostName> configServerHostnames, Cursor array) {
configServerHostnames.stream().map(HostName::value).forEach(array::addString);
}
private void deploymentStatisticsToSlime(DeploymentStatistics statistics, Cursor object) {
object.setString(versionField, statistics.version().toString());
applicationsToSlime(statistics.failing(), object.setArray(failingField));
applicationsToSlime(statistics.production(), object.setArray(productionField));
applicationsToSlime(statistics.deploying(), object.setArray(deployingField));
}
private void applicationsToSlime(Collection<ApplicationId> applications, Cursor array) {
applications.forEach(application -> array.addString(application.serializedForm()));
}
private List<VespaVersion> vespaVersionsFromSlime(Inspector array) {
List<VespaVersion> versions = new ArrayList<>();
array.traverse((ArrayTraverser) (i, object) -> versions.add(vespaVersionFromSlime(object)));
return Collections.unmodifiableList(versions);
}
private NodeVersions nodeVersionsFromSlime(Inspector root, Version version) {
var nodeVersions = ImmutableMap.<HostName, NodeVersion>builder();
var nodeVersionsRoot = root.field(nodeVersionsField);
if (nodeVersionsRoot.valid()) {
nodeVersionsRoot.traverse((ArrayTraverser) (i, entry) -> {
var hostname = HostName.from(entry.field(hostnameField).asString());
var wantedVersion = Version.fromString(entry.field(wantedVersionField).asString());
var changedAt = Instant.ofEpochMilli(entry.field(changedAtField).asLong());
nodeVersions.put(hostname, new NodeVersion(hostname, version, wantedVersion, changedAt));
});
} else {
var configServerHostnames = configServersFromSlime(root.field(configServersField));
for (var hostname : configServerHostnames) {
nodeVersions.put(hostname, NodeVersion.empty(hostname));
}
}
return new NodeVersions(nodeVersions.build());
}
private Set<HostName> configServersFromSlime(Inspector array) {
Set<HostName> configServerHostnames = new LinkedHashSet<>();
array.traverse((ArrayTraverser) (i, entry) -> configServerHostnames.add(HostName.from(entry.asString())));
return Collections.unmodifiableSet(configServerHostnames);
}
private DeploymentStatistics deploymentStatisticsFromSlime(Inspector object) {
return new DeploymentStatistics(Version.fromString(object.field(versionField).asString()),
applicationsFromSlime(object.field(failingField)),
applicationsFromSlime(object.field(productionField)),
applicationsFromSlime(object.field(deployingField)));
}
private List<ApplicationId> applicationsFromSlime(Inspector array) {
List<ApplicationId> applications = new ArrayList<>();
array.traverse((ArrayTraverser) (i, entry) -> applications.add(
ApplicationId.fromSerializedForm(entry.asString()))
);
return Collections.unmodifiableList(applications);
}
} |
Yes, I considered this as well. Will find a better approach just in case. | private static NodeVersions findSystemApplicationVersions(Controller controller) {
var nodeVersions = controller.versionStatus().systemVersion()
.map(VespaVersion::nodeVersions)
.orElse(NodeVersions.EMPTY);
var hostnames = new HashSet<HostName>();
for (var zone : controller.zoneRegistry().zones().controllerUpgraded().zones()) {
for (var application : SystemApplication.all()) {
var nodes = controller.serviceRegistry().configServer().nodeRepository()
.list(zone.getId(), application.id()).stream()
.filter(SystemUpgrader::eligibleForUpgrade)
.collect(Collectors.toList());
if (nodes.isEmpty()) continue;
var configConverged = application.configConvergedIn(zone.getId(), controller, Optional.empty());
if (!configConverged) {
log.log(LogLevel.WARNING, "Config for " + application.id() + " in " + zone.getId() +
" has not converged");
}
var now = controller.clock().instant();
for (var node : nodes) {
Version version = configConverged ? node.currentVersion() : controller.systemVersion();
nodeVersions = nodeVersions.with(new NodeVersion(node.hostname(), version, now));
hostnames.add(node.hostname());
}
}
}
return nodeVersions.retainAll(hostnames);
} | nodeVersions = nodeVersions.with(new NodeVersion(node.hostname(), version, now)); | private static NodeVersions findSystemApplicationVersions(Controller controller) {
var nodeVersions = controller.versionStatus().systemVersion()
.map(VespaVersion::nodeVersions)
.orElse(NodeVersions.EMPTY);
var newNodeVersions = new ArrayList<NodeVersion>();
for (var zone : controller.zoneRegistry().zones().controllerUpgraded().zones()) {
for (var application : SystemApplication.all()) {
var nodes = controller.serviceRegistry().configServer().nodeRepository()
.list(zone.getId(), application.id()).stream()
.filter(SystemUpgrader::eligibleForUpgrade)
.collect(Collectors.toList());
if (nodes.isEmpty()) continue;
var configConverged = application.configConvergedIn(zone.getId(), controller, Optional.empty());
if (!configConverged) {
log.log(LogLevel.WARNING, "Config for " + application.id() + " in " + zone.getId() +
" has not converged");
}
var now = controller.clock().instant();
for (var node : nodes) {
Version version = configConverged ? node.currentVersion() : controller.systemVersion();
newNodeVersions.add(new NodeVersion(node.hostname(), version, node.wantedVersion(), now));
}
}
}
return nodeVersions.with(newNodeVersions);
} | class VersionStatus {
private static final Logger log = Logger.getLogger(VersionStatus.class.getName());
private final ImmutableList<VespaVersion> versions;
/** Create a version status. DO NOT USE: Public for testing and serialization only */
public VersionStatus(List<VespaVersion> versions) {
this.versions = ImmutableList.copyOf(versions);
}
/** Returns the current version of controllers in this system */
public Optional<VespaVersion> controllerVersion() {
return versions().stream().filter(VespaVersion::isControllerVersion).findFirst();
}
/**
* Returns the current Vespa version of the system controlled by this,
* or empty if we have not currently determined what the system version is in this status.
*/
public Optional<VespaVersion> systemVersion() {
return versions().stream().filter(VespaVersion::isSystemVersion).findFirst();
}
/** Returns whether the system is currently upgrading */
public boolean isUpgrading() {
return systemVersion().map(VespaVersion::versionNumber).orElse(Version.emptyVersion)
.isBefore(controllerVersion().map(VespaVersion::versionNumber)
.orElse(Version.emptyVersion));
}
/**
* Lists all currently active Vespa versions, with deployment statistics,
* sorted from lowest to highest version number.
* The returned list is immutable.
* Calling this is free, but the returned status is slightly out of date.
*/
public List<VespaVersion> versions() { return versions; }
/** Returns the given version, or null if it is not present */
public VespaVersion version(Version version) {
return versions.stream().filter(v -> v.versionNumber().equals(version)).findFirst().orElse(null);
}
/** Create the empty version status */
public static VersionStatus empty() { return new VersionStatus(ImmutableList.of()); }
/** Create a full, updated version status. This is expensive and should be done infrequently */
public static VersionStatus compute(Controller controller) {
var systemApplicationVersions = findSystemApplicationVersions(controller);
var controllerVersions = findControllerVersions(controller);
var infrastructureVersions = ArrayListMultimap.<Version, HostName>create();
for (var kv : controllerVersions.asMap().entrySet()) {
infrastructureVersions.putAll(kv.getKey().version(), kv.getValue());
}
infrastructureVersions.putAll(systemApplicationVersions.asVersionMap());
ControllerVersion controllerVersion = controllerVersions.keySet().stream()
.min(Comparator.naturalOrder())
.get();
Version newSystemVersion = infrastructureVersions.keySet().stream().min(Comparator.naturalOrder()).get();
Version systemVersion = controller.versionStatus().systemVersion()
.map(VespaVersion::versionNumber)
.orElse(newSystemVersion);
if (newSystemVersion.isBefore(systemVersion)) {
log.warning("Refusing to lower system version from " +
controller.systemVersion() +
" to " +
newSystemVersion +
", nodes on " + newSystemVersion + ": " +
infrastructureVersions.get(newSystemVersion).stream()
.map(HostName::value)
.collect(Collectors.joining(", ")));
} else {
systemVersion = newSystemVersion;
}
Collection<DeploymentStatistics> deploymentStatistics = computeDeploymentStatistics(infrastructureVersions.keySet(),
controller.applications().asList());
List<VespaVersion> versions = new ArrayList<>();
List<Version> releasedVersions = controller.mavenRepository().metadata().versions();
for (DeploymentStatistics statistics : deploymentStatistics) {
if (statistics.version().isEmpty()) continue;
try {
boolean isReleased = Collections.binarySearch(releasedVersions, statistics.version()) >= 0;
VespaVersion vespaVersion = createVersion(statistics,
controllerVersion,
systemVersion,
isReleased,
systemApplicationVersions.matching(statistics.version()),
controller);
versions.add(vespaVersion);
} catch (IllegalArgumentException e) {
log.log(Level.WARNING, "Unable to create VespaVersion for version " +
statistics.version().toFullString(), e);
}
}
Collections.sort(versions);
return new VersionStatus(versions);
}
private static ListMultimap<ControllerVersion, HostName> findControllerVersions(Controller controller) {
ListMultimap<ControllerVersion, HostName> versions = ArrayListMultimap.create();
if (controller.curator().cluster().isEmpty()) {
versions.put(ControllerVersion.CURRENT, controller.hostname());
} else {
for (HostName hostname : controller.curator().cluster()) {
versions.put(controller.curator().readControllerVersion(hostname), hostname);
}
}
return versions;
}
private static Collection<DeploymentStatistics> computeDeploymentStatistics(Set<Version> infrastructureVersions,
List<Application> instances) {
Map<Version, DeploymentStatistics> versionMap = new HashMap<>();
for (Version infrastructureVersion : infrastructureVersions) {
versionMap.put(infrastructureVersion, DeploymentStatistics.empty(infrastructureVersion));
}
for (Application application : ApplicationList.from(instances).withProductionDeployment().asList())
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.productionDeployments().values()) {
versionMap.computeIfAbsent(deployment.version(), DeploymentStatistics::empty);
}
JobList.from(instance)
.failing()
.not().failingApplicationChange()
.not().failingBecause(outOfCapacity)
.mapToList(job -> job.lastCompleted().get().platform())
.forEach(version -> versionMap
.put(version, versionMap.getOrDefault(version, DeploymentStatistics.empty(version))
.withFailing(instance.id())));
JobList.from(instance)
.lastSuccess().present()
.production()
.mapToList(job -> job.lastSuccess().get().platform())
.forEach(version -> versionMap
.put(version, versionMap.getOrDefault(version, DeploymentStatistics.empty(version))
.withProduction(instance.id())));
JobList.from(instance)
.upgrading()
.mapToList(job -> job.lastTriggered().get().platform())
.forEach(version -> versionMap
.put(version, versionMap.getOrDefault(version, DeploymentStatistics.empty(version))
.withDeploying(instance.id())));
}
return versionMap.values();
}
private static VespaVersion createVersion(DeploymentStatistics statistics,
ControllerVersion controllerVersion,
Version systemVersion,
boolean isReleased,
NodeVersions nodeVersions,
Controller controller) {
var isSystemVersion = statistics.version().equals(systemVersion);
var isControllerVersion = statistics.version().equals(controllerVersion.version());
var confidence = controller.curator().readConfidenceOverrides().get(statistics.version());
var confidenceIsOverridden = confidence != null;
var previousStatus = controller.versionStatus().version(statistics.version());
if (!confidenceIsOverridden) {
if (isSystemVersion || isControllerVersion) {
confidence = VespaVersion.confidenceFrom(statistics, controller);
} else {
confidence = getOrUpdateConfidence(statistics, controller);
}
}
var commitSha = controllerVersion.commitSha();
var commitDate = controllerVersion.commitDate();
if (previousStatus != null) {
commitSha = previousStatus.releaseCommit();
commitDate = previousStatus.committedAt();
if (!confidenceIsOverridden &&
!previousStatus.confidence().canChangeTo(confidence, controller.clock().instant())) {
confidence = previousStatus.confidence();
}
}
return new VespaVersion(statistics,
commitSha,
commitDate,
isControllerVersion,
isSystemVersion,
isReleased,
nodeVersions,
confidence);
}
/**
* Calculate confidence from given deployment statistics.
*
* @return previously calculated confidence for this version. If none exists, a new confidence will be calculated.
*/
private static VespaVersion.Confidence getOrUpdateConfidence(DeploymentStatistics statistics, Controller controller) {
return controller.versionStatus().versions().stream()
.filter(v -> statistics.version().equals(v.versionNumber()))
.map(VespaVersion::confidence)
.findFirst()
.orElseGet(() -> VespaVersion.confidenceFrom(statistics, controller));
}
} | class VersionStatus {
private static final Logger log = Logger.getLogger(VersionStatus.class.getName());
private final ImmutableList<VespaVersion> versions;
/** Create a version status. DO NOT USE: Public for testing and serialization only */
public VersionStatus(List<VespaVersion> versions) {
this.versions = ImmutableList.copyOf(versions);
}
/** Returns the current version of controllers in this system */
public Optional<VespaVersion> controllerVersion() {
return versions().stream().filter(VespaVersion::isControllerVersion).findFirst();
}
/**
* Returns the current Vespa version of the system controlled by this,
* or empty if we have not currently determined what the system version is in this status.
*/
public Optional<VespaVersion> systemVersion() {
return versions().stream().filter(VespaVersion::isSystemVersion).findFirst();
}
/** Returns whether the system is currently upgrading */
public boolean isUpgrading() {
return systemVersion().map(VespaVersion::versionNumber).orElse(Version.emptyVersion)
.isBefore(controllerVersion().map(VespaVersion::versionNumber)
.orElse(Version.emptyVersion));
}
/**
* Lists all currently active Vespa versions, with deployment statistics,
* sorted from lowest to highest version number.
* The returned list is immutable.
* Calling this is free, but the returned status is slightly out of date.
*/
public List<VespaVersion> versions() { return versions; }
/** Returns the given version, or null if it is not present */
public VespaVersion version(Version version) {
return versions.stream().filter(v -> v.versionNumber().equals(version)).findFirst().orElse(null);
}
/** Create the empty version status */
public static VersionStatus empty() { return new VersionStatus(ImmutableList.of()); }
/** Create a full, updated version status. This is expensive and should be done infrequently */
public static VersionStatus compute(Controller controller) {
var systemApplicationVersions = findSystemApplicationVersions(controller);
var controllerVersions = findControllerVersions(controller);
var infrastructureVersions = ArrayListMultimap.<Version, HostName>create();
for (var kv : controllerVersions.asMap().entrySet()) {
infrastructureVersions.putAll(kv.getKey().version(), kv.getValue());
}
infrastructureVersions.putAll(systemApplicationVersions.asVersionMap());
ControllerVersion controllerVersion = controllerVersions.keySet().stream()
.min(Comparator.naturalOrder())
.get();
Version newSystemVersion = infrastructureVersions.keySet().stream().min(Comparator.naturalOrder()).get();
Version systemVersion = controller.versionStatus().systemVersion()
.map(VespaVersion::versionNumber)
.orElse(newSystemVersion);
if (newSystemVersion.isBefore(systemVersion)) {
log.warning("Refusing to lower system version from " +
controller.systemVersion() +
" to " +
newSystemVersion +
", nodes on " + newSystemVersion + ": " +
infrastructureVersions.get(newSystemVersion).stream()
.map(HostName::value)
.collect(Collectors.joining(", ")));
} else {
systemVersion = newSystemVersion;
}
Collection<DeploymentStatistics> deploymentStatistics = computeDeploymentStatistics(infrastructureVersions.keySet(),
controller.applications().asList());
List<VespaVersion> versions = new ArrayList<>();
List<Version> releasedVersions = controller.mavenRepository().metadata().versions();
for (DeploymentStatistics statistics : deploymentStatistics) {
if (statistics.version().isEmpty()) continue;
try {
boolean isReleased = Collections.binarySearch(releasedVersions, statistics.version()) >= 0;
VespaVersion vespaVersion = createVersion(statistics,
controllerVersion,
systemVersion,
isReleased,
systemApplicationVersions.matching(statistics.version()),
controller);
versions.add(vespaVersion);
} catch (IllegalArgumentException e) {
log.log(Level.WARNING, "Unable to create VespaVersion for version " +
statistics.version().toFullString(), e);
}
}
Collections.sort(versions);
return new VersionStatus(versions);
}
private static ListMultimap<ControllerVersion, HostName> findControllerVersions(Controller controller) {
ListMultimap<ControllerVersion, HostName> versions = ArrayListMultimap.create();
if (controller.curator().cluster().isEmpty()) {
versions.put(ControllerVersion.CURRENT, controller.hostname());
} else {
for (HostName hostname : controller.curator().cluster()) {
versions.put(controller.curator().readControllerVersion(hostname), hostname);
}
}
return versions;
}
private static Collection<DeploymentStatistics> computeDeploymentStatistics(Set<Version> infrastructureVersions,
List<Application> instances) {
Map<Version, DeploymentStatistics> versionMap = new HashMap<>();
for (Version infrastructureVersion : infrastructureVersions) {
versionMap.put(infrastructureVersion, DeploymentStatistics.empty(infrastructureVersion));
}
for (Application application : ApplicationList.from(instances).withProductionDeployment().asList())
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.productionDeployments().values()) {
versionMap.computeIfAbsent(deployment.version(), DeploymentStatistics::empty);
}
JobList.from(instance)
.failing()
.not().failingApplicationChange()
.not().failingBecause(outOfCapacity)
.mapToList(job -> job.lastCompleted().get().platform())
.forEach(version -> versionMap
.put(version, versionMap.getOrDefault(version, DeploymentStatistics.empty(version))
.withFailing(instance.id())));
JobList.from(instance)
.lastSuccess().present()
.production()
.mapToList(job -> job.lastSuccess().get().platform())
.forEach(version -> versionMap
.put(version, versionMap.getOrDefault(version, DeploymentStatistics.empty(version))
.withProduction(instance.id())));
JobList.from(instance)
.upgrading()
.mapToList(job -> job.lastTriggered().get().platform())
.forEach(version -> versionMap
.put(version, versionMap.getOrDefault(version, DeploymentStatistics.empty(version))
.withDeploying(instance.id())));
}
return versionMap.values();
}
private static VespaVersion createVersion(DeploymentStatistics statistics,
ControllerVersion controllerVersion,
Version systemVersion,
boolean isReleased,
NodeVersions nodeVersions,
Controller controller) {
var isSystemVersion = statistics.version().equals(systemVersion);
var isControllerVersion = statistics.version().equals(controllerVersion.version());
var confidence = controller.curator().readConfidenceOverrides().get(statistics.version());
var confidenceIsOverridden = confidence != null;
var previousStatus = controller.versionStatus().version(statistics.version());
if (!confidenceIsOverridden) {
if (isSystemVersion || isControllerVersion) {
confidence = VespaVersion.confidenceFrom(statistics, controller);
} else {
confidence = getOrUpdateConfidence(statistics, controller);
}
}
var commitSha = controllerVersion.commitSha();
var commitDate = controllerVersion.commitDate();
if (previousStatus != null) {
commitSha = previousStatus.releaseCommit();
commitDate = previousStatus.committedAt();
if (!confidenceIsOverridden &&
!previousStatus.confidence().canChangeTo(confidence, controller.clock().instant())) {
confidence = previousStatus.confidence();
}
}
return new VespaVersion(statistics,
commitSha,
commitDate,
isControllerVersion,
isSystemVersion,
isReleased,
nodeVersions,
confidence);
}
/**
* Calculate confidence from given deployment statistics.
*
* @return previously calculated confidence for this version. If none exists, a new confidence will be calculated.
*/
private static VespaVersion.Confidence getOrUpdateConfidence(DeploymentStatistics statistics, Controller controller) {
return controller.versionStatus().versions().stream()
.filter(v -> statistics.version().equals(v.versionNumber()))
.map(VespaVersion::confidence)
.findFirst()
.orElseGet(() -> VespaVersion.confidenceFrom(statistics, controller));
}
} |
Consider catching any exceptions thrown by `KeyUtils` to improve the error messages back to user (e.g when user uploads unsupported key or invalid PEM). | 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);
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant ->
controller.tenants().store(tenant.withDeveloperKey(developerKey, user)));
return new MessageResponse("Set developer key " + pemDeveloperKey + " for " + user);
} | PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey); | 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);
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant ->
controller.tenants().store(tenant.withDeveloperKey(developerKey, user)));
return new MessageResponse("Set developer key " + pemDeveloperKey + " for " + user);
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
}
@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/user")) return authenticatedUser(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"), "default", 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 application(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}/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}/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}/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/user")) return createUser(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"), "default", 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}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), 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"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createApplication(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/{ignored}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), path.get("instance"), 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}/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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), "default");
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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), path.get("instance"));
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}/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, "user", "tenant");
}
private HttpResponse authenticatedUser(HttpRequest request) {
Principal user = requireUserPrincipal(request);
if (user == null)
throw new NotAuthorizedException("You must be authenticated.");
String userName = user instanceof AthenzPrincipal ? ((AthenzPrincipal) user).getIdentity().getName() : user.getName();
TenantName tenantName = TenantName.from(UserTenant.normalizeUser(userName));
List<Tenant> tenants = controller.tenants().asList(new Credentials(user));
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setString("user", userName);
Cursor tenantsArray = response.setArray("tenants");
for (Tenant tenant : tenants)
tenantInTenantsListToSlime(tenant, request.getUri(), tenantsArray.addObject());
response.setBool("tenantExists", tenants.stream().anyMatch(tenant -> tenant.name().equals(tenantName)));
return new SlimeJsonResponse(slime);
}
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);
Slime slime = new Slime();
Cursor array = slime.setArray();
for (Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true))
for (InstanceName instance : application.instances().keySet())
toSlime(application.id().instance(instance), array.addObject(), request);
}
return new SlimeJsonResponse(slime);
}
private HttpResponse application(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
getApplication(tenantName, applicationName, instanceName), request);
return new SlimeJsonResponse(slime);
}
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);
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant ->
controller.tenants().store(tenant.withoutDeveloperKey(developerKey)));
return new MessageResponse("Removed developer key " + pemDeveloperKey + " for " + user);
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application ->
controller.applications().store(application.withDeployKey(deployKey)));
return new MessageResponse("Added deploy key " + pemDeployKey);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application ->
controller.applications().store(application.withoutDeployKey(deployKey)));
return new MessageResponse("Removed deploy key " + pemDeployKey);
}
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 Application getApplication(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
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()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.canonicalFlavor());
nodeObject.setDouble("vcpu", node.vcpu());
nodeObject.setDouble("memoryGb", node.memoryGb());
nodeObject.setDouble("diskGb", node.diskGb());
nodeObject.setDouble("bandwidthGbps", node.bandwidthGbps());
nodeObject.setBool("fastDisk", node.fastDisk());
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
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";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
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) {
String triggered = controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName())
.stream().map(JobType::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 void toSlime(Cursor object, Instance instance, Application application, HttpRequest request) {
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());
instance.deploymentJobs().statusOf(JobType.component)
.flatMap(JobStatus::lastSuccess)
.map(run -> run.application().source())
.ifPresent(source -> sourceRevisionToSlime(source, object.setObject("source")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if ( ! application.change().isEmpty()) {
toSlime(object.setObject("deploying"), application.change());
}
if ( ! application.outstandingChange().isEmpty()) {
toSlime(object.setObject("outstandingChange"), application.outstandingChange());
}
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedJobs(instance.deploymentJobs().jobStatus().values());
object.setBool("deployedInternally", application.internal());
Cursor deploymentsArray = object.setArray("deploymentJobs");
for (JobStatus job : jobStatus) {
Cursor jobObject = deploymentsArray.addObject();
jobObject.setString("type", job.type().jobName());
jobObject.setBool("success", job.isSuccess());
job.lastTriggered().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastTriggered")));
job.lastCompleted().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastCompleted")));
job.firstFailing().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("firstFailing")));
job.lastSuccess().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastSuccess")));
}
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().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);
});
object.setString("compileVersion", compileVersion(application.id()).toFullString());
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor globalRotationsArray = object.setArray("globalRotations");
instance.endpointsIn(controller.system())
.scope(Endpoint.Scope.global)
.legacy(false)
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
Set<RoutingPolicy> routingPolicies = controller.applications().routingPolicies().get(instance.id());
for (RoutingPolicy policy : routingPolicies) {
policy.rotationEndpointsIn(controller.system()).asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
}
List<Deployment> deployments = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedDeployments(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 (!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().getPath().contains("/instance/") ? "" : "/instance/" + instance.id().instance().value()),
request.getUri()).toString());
}
}
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(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 endpointArray = response.setArray("endpoints");
for (var policy : controller.applications().routingPolicies().get(deploymentId)) {
Cursor endpointObject = endpointArray.addObject();
Endpoint endpoint = policy.endpointIn(controller.system());
endpointObject.setString("cluster", policy.cluster().value());
endpointObject.setBool("tls", endpoint.tls());
endpointObject.setString("url", endpoint.url().toString());
}
Cursor serviceUrlArray = response.setArray("serviceUrls");
controller.applications().getDeploymentEndpoints(deploymentId)
.forEach(endpoint -> serviceUrlArray.addString(endpoint.toString()));
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()));
controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId())).projectId()
.ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
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));
DeploymentCost appCost = deployment.calculateCost();
Cursor costObject = response.setObject("cost");
toSlime(appCost, costObject);
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.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if ( ! revision.isPresent()) 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();
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
}
}
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);
return controller.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 -> ! controller.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);
}
Inspector requestData = toSlime(request.getData()).get();
String reason = mandatory("reason", requestData).asString();
String agent = requireUserPrincipal(request).getName();
long timestamp = controller.clock().instant().getEpochSecond();
EndpointStatus.Status status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
EndpointStatus endpointStatus = new EndpointStatus(status, reason, agent, timestamp);
controller.applications().setGlobalRotationStatus(new DeploymentId(instance.id(), deployment.zone()),
endpointStatus);
return new MessageResponse(String.format("Successfully set %s in %s.%s %s service",
instance.id().toShortString(),
deployment.zone().environment().value(),
deployment.zone().region().value(),
inService ? "in" : "out of"));
}
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");
Map<RoutingEndpoint, EndpointStatus> status = controller.applications().globalRotationStatus(deploymentId);
for (RoutingEndpoint endpoint : status.keySet()) {
EndpointStatus currentStatus = status.get(endpoint);
array.addString(endpoint.upstreamName());
Cursor statusObject = array.addObject();
statusObject.setString("status", currentStatus.getStatus().name());
statusObject.setString("reason", currentStatus.getReason() == null ? "" : currentStatus.getReason());
statusObject.setString("agent", currentStatus.getAgent() == null ? "" : currentStatus.getAgent());
statusObject.setLong("timestamp", currentStatus.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();
MeteringInfo meteringInfo = controller.serviceRegistry().meteringService().getResourceSnapshots(tenant, application);
ResourceAllocation currentSnapshot = meteringInfo.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringInfo.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringInfo.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 = meteringInfo.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 tenant, String application, String instance, HttpRequest request) {
Application app = controller.applications().requireApplication(TenantAndApplicationId.from(tenant, application));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! app.change().isEmpty()) {
app.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
app.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", app.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) {
Map<?,?> result = controller.getServiceApiResponse(tenantName, applicationName, instanceName, environment, region, serviceName, restPath);
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(result, serviceName, restPath);
return response;
}
private HttpResponse createUser(HttpRequest request) {
String user = Optional.of(requireUserPrincipal(request))
.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.map(AthenzIdentity::getName)
.map(UserTenant::normalizeUser)
.orElseThrow(() -> new ForbiddenException("Not authenticated or not a user."));
UserTenant tenant = UserTenant.create(user);
try {
controller.tenants().createUser(tenant);
return new MessageResponse("Created user '" + user + "'");
} catch (AlreadyExistsException e) {
return new MessageResponse("User '" + user + "' already exists");
}
}
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, String instanceName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
try {
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest()));
Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
catch (ZmsClientException e) {
if (e.getErrorCode() == com.yahoo.jdisc.Response.Status.FORBIDDEN)
throw new ForbiddenException("Not authorized to create application", e);
else
throw e;
}
}
/** 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());
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(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 " + change + " for " + 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);
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = Change.of(application.get().require(InstanceName.from(instanceName)).deploymentJobs().statusOf(JobType.component).get().lastSuccess().get().application());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered " + change + " for " + 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) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = application.get().change();
if (change.isEmpty()) {
response.append("No deployment in progress for " + application + " at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '" + change + "' to '" +
controller.applications().requireApplication(id).change() + "' for " + application);
});
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) {
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(),
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);
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<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,
application.get().internal(),
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,
application.get().internal(),
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass,
Optional.of(requireUserPrincipal(request)));
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if ( ! tenant.isPresent())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
if (tenant.get().type() == Tenant.Type.user)
controller.tenants().deleteUser((UserTenant) tenant.get());
else
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) {
TenantName tenant = TenantName.from(tenantName);
ApplicationName application = ApplicationName.from(applicationName);
Optional<Credentials> credentials = controller.tenants().require(tenant).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(tenant, toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteApplication(tenant, application, credentials);
return new MessageResponse("Deleted application " + tenant + "." + application);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteInstance(id, credentials);
return new MessageResponse("Deleted instance " + id.toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
DeploymentId deploymentId = new DeploymentId(instance.id(), ZoneId.from(environment, region));
controller.applications().deactivate(deploymentId.applicationId(), deploymentId.zoneId());
return new MessageResponse("Deactivated " + deploymentId);
}
private HttpResponse notifyJobCompletion(String tenant, String application, HttpRequest request) {
try {
DeploymentJobs.JobReport report = toJobReport(tenant, application, toSlime(request.getData()).get());
if ( report.jobType() == JobType.component
&& controller.applications().requireApplication(TenantAndApplicationId.from(report.applicationId())).internal())
throw new IllegalArgumentException(report.applicationId() + " is set up to be deployed from internally, and no " +
"longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.");
controller.applications().deploymentTrigger().notifyOfCompletion(report);
return new MessageResponse("ok");
} catch (IllegalStateException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
}
private HttpResponse testConfig(ApplicationId id, JobType type) {
var endpoints = controller.applications().clusterEndpoints(id, controller.jobController().testedZoneAndProductionZones(id, type));
return new SlimeJsonResponse(new TestConfigSerializer(controller.system()).configSlime(id,
type,
endpoints,
Collections.emptyMap()));
}
private static DeploymentJobs.JobReport toJobReport(String tenantName, String applicationName, Inspector report) {
Optional<DeploymentJobs.JobError> jobError = Optional.empty();
if (report.field("jobError").valid()) {
jobError = Optional.of(DeploymentJobs.JobError.valueOf(report.field("jobError").asString()));
}
ApplicationId id = ApplicationId.from(tenantName, applicationName, report.field("instance").asString());
JobType type = JobType.fromJobName(report.field("jobName").asString());
long buildNumber = report.field("buildNumber").asLong();
if (type == JobType.component)
return DeploymentJobs.JobReport.ofComponent(id,
report.field("projectId").asLong(),
buildNumber,
jobError,
toSourceRevision(report.field("sourceRevision")));
else
return DeploymentJobs.JobReport.ofJob(id, type, buildNumber, jobError);
}
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<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 user: break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
Cursor pemDeployKeysArray = object.setArray("pemDeployKeys");
for (Application application : applications)
for (PublicKey key : application.deployKeys()) {
Cursor keyObject = pemDeployKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("application", application.id().application().value());
}
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 (Application application : applications)
for (Instance instance : application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, application, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
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 user: 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(JobStatus.JobRun jobRun, Cursor object) {
object.setLong("id", jobRun.id());
object.setString("version", jobRun.platform().toFullString());
if (!jobRun.application().isUnknown())
toSlime(jobRun.application(), object.setObject("revision"));
object.setString("reason", jobRun.reason());
object.setLong("at", jobRun.at().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(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));
}
public static void toSlime(DeploymentCost deploymentCost, Cursor object) {
object.setLong("tco", (long)deploymentCost.getTco());
object.setLong("waste", (long)deploymentCost.getWaste());
object.setDouble("utilization", deploymentCost.getUtilization());
Cursor clustersObject = object.setObject("cluster");
for (Map.Entry<String, ClusterCost> clusterEntry : deploymentCost.getCluster().entrySet())
toSlime(clusterEntry.getValue(), clustersObject.setObject(clusterEntry.getKey()));
}
private static void toSlime(ClusterCost clusterCost, Cursor object) {
object.setLong("count", clusterCost.getClusterInfo().getHostnames().size());
object.setString("resource", getResourceName(clusterCost.getResultUtilization()));
object.setDouble("utilization", clusterCost.getResultUtilization().getMaxUtilization());
object.setLong("tco", (int)clusterCost.getTco());
object.setLong("waste", (int)clusterCost.getWaste());
object.setString("flavor", clusterCost.getClusterInfo().getFlavor());
object.setDouble("flavorCost", clusterCost.getClusterInfo().getFlavorCost());
object.setDouble("flavorCpu", clusterCost.getClusterInfo().getFlavorCPU());
object.setDouble("flavorMem", clusterCost.getClusterInfo().getFlavorMem());
object.setDouble("flavorDisk", clusterCost.getClusterInfo().getFlavorDisk());
object.setString("type", clusterCost.getClusterInfo().getClusterType().name());
Cursor utilObject = object.setObject("util");
utilObject.setDouble("cpu", clusterCost.getResultUtilization().getCpu());
utilObject.setDouble("mem", clusterCost.getResultUtilization().getMemory());
utilObject.setDouble("disk", clusterCost.getResultUtilization().getDisk());
utilObject.setDouble("diskBusy", clusterCost.getResultUtilization().getDiskBusy());
Cursor usageObject = object.setObject("usage");
usageObject.setDouble("cpu", clusterCost.getSystemUtilization().getCpu());
usageObject.setDouble("mem", clusterCost.getSystemUtilization().getMemory());
usageObject.setDouble("disk", clusterCost.getSystemUtilization().getDisk());
usageObject.setDouble("diskBusy", clusterCost.getSystemUtilization().getDiskBusy());
Cursor hostnamesArray = object.setArray("hostnames");
for (String hostname : clusterCost.getClusterInfo().getHostnames())
hostnamesArray.addString(hostname);
}
private static String getResourceName(ClusterUtilization utilization) {
String name = "cpu";
double max = utilization.getMaxUtilization();
if (utilization.getMemory() == max) {
name = "mem";
} else if (utilization.getDisk() == max) {
name = "disk";
} else if (utilization.getDiskBusy() == max) {
name = "diskbusy";
}
return name;
}
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 String tenantType(Tenant tenant) {
switch (tenant.type()) {
case user: return "USER";
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, String instance, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
SourceRevision sourceRevision = toSourceRevision(submitOptions);
String authorEmail = submitOptions.field("authorEmail").asString();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
instance,
sourceRevision,
authorEmail,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
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";
}
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
}
@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/user")) return authenticatedUser(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"), "default", 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 application(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}/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}/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}/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/user")) return createUser(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"), "default", 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}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), 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"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createApplication(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/{ignored}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), path.get("instance"), 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}/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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), "default");
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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), path.get("instance"));
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}/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, "user", "tenant");
}
private HttpResponse authenticatedUser(HttpRequest request) {
Principal user = requireUserPrincipal(request);
if (user == null)
throw new NotAuthorizedException("You must be authenticated.");
String userName = user instanceof AthenzPrincipal ? ((AthenzPrincipal) user).getIdentity().getName() : user.getName();
TenantName tenantName = TenantName.from(UserTenant.normalizeUser(userName));
List<Tenant> tenants = controller.tenants().asList(new Credentials(user));
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setString("user", userName);
Cursor tenantsArray = response.setArray("tenants");
for (Tenant tenant : tenants)
tenantInTenantsListToSlime(tenant, request.getUri(), tenantsArray.addObject());
response.setBool("tenantExists", tenants.stream().anyMatch(tenant -> tenant.name().equals(tenantName)));
return new SlimeJsonResponse(slime);
}
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);
Slime slime = new Slime();
Cursor array = slime.setArray();
for (Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true))
for (InstanceName instance : application.instances().keySet())
toSlime(application.id().instance(instance), array.addObject(), request);
}
return new SlimeJsonResponse(slime);
}
private HttpResponse application(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
getApplication(tenantName, applicationName, instanceName), request);
return new SlimeJsonResponse(slime);
}
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);
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant ->
controller.tenants().store(tenant.withoutDeveloperKey(developerKey)));
return new MessageResponse("Removed developer key " + pemDeveloperKey + " for " + user);
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application ->
controller.applications().store(application.withDeployKey(deployKey)));
return new MessageResponse("Added deploy key " + pemDeployKey);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application ->
controller.applications().store(application.withoutDeployKey(deployKey)));
return new MessageResponse("Removed deploy key " + pemDeployKey);
}
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 Application getApplication(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
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()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.canonicalFlavor());
nodeObject.setDouble("vcpu", node.vcpu());
nodeObject.setDouble("memoryGb", node.memoryGb());
nodeObject.setDouble("diskGb", node.diskGb());
nodeObject.setDouble("bandwidthGbps", node.bandwidthGbps());
nodeObject.setBool("fastDisk", node.fastDisk());
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
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";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
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) {
String triggered = controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName())
.stream().map(JobType::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 void toSlime(Cursor object, Instance instance, Application application, HttpRequest request) {
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());
instance.deploymentJobs().statusOf(JobType.component)
.flatMap(JobStatus::lastSuccess)
.map(run -> run.application().source())
.ifPresent(source -> sourceRevisionToSlime(source, object.setObject("source")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if ( ! application.change().isEmpty()) {
toSlime(object.setObject("deploying"), application.change());
}
if ( ! application.outstandingChange().isEmpty()) {
toSlime(object.setObject("outstandingChange"), application.outstandingChange());
}
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedJobs(instance.deploymentJobs().jobStatus().values());
object.setBool("deployedInternally", application.internal());
Cursor deploymentsArray = object.setArray("deploymentJobs");
for (JobStatus job : jobStatus) {
Cursor jobObject = deploymentsArray.addObject();
jobObject.setString("type", job.type().jobName());
jobObject.setBool("success", job.isSuccess());
job.lastTriggered().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastTriggered")));
job.lastCompleted().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastCompleted")));
job.firstFailing().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("firstFailing")));
job.lastSuccess().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastSuccess")));
}
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().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);
});
object.setString("compileVersion", compileVersion(application.id()).toFullString());
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor globalRotationsArray = object.setArray("globalRotations");
instance.endpointsIn(controller.system())
.scope(Endpoint.Scope.global)
.legacy(false)
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
Set<RoutingPolicy> routingPolicies = controller.applications().routingPolicies().get(instance.id());
for (RoutingPolicy policy : routingPolicies) {
policy.rotationEndpointsIn(controller.system()).asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
}
List<Deployment> deployments = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedDeployments(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 (!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().getPath().contains("/instance/") ? "" : "/instance/" + instance.id().instance().value()),
request.getUri()).toString());
}
}
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(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 endpointArray = response.setArray("endpoints");
for (var policy : controller.applications().routingPolicies().get(deploymentId)) {
Cursor endpointObject = endpointArray.addObject();
Endpoint endpoint = policy.endpointIn(controller.system());
endpointObject.setString("cluster", policy.cluster().value());
endpointObject.setBool("tls", endpoint.tls());
endpointObject.setString("url", endpoint.url().toString());
}
Cursor serviceUrlArray = response.setArray("serviceUrls");
controller.applications().getDeploymentEndpoints(deploymentId)
.forEach(endpoint -> serviceUrlArray.addString(endpoint.toString()));
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()));
controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId())).projectId()
.ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
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));
DeploymentCost appCost = deployment.calculateCost();
Cursor costObject = response.setObject("cost");
toSlime(appCost, costObject);
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.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if ( ! revision.isPresent()) 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();
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
}
}
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);
return controller.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 -> ! controller.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);
}
Inspector requestData = toSlime(request.getData()).get();
String reason = mandatory("reason", requestData).asString();
String agent = requireUserPrincipal(request).getName();
long timestamp = controller.clock().instant().getEpochSecond();
EndpointStatus.Status status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
EndpointStatus endpointStatus = new EndpointStatus(status, reason, agent, timestamp);
controller.applications().setGlobalRotationStatus(new DeploymentId(instance.id(), deployment.zone()),
endpointStatus);
return new MessageResponse(String.format("Successfully set %s in %s.%s %s service",
instance.id().toShortString(),
deployment.zone().environment().value(),
deployment.zone().region().value(),
inService ? "in" : "out of"));
}
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");
Map<RoutingEndpoint, EndpointStatus> status = controller.applications().globalRotationStatus(deploymentId);
for (RoutingEndpoint endpoint : status.keySet()) {
EndpointStatus currentStatus = status.get(endpoint);
array.addString(endpoint.upstreamName());
Cursor statusObject = array.addObject();
statusObject.setString("status", currentStatus.getStatus().name());
statusObject.setString("reason", currentStatus.getReason() == null ? "" : currentStatus.getReason());
statusObject.setString("agent", currentStatus.getAgent() == null ? "" : currentStatus.getAgent());
statusObject.setLong("timestamp", currentStatus.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();
MeteringInfo meteringInfo = controller.serviceRegistry().meteringService().getResourceSnapshots(tenant, application);
ResourceAllocation currentSnapshot = meteringInfo.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringInfo.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringInfo.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 = meteringInfo.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 tenant, String application, String instance, HttpRequest request) {
Application app = controller.applications().requireApplication(TenantAndApplicationId.from(tenant, application));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! app.change().isEmpty()) {
app.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
app.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", app.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) {
Map<?,?> result = controller.getServiceApiResponse(tenantName, applicationName, instanceName, environment, region, serviceName, restPath);
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(result, serviceName, restPath);
return response;
}
private HttpResponse createUser(HttpRequest request) {
String user = Optional.of(requireUserPrincipal(request))
.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.map(AthenzIdentity::getName)
.map(UserTenant::normalizeUser)
.orElseThrow(() -> new ForbiddenException("Not authenticated or not a user."));
UserTenant tenant = UserTenant.create(user);
try {
controller.tenants().createUser(tenant);
return new MessageResponse("Created user '" + user + "'");
} catch (AlreadyExistsException e) {
return new MessageResponse("User '" + user + "' already exists");
}
}
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, String instanceName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
try {
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest()));
Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
catch (ZmsClientException e) {
if (e.getErrorCode() == com.yahoo.jdisc.Response.Status.FORBIDDEN)
throw new ForbiddenException("Not authorized to create application", e);
else
throw e;
}
}
/** 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());
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(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 " + change + " for " + 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);
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = Change.of(application.get().require(InstanceName.from(instanceName)).deploymentJobs().statusOf(JobType.component).get().lastSuccess().get().application());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered " + change + " for " + 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) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = application.get().change();
if (change.isEmpty()) {
response.append("No deployment in progress for " + application + " at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '" + change + "' to '" +
controller.applications().requireApplication(id).change() + "' for " + application);
});
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) {
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(),
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);
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<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,
application.get().internal(),
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,
application.get().internal(),
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass,
Optional.of(requireUserPrincipal(request)));
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if ( ! tenant.isPresent())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
if (tenant.get().type() == Tenant.Type.user)
controller.tenants().deleteUser((UserTenant) tenant.get());
else
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) {
TenantName tenant = TenantName.from(tenantName);
ApplicationName application = ApplicationName.from(applicationName);
Optional<Credentials> credentials = controller.tenants().require(tenant).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(tenant, toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteApplication(tenant, application, credentials);
return new MessageResponse("Deleted application " + tenant + "." + application);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteInstance(id, credentials);
return new MessageResponse("Deleted instance " + id.toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
DeploymentId deploymentId = new DeploymentId(instance.id(), ZoneId.from(environment, region));
controller.applications().deactivate(deploymentId.applicationId(), deploymentId.zoneId());
return new MessageResponse("Deactivated " + deploymentId);
}
private HttpResponse notifyJobCompletion(String tenant, String application, HttpRequest request) {
try {
DeploymentJobs.JobReport report = toJobReport(tenant, application, toSlime(request.getData()).get());
if ( report.jobType() == JobType.component
&& controller.applications().requireApplication(TenantAndApplicationId.from(report.applicationId())).internal())
throw new IllegalArgumentException(report.applicationId() + " is set up to be deployed from internally, and no " +
"longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.");
controller.applications().deploymentTrigger().notifyOfCompletion(report);
return new MessageResponse("ok");
} catch (IllegalStateException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
}
private HttpResponse testConfig(ApplicationId id, JobType type) {
var endpoints = controller.applications().clusterEndpoints(id, controller.jobController().testedZoneAndProductionZones(id, type));
return new SlimeJsonResponse(new TestConfigSerializer(controller.system()).configSlime(id,
type,
endpoints,
Collections.emptyMap()));
}
private static DeploymentJobs.JobReport toJobReport(String tenantName, String applicationName, Inspector report) {
Optional<DeploymentJobs.JobError> jobError = Optional.empty();
if (report.field("jobError").valid()) {
jobError = Optional.of(DeploymentJobs.JobError.valueOf(report.field("jobError").asString()));
}
ApplicationId id = ApplicationId.from(tenantName, applicationName, report.field("instance").asString());
JobType type = JobType.fromJobName(report.field("jobName").asString());
long buildNumber = report.field("buildNumber").asLong();
if (type == JobType.component)
return DeploymentJobs.JobReport.ofComponent(id,
report.field("projectId").asLong(),
buildNumber,
jobError,
toSourceRevision(report.field("sourceRevision")));
else
return DeploymentJobs.JobReport.ofJob(id, type, buildNumber, jobError);
}
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<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 user: 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 (Application application : applications)
for (Instance instance : application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, application, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
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 user: 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(JobStatus.JobRun jobRun, Cursor object) {
object.setLong("id", jobRun.id());
object.setString("version", jobRun.platform().toFullString());
if (!jobRun.application().isUnknown())
toSlime(jobRun.application(), object.setObject("revision"));
object.setString("reason", jobRun.reason());
object.setLong("at", jobRun.at().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(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));
}
public static void toSlime(DeploymentCost deploymentCost, Cursor object) {
object.setLong("tco", (long)deploymentCost.getTco());
object.setLong("waste", (long)deploymentCost.getWaste());
object.setDouble("utilization", deploymentCost.getUtilization());
Cursor clustersObject = object.setObject("cluster");
for (Map.Entry<String, ClusterCost> clusterEntry : deploymentCost.getCluster().entrySet())
toSlime(clusterEntry.getValue(), clustersObject.setObject(clusterEntry.getKey()));
}
private static void toSlime(ClusterCost clusterCost, Cursor object) {
object.setLong("count", clusterCost.getClusterInfo().getHostnames().size());
object.setString("resource", getResourceName(clusterCost.getResultUtilization()));
object.setDouble("utilization", clusterCost.getResultUtilization().getMaxUtilization());
object.setLong("tco", (int)clusterCost.getTco());
object.setLong("waste", (int)clusterCost.getWaste());
object.setString("flavor", clusterCost.getClusterInfo().getFlavor());
object.setDouble("flavorCost", clusterCost.getClusterInfo().getFlavorCost());
object.setDouble("flavorCpu", clusterCost.getClusterInfo().getFlavorCPU());
object.setDouble("flavorMem", clusterCost.getClusterInfo().getFlavorMem());
object.setDouble("flavorDisk", clusterCost.getClusterInfo().getFlavorDisk());
object.setString("type", clusterCost.getClusterInfo().getClusterType().name());
Cursor utilObject = object.setObject("util");
utilObject.setDouble("cpu", clusterCost.getResultUtilization().getCpu());
utilObject.setDouble("mem", clusterCost.getResultUtilization().getMemory());
utilObject.setDouble("disk", clusterCost.getResultUtilization().getDisk());
utilObject.setDouble("diskBusy", clusterCost.getResultUtilization().getDiskBusy());
Cursor usageObject = object.setObject("usage");
usageObject.setDouble("cpu", clusterCost.getSystemUtilization().getCpu());
usageObject.setDouble("mem", clusterCost.getSystemUtilization().getMemory());
usageObject.setDouble("disk", clusterCost.getSystemUtilization().getDisk());
usageObject.setDouble("diskBusy", clusterCost.getSystemUtilization().getDiskBusy());
Cursor hostnamesArray = object.setArray("hostnames");
for (String hostname : clusterCost.getClusterInfo().getHostnames())
hostnamesArray.addString(hostname);
}
private static String getResourceName(ClusterUtilization utilization) {
String name = "cpu";
double max = utilization.getMaxUtilization();
if (utilization.getMemory() == max) {
name = "mem";
} else if (utilization.getDisk() == max) {
name = "disk";
} else if (utilization.getDiskBusy() == max) {
name = "diskbusy";
}
return name;
}
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 String tenantType(Tenant tenant) {
switch (tenant.type()) {
case user: return "USER";
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, String instance, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
SourceRevision sourceRevision = toSourceRevision(submitOptions);
String authorEmail = submitOptions.field("authorEmail").asString();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
instance,
sourceRevision,
authorEmail,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
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";
}
} |
Consider moving this branch to a separate method to make the separation between developer and deploy keys more clear. | protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
if ( request.getAttribute(SecurityContext.ATTRIBUTE_NAME) == null
&& request.getHeader("X-Authorization") != null)
try {
ApplicationId id = ApplicationId.fromSerializedForm(request.getHeader("X-Key-Id"));
SecurityContext securityContext = null;
if (request.getHeader("X-Key") != null) {
PublicKey key = KeyUtils.fromPemEncodedPublicKey(new String(Base64.getDecoder().decode(request.getHeader("X-Key")), UTF_8));
if (keyVerifies(key, request)) {
Principal principal = null;
Set<Role> roles = new HashSet<>();
Optional <Application> application = controller.applications().getApplication(TenantAndApplicationId.from(id));
if (application.isPresent() && application.get().deployKeys().contains(key)) {
principal = new SimplePrincipal("headless@" + id.tenant() + "." + id.application());
roles.add(Role.reader(id.tenant()));
roles.add(Role.headless(id.tenant(), id.application()));
}
Optional<CloudTenant> tenant = controller.tenants().get(id.tenant())
.filter(CloudTenant.class::isInstance)
.map(CloudTenant.class::cast);
if (tenant.isPresent() && tenant.get().developerKeys().containsKey(key)) {
principal = tenant.get().developerKeys().get(key);
roles.add(Role.reader(id.tenant()));
roles.add(Role.developer(id.tenant()));
}
if (principal != null)
securityContext = new SecurityContext(principal, roles);
}
}
else if (anyDeployKeyMatches(TenantAndApplicationId.from(id), request))
securityContext = new SecurityContext(new SimplePrincipal("buildService@" + id.tenant() + "." + id.application()),
Set.of(Role.buildService(id.tenant(), id.application())));
if (securityContext != null) {
request.setUserPrincipal(securityContext.principal());
request.setRemoteUser(securityContext.principal().getName());
request.setAttribute(SecurityContext.ATTRIBUTE_NAME, securityContext);
}
}
catch (Exception e) {
logger.log(LogLevel.DEBUG, () -> "Exception verifying signed request: " + Exceptions.toMessageString(e));
}
return Optional.empty();
} | } | protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
if ( request.getAttribute(SecurityContext.ATTRIBUTE_NAME) == null
&& request.getHeader("X-Authorization") != null)
try {
getSecurityContext(request).ifPresent(securityContext -> {
request.setUserPrincipal(securityContext.principal());
request.setRemoteUser(securityContext.principal().getName());
request.setAttribute(SecurityContext.ATTRIBUTE_NAME, securityContext);
});
}
catch (Exception e) {
logger.log(LogLevel.DEBUG, () -> "Exception verifying signed request: " + Exceptions.toMessageString(e));
}
return Optional.empty();
} | class SignatureFilter extends JsonSecurityRequestFilterBase {
private static final Logger logger = Logger.getLogger(SignatureFilter.class.getName());
private final Controller controller;
@Inject
public SignatureFilter(Controller controller) {
this.controller = controller;
}
@Override
private boolean anyDeployKeyMatches(TenantAndApplicationId id, DiscFilterRequest request) {
return controller.applications().getApplication(id).stream()
.map(Application::deployKeys)
.flatMap(Set::stream)
.anyMatch(key -> keyVerifies(key, request));
}
private boolean keyVerifies(PublicKey key, DiscFilterRequest request) {
return new RequestVerifier(key, controller.clock()).verify(Method.valueOf(request.getMethod()),
request.getUri(),
request.getHeader("X-Timestamp"),
request.getHeader("X-Content-Hash"),
request.getHeader("X-Authorization"));
}
private Optional<Principal> getPrincipal(CloudTenant tenant, PublicKey key) {
return Optional.empty();
}
} | class SignatureFilter extends JsonSecurityRequestFilterBase {
private static final Logger logger = Logger.getLogger(SignatureFilter.class.getName());
private final Controller controller;
@Inject
public SignatureFilter(Controller controller) {
this.controller = controller;
}
@Override
private boolean anyDeployKeyMatches(TenantAndApplicationId id, DiscFilterRequest request) {
return controller.applications().getApplication(id).stream()
.map(Application::deployKeys)
.flatMap(Set::stream)
.anyMatch(key -> keyVerifies(key, request));
}
private boolean keyVerifies(PublicKey key, DiscFilterRequest request) {
return new RequestVerifier(key, controller.clock()).verify(Method.valueOf(request.getMethod()),
request.getUri(),
request.getHeader("X-Timestamp"),
request.getHeader("X-Content-Hash"),
request.getHeader("X-Authorization"));
}
private Optional<SecurityContext> getSecurityContext(DiscFilterRequest request) {
ApplicationId id = ApplicationId.fromSerializedForm(request.getHeader("X-Key-Id"));
if (request.getHeader("X-Key") != null) {
PublicKey key = KeyUtils.fromPemEncodedPublicKey(new String(Base64.getDecoder().decode(request.getHeader("X-Key")), UTF_8));
if (keyVerifies(key, request)) {
Optional<CloudTenant> tenant = controller.tenants().get(id.tenant())
.filter(CloudTenant.class::isInstance)
.map(CloudTenant.class::cast);
if (tenant.isPresent() && tenant.get().developerKeys().containsKey(key))
return Optional.of(new SecurityContext(tenant.get().developerKeys().get(key),
Set.of(Role.reader(id.tenant()),
Role.developer(id.tenant()))));
Optional <Application> application = controller.applications().getApplication(TenantAndApplicationId.from(id));
if (application.isPresent() && application.get().deployKeys().contains(key))
return Optional.of(new SecurityContext(new SimplePrincipal("headless@" + id.tenant() + "." + id.application()),
Set.of(Role.reader(id.tenant()),
Role.developer(id.tenant()))));
}
}
else if (anyDeployKeyMatches(TenantAndApplicationId.from(id), request))
return Optional.of(new SecurityContext(new SimplePrincipal("headless@" + id.tenant() + "." + id.application()),
Set.of(Role.reader(id.tenant()),
Role.developer(id.tenant()))));
return Optional.empty();
}
} |
The intention is not to set it to the same as default config. If you set heapSize you need to ensure that heapSizeAsPercentageOfPhysicalMemory is 0. The fact that it is 0 in default config can change. Now that does not matter. I was not aware of ApplicationContainerCluster, at least not when memory percentage stuff was written. I will move it there, but as a separate PR. | public void getConfig(QrStartConfig.Builder builder) {
builder.jvm.heapsize(512);
builder.jvm.heapSizeAsPercentageOfPhysicalMemory(0);
builder.jvm.availableProcessors(2);
builder.jvm.verbosegc(false);
} | builder.jvm.heapSizeAsPercentageOfPhysicalMemory(0); | public void getConfig(QrStartConfig.Builder builder) {
builder.jvm
.verbosegc(false)
.availableProcessors(2)
.heapsize(512)
.heapSizeAsPercentageOfPhysicalMemory(0);
} | class ClusterControllerContainer extends Container implements
BundlesConfig.Producer,
ZookeeperServerConfig.Producer,
QrStartConfig.Producer
{
private static final ComponentSpecification CLUSTERCONTROLLER_BUNDLE = new ComponentSpecification("clustercontroller-apps");
private static final ComponentSpecification ZKFACADE_BUNDLE = new ComponentSpecification("zkfacade");
private final Set<String> bundles = new TreeSet<>();
public ClusterControllerContainer(AbstractConfigProducer parent, int index, boolean runStandaloneZooKeeper, boolean isHosted) {
super(parent, "" + index, index);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-status"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StatusHandler"),
CLUSTERCONTROLLER_BUNDLE))), "clustercontroller-status/*"
);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-state-restapi-v2"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StateRestApiV2Handler"),
CLUSTERCONTROLLER_BUNDLE))), "cluster/v2/*"
);
if (runStandaloneZooKeeper) {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkrunner"),
new ComponentSpecification("com.yahoo.vespa.zookeeper.ZooKeeperServer"), ZKFACADE_BUNDLE))));
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StandaloneZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
} else {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.DummyZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
}
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apps-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apputil-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-core-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-utils-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/zkfacade-jar-with-dependencies.jar"));
log.log(LogLevel.DEBUG, "Adding access log for cluster controller ...");
addComponent(new AccessLogComponent(AccessLogComponent.AccessLogType.jsonAccessLog, "controller", isHosted));
}
@Override
public int getWantedPort() {
return 19050;
}
@Override
public boolean requiresWantedPort() {
return index() == 0;
}
@Override
public ContainerServiceType myServiceType() {
return ContainerServiceType.CLUSTERCONTROLLER_CONTAINER;
}
private void addHandler(Handler h, String binding) {
h.addServerBindings("http:
super.addHandler(h);
}
public void addBundle(String bundlePath) {
bundles.add(bundlePath);
}
@Override
public void getConfig(BundlesConfig.Builder builder) {
for (String bundle : bundles) {
builder.bundle(bundle);
}
}
@Override
public void getConfig(ZookeeperServerConfig.Builder builder) {
builder.myid(index());
}
@Override
} | class ClusterControllerContainer extends Container implements
BundlesConfig.Producer,
ZookeeperServerConfig.Producer,
QrStartConfig.Producer
{
private static final ComponentSpecification CLUSTERCONTROLLER_BUNDLE = new ComponentSpecification("clustercontroller-apps");
private static final ComponentSpecification ZKFACADE_BUNDLE = new ComponentSpecification("zkfacade");
private final Set<String> bundles = new TreeSet<>();
public ClusterControllerContainer(AbstractConfigProducer parent, int index, boolean runStandaloneZooKeeper, boolean isHosted) {
super(parent, "" + index, index);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-status"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StatusHandler"),
CLUSTERCONTROLLER_BUNDLE))), "clustercontroller-status/*"
);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-state-restapi-v2"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StateRestApiV2Handler"),
CLUSTERCONTROLLER_BUNDLE))), "cluster/v2/*"
);
if (runStandaloneZooKeeper) {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkrunner"),
new ComponentSpecification("com.yahoo.vespa.zookeeper.ZooKeeperServer"), ZKFACADE_BUNDLE))));
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StandaloneZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
} else {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.DummyZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
}
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apps-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apputil-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-core-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-utils-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/zkfacade-jar-with-dependencies.jar"));
log.log(LogLevel.DEBUG, "Adding access log for cluster controller ...");
addComponent(new AccessLogComponent(AccessLogComponent.AccessLogType.jsonAccessLog, "controller", isHosted));
}
@Override
public int getWantedPort() {
return 19050;
}
@Override
public boolean requiresWantedPort() {
return index() == 0;
}
@Override
public ContainerServiceType myServiceType() {
return ContainerServiceType.CLUSTERCONTROLLER_CONTAINER;
}
private void addHandler(Handler h, String binding) {
h.addServerBindings("http:
super.addHandler(h);
}
public void addBundle(String bundlePath) {
bundles.add(bundlePath);
}
@Override
public void getConfig(BundlesConfig.Builder builder) {
for (String bundle : bundles) {
builder.bundle(bundle);
}
}
@Override
public void getConfig(ZookeeperServerConfig.Builder builder) {
builder.myid(index());
}
@Override
} |
The `Throwable.getMessage()` will be shown along with a 400 status code. Hopefully the message is good enough? | 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);
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant ->
controller.tenants().store(tenant.withDeveloperKey(developerKey, user)));
return new MessageResponse("Set developer key " + pemDeveloperKey + " for " + user);
} | PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey); | 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);
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant ->
controller.tenants().store(tenant.withDeveloperKey(developerKey, user)));
return new MessageResponse("Set developer key " + pemDeveloperKey + " for " + user);
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
}
@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/user")) return authenticatedUser(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"), "default", 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 application(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}/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}/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}/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/user")) return createUser(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"), "default", 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}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), 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"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createApplication(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/{ignored}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), path.get("instance"), 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}/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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), "default");
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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), path.get("instance"));
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}/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, "user", "tenant");
}
private HttpResponse authenticatedUser(HttpRequest request) {
Principal user = requireUserPrincipal(request);
if (user == null)
throw new NotAuthorizedException("You must be authenticated.");
String userName = user instanceof AthenzPrincipal ? ((AthenzPrincipal) user).getIdentity().getName() : user.getName();
TenantName tenantName = TenantName.from(UserTenant.normalizeUser(userName));
List<Tenant> tenants = controller.tenants().asList(new Credentials(user));
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setString("user", userName);
Cursor tenantsArray = response.setArray("tenants");
for (Tenant tenant : tenants)
tenantInTenantsListToSlime(tenant, request.getUri(), tenantsArray.addObject());
response.setBool("tenantExists", tenants.stream().anyMatch(tenant -> tenant.name().equals(tenantName)));
return new SlimeJsonResponse(slime);
}
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);
Slime slime = new Slime();
Cursor array = slime.setArray();
for (Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true))
for (InstanceName instance : application.instances().keySet())
toSlime(application.id().instance(instance), array.addObject(), request);
}
return new SlimeJsonResponse(slime);
}
private HttpResponse application(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
getApplication(tenantName, applicationName, instanceName), request);
return new SlimeJsonResponse(slime);
}
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);
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant ->
controller.tenants().store(tenant.withoutDeveloperKey(developerKey)));
return new MessageResponse("Removed developer key " + pemDeveloperKey + " for " + user);
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application ->
controller.applications().store(application.withDeployKey(deployKey)));
return new MessageResponse("Added deploy key " + pemDeployKey);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application ->
controller.applications().store(application.withoutDeployKey(deployKey)));
return new MessageResponse("Removed deploy key " + pemDeployKey);
}
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 Application getApplication(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
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()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.canonicalFlavor());
nodeObject.setDouble("vcpu", node.vcpu());
nodeObject.setDouble("memoryGb", node.memoryGb());
nodeObject.setDouble("diskGb", node.diskGb());
nodeObject.setDouble("bandwidthGbps", node.bandwidthGbps());
nodeObject.setBool("fastDisk", node.fastDisk());
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
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";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
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) {
String triggered = controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName())
.stream().map(JobType::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 void toSlime(Cursor object, Instance instance, Application application, HttpRequest request) {
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());
instance.deploymentJobs().statusOf(JobType.component)
.flatMap(JobStatus::lastSuccess)
.map(run -> run.application().source())
.ifPresent(source -> sourceRevisionToSlime(source, object.setObject("source")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if ( ! application.change().isEmpty()) {
toSlime(object.setObject("deploying"), application.change());
}
if ( ! application.outstandingChange().isEmpty()) {
toSlime(object.setObject("outstandingChange"), application.outstandingChange());
}
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedJobs(instance.deploymentJobs().jobStatus().values());
object.setBool("deployedInternally", application.internal());
Cursor deploymentsArray = object.setArray("deploymentJobs");
for (JobStatus job : jobStatus) {
Cursor jobObject = deploymentsArray.addObject();
jobObject.setString("type", job.type().jobName());
jobObject.setBool("success", job.isSuccess());
job.lastTriggered().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastTriggered")));
job.lastCompleted().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastCompleted")));
job.firstFailing().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("firstFailing")));
job.lastSuccess().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastSuccess")));
}
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().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);
});
object.setString("compileVersion", compileVersion(application.id()).toFullString());
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor globalRotationsArray = object.setArray("globalRotations");
instance.endpointsIn(controller.system())
.scope(Endpoint.Scope.global)
.legacy(false)
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
Set<RoutingPolicy> routingPolicies = controller.applications().routingPolicies().get(instance.id());
for (RoutingPolicy policy : routingPolicies) {
policy.rotationEndpointsIn(controller.system()).asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
}
List<Deployment> deployments = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedDeployments(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 (!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().getPath().contains("/instance/") ? "" : "/instance/" + instance.id().instance().value()),
request.getUri()).toString());
}
}
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(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 endpointArray = response.setArray("endpoints");
for (var policy : controller.applications().routingPolicies().get(deploymentId)) {
Cursor endpointObject = endpointArray.addObject();
Endpoint endpoint = policy.endpointIn(controller.system());
endpointObject.setString("cluster", policy.cluster().value());
endpointObject.setBool("tls", endpoint.tls());
endpointObject.setString("url", endpoint.url().toString());
}
Cursor serviceUrlArray = response.setArray("serviceUrls");
controller.applications().getDeploymentEndpoints(deploymentId)
.forEach(endpoint -> serviceUrlArray.addString(endpoint.toString()));
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()));
controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId())).projectId()
.ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
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));
DeploymentCost appCost = deployment.calculateCost();
Cursor costObject = response.setObject("cost");
toSlime(appCost, costObject);
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.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if ( ! revision.isPresent()) 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();
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
}
}
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);
return controller.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 -> ! controller.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);
}
Inspector requestData = toSlime(request.getData()).get();
String reason = mandatory("reason", requestData).asString();
String agent = requireUserPrincipal(request).getName();
long timestamp = controller.clock().instant().getEpochSecond();
EndpointStatus.Status status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
EndpointStatus endpointStatus = new EndpointStatus(status, reason, agent, timestamp);
controller.applications().setGlobalRotationStatus(new DeploymentId(instance.id(), deployment.zone()),
endpointStatus);
return new MessageResponse(String.format("Successfully set %s in %s.%s %s service",
instance.id().toShortString(),
deployment.zone().environment().value(),
deployment.zone().region().value(),
inService ? "in" : "out of"));
}
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");
Map<RoutingEndpoint, EndpointStatus> status = controller.applications().globalRotationStatus(deploymentId);
for (RoutingEndpoint endpoint : status.keySet()) {
EndpointStatus currentStatus = status.get(endpoint);
array.addString(endpoint.upstreamName());
Cursor statusObject = array.addObject();
statusObject.setString("status", currentStatus.getStatus().name());
statusObject.setString("reason", currentStatus.getReason() == null ? "" : currentStatus.getReason());
statusObject.setString("agent", currentStatus.getAgent() == null ? "" : currentStatus.getAgent());
statusObject.setLong("timestamp", currentStatus.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();
MeteringInfo meteringInfo = controller.serviceRegistry().meteringService().getResourceSnapshots(tenant, application);
ResourceAllocation currentSnapshot = meteringInfo.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringInfo.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringInfo.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 = meteringInfo.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 tenant, String application, String instance, HttpRequest request) {
Application app = controller.applications().requireApplication(TenantAndApplicationId.from(tenant, application));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! app.change().isEmpty()) {
app.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
app.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", app.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) {
Map<?,?> result = controller.getServiceApiResponse(tenantName, applicationName, instanceName, environment, region, serviceName, restPath);
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(result, serviceName, restPath);
return response;
}
private HttpResponse createUser(HttpRequest request) {
String user = Optional.of(requireUserPrincipal(request))
.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.map(AthenzIdentity::getName)
.map(UserTenant::normalizeUser)
.orElseThrow(() -> new ForbiddenException("Not authenticated or not a user."));
UserTenant tenant = UserTenant.create(user);
try {
controller.tenants().createUser(tenant);
return new MessageResponse("Created user '" + user + "'");
} catch (AlreadyExistsException e) {
return new MessageResponse("User '" + user + "' already exists");
}
}
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, String instanceName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
try {
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest()));
Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
catch (ZmsClientException e) {
if (e.getErrorCode() == com.yahoo.jdisc.Response.Status.FORBIDDEN)
throw new ForbiddenException("Not authorized to create application", e);
else
throw e;
}
}
/** 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());
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(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 " + change + " for " + 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);
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = Change.of(application.get().require(InstanceName.from(instanceName)).deploymentJobs().statusOf(JobType.component).get().lastSuccess().get().application());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered " + change + " for " + 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) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = application.get().change();
if (change.isEmpty()) {
response.append("No deployment in progress for " + application + " at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '" + change + "' to '" +
controller.applications().requireApplication(id).change() + "' for " + application);
});
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) {
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(),
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);
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<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,
application.get().internal(),
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,
application.get().internal(),
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass,
Optional.of(requireUserPrincipal(request)));
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if ( ! tenant.isPresent())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
if (tenant.get().type() == Tenant.Type.user)
controller.tenants().deleteUser((UserTenant) tenant.get());
else
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) {
TenantName tenant = TenantName.from(tenantName);
ApplicationName application = ApplicationName.from(applicationName);
Optional<Credentials> credentials = controller.tenants().require(tenant).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(tenant, toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteApplication(tenant, application, credentials);
return new MessageResponse("Deleted application " + tenant + "." + application);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteInstance(id, credentials);
return new MessageResponse("Deleted instance " + id.toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
DeploymentId deploymentId = new DeploymentId(instance.id(), ZoneId.from(environment, region));
controller.applications().deactivate(deploymentId.applicationId(), deploymentId.zoneId());
return new MessageResponse("Deactivated " + deploymentId);
}
private HttpResponse notifyJobCompletion(String tenant, String application, HttpRequest request) {
try {
DeploymentJobs.JobReport report = toJobReport(tenant, application, toSlime(request.getData()).get());
if ( report.jobType() == JobType.component
&& controller.applications().requireApplication(TenantAndApplicationId.from(report.applicationId())).internal())
throw new IllegalArgumentException(report.applicationId() + " is set up to be deployed from internally, and no " +
"longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.");
controller.applications().deploymentTrigger().notifyOfCompletion(report);
return new MessageResponse("ok");
} catch (IllegalStateException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
}
private HttpResponse testConfig(ApplicationId id, JobType type) {
var endpoints = controller.applications().clusterEndpoints(id, controller.jobController().testedZoneAndProductionZones(id, type));
return new SlimeJsonResponse(new TestConfigSerializer(controller.system()).configSlime(id,
type,
endpoints,
Collections.emptyMap()));
}
private static DeploymentJobs.JobReport toJobReport(String tenantName, String applicationName, Inspector report) {
Optional<DeploymentJobs.JobError> jobError = Optional.empty();
if (report.field("jobError").valid()) {
jobError = Optional.of(DeploymentJobs.JobError.valueOf(report.field("jobError").asString()));
}
ApplicationId id = ApplicationId.from(tenantName, applicationName, report.field("instance").asString());
JobType type = JobType.fromJobName(report.field("jobName").asString());
long buildNumber = report.field("buildNumber").asLong();
if (type == JobType.component)
return DeploymentJobs.JobReport.ofComponent(id,
report.field("projectId").asLong(),
buildNumber,
jobError,
toSourceRevision(report.field("sourceRevision")));
else
return DeploymentJobs.JobReport.ofJob(id, type, buildNumber, jobError);
}
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<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 user: break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
Cursor pemDeployKeysArray = object.setArray("pemDeployKeys");
for (Application application : applications)
for (PublicKey key : application.deployKeys()) {
Cursor keyObject = pemDeployKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("application", application.id().application().value());
}
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 (Application application : applications)
for (Instance instance : application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, application, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
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 user: 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(JobStatus.JobRun jobRun, Cursor object) {
object.setLong("id", jobRun.id());
object.setString("version", jobRun.platform().toFullString());
if (!jobRun.application().isUnknown())
toSlime(jobRun.application(), object.setObject("revision"));
object.setString("reason", jobRun.reason());
object.setLong("at", jobRun.at().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(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));
}
public static void toSlime(DeploymentCost deploymentCost, Cursor object) {
object.setLong("tco", (long)deploymentCost.getTco());
object.setLong("waste", (long)deploymentCost.getWaste());
object.setDouble("utilization", deploymentCost.getUtilization());
Cursor clustersObject = object.setObject("cluster");
for (Map.Entry<String, ClusterCost> clusterEntry : deploymentCost.getCluster().entrySet())
toSlime(clusterEntry.getValue(), clustersObject.setObject(clusterEntry.getKey()));
}
private static void toSlime(ClusterCost clusterCost, Cursor object) {
object.setLong("count", clusterCost.getClusterInfo().getHostnames().size());
object.setString("resource", getResourceName(clusterCost.getResultUtilization()));
object.setDouble("utilization", clusterCost.getResultUtilization().getMaxUtilization());
object.setLong("tco", (int)clusterCost.getTco());
object.setLong("waste", (int)clusterCost.getWaste());
object.setString("flavor", clusterCost.getClusterInfo().getFlavor());
object.setDouble("flavorCost", clusterCost.getClusterInfo().getFlavorCost());
object.setDouble("flavorCpu", clusterCost.getClusterInfo().getFlavorCPU());
object.setDouble("flavorMem", clusterCost.getClusterInfo().getFlavorMem());
object.setDouble("flavorDisk", clusterCost.getClusterInfo().getFlavorDisk());
object.setString("type", clusterCost.getClusterInfo().getClusterType().name());
Cursor utilObject = object.setObject("util");
utilObject.setDouble("cpu", clusterCost.getResultUtilization().getCpu());
utilObject.setDouble("mem", clusterCost.getResultUtilization().getMemory());
utilObject.setDouble("disk", clusterCost.getResultUtilization().getDisk());
utilObject.setDouble("diskBusy", clusterCost.getResultUtilization().getDiskBusy());
Cursor usageObject = object.setObject("usage");
usageObject.setDouble("cpu", clusterCost.getSystemUtilization().getCpu());
usageObject.setDouble("mem", clusterCost.getSystemUtilization().getMemory());
usageObject.setDouble("disk", clusterCost.getSystemUtilization().getDisk());
usageObject.setDouble("diskBusy", clusterCost.getSystemUtilization().getDiskBusy());
Cursor hostnamesArray = object.setArray("hostnames");
for (String hostname : clusterCost.getClusterInfo().getHostnames())
hostnamesArray.addString(hostname);
}
private static String getResourceName(ClusterUtilization utilization) {
String name = "cpu";
double max = utilization.getMaxUtilization();
if (utilization.getMemory() == max) {
name = "mem";
} else if (utilization.getDisk() == max) {
name = "disk";
} else if (utilization.getDiskBusy() == max) {
name = "diskbusy";
}
return name;
}
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 String tenantType(Tenant tenant) {
switch (tenant.type()) {
case user: return "USER";
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, String instance, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
SourceRevision sourceRevision = toSourceRevision(submitOptions);
String authorEmail = submitOptions.field("authorEmail").asString();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
instance,
sourceRevision,
authorEmail,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
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";
}
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
}
@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/user")) return authenticatedUser(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"), "default", 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 application(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}/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}/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}/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/user")) return createUser(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"), "default", 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}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), 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"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createApplication(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/{ignored}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), path.get("instance"), 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}/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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), "default");
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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), path.get("instance"));
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}/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, "user", "tenant");
}
private HttpResponse authenticatedUser(HttpRequest request) {
Principal user = requireUserPrincipal(request);
if (user == null)
throw new NotAuthorizedException("You must be authenticated.");
String userName = user instanceof AthenzPrincipal ? ((AthenzPrincipal) user).getIdentity().getName() : user.getName();
TenantName tenantName = TenantName.from(UserTenant.normalizeUser(userName));
List<Tenant> tenants = controller.tenants().asList(new Credentials(user));
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setString("user", userName);
Cursor tenantsArray = response.setArray("tenants");
for (Tenant tenant : tenants)
tenantInTenantsListToSlime(tenant, request.getUri(), tenantsArray.addObject());
response.setBool("tenantExists", tenants.stream().anyMatch(tenant -> tenant.name().equals(tenantName)));
return new SlimeJsonResponse(slime);
}
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);
Slime slime = new Slime();
Cursor array = slime.setArray();
for (Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true))
for (InstanceName instance : application.instances().keySet())
toSlime(application.id().instance(instance), array.addObject(), request);
}
return new SlimeJsonResponse(slime);
}
private HttpResponse application(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
getApplication(tenantName, applicationName, instanceName), request);
return new SlimeJsonResponse(slime);
}
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);
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant ->
controller.tenants().store(tenant.withoutDeveloperKey(developerKey)));
return new MessageResponse("Removed developer key " + pemDeveloperKey + " for " + user);
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application ->
controller.applications().store(application.withDeployKey(deployKey)));
return new MessageResponse("Added deploy key " + pemDeployKey);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application ->
controller.applications().store(application.withoutDeployKey(deployKey)));
return new MessageResponse("Removed deploy key " + pemDeployKey);
}
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 Application getApplication(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
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()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.canonicalFlavor());
nodeObject.setDouble("vcpu", node.vcpu());
nodeObject.setDouble("memoryGb", node.memoryGb());
nodeObject.setDouble("diskGb", node.diskGb());
nodeObject.setDouble("bandwidthGbps", node.bandwidthGbps());
nodeObject.setBool("fastDisk", node.fastDisk());
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
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";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
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) {
String triggered = controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName())
.stream().map(JobType::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 void toSlime(Cursor object, Instance instance, Application application, HttpRequest request) {
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());
instance.deploymentJobs().statusOf(JobType.component)
.flatMap(JobStatus::lastSuccess)
.map(run -> run.application().source())
.ifPresent(source -> sourceRevisionToSlime(source, object.setObject("source")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if ( ! application.change().isEmpty()) {
toSlime(object.setObject("deploying"), application.change());
}
if ( ! application.outstandingChange().isEmpty()) {
toSlime(object.setObject("outstandingChange"), application.outstandingChange());
}
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedJobs(instance.deploymentJobs().jobStatus().values());
object.setBool("deployedInternally", application.internal());
Cursor deploymentsArray = object.setArray("deploymentJobs");
for (JobStatus job : jobStatus) {
Cursor jobObject = deploymentsArray.addObject();
jobObject.setString("type", job.type().jobName());
jobObject.setBool("success", job.isSuccess());
job.lastTriggered().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastTriggered")));
job.lastCompleted().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastCompleted")));
job.firstFailing().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("firstFailing")));
job.lastSuccess().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastSuccess")));
}
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().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);
});
object.setString("compileVersion", compileVersion(application.id()).toFullString());
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor globalRotationsArray = object.setArray("globalRotations");
instance.endpointsIn(controller.system())
.scope(Endpoint.Scope.global)
.legacy(false)
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
Set<RoutingPolicy> routingPolicies = controller.applications().routingPolicies().get(instance.id());
for (RoutingPolicy policy : routingPolicies) {
policy.rotationEndpointsIn(controller.system()).asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
}
List<Deployment> deployments = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedDeployments(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 (!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().getPath().contains("/instance/") ? "" : "/instance/" + instance.id().instance().value()),
request.getUri()).toString());
}
}
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(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 endpointArray = response.setArray("endpoints");
for (var policy : controller.applications().routingPolicies().get(deploymentId)) {
Cursor endpointObject = endpointArray.addObject();
Endpoint endpoint = policy.endpointIn(controller.system());
endpointObject.setString("cluster", policy.cluster().value());
endpointObject.setBool("tls", endpoint.tls());
endpointObject.setString("url", endpoint.url().toString());
}
Cursor serviceUrlArray = response.setArray("serviceUrls");
controller.applications().getDeploymentEndpoints(deploymentId)
.forEach(endpoint -> serviceUrlArray.addString(endpoint.toString()));
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()));
controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId())).projectId()
.ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
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));
DeploymentCost appCost = deployment.calculateCost();
Cursor costObject = response.setObject("cost");
toSlime(appCost, costObject);
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.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if ( ! revision.isPresent()) 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();
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
}
}
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);
return controller.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 -> ! controller.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);
}
Inspector requestData = toSlime(request.getData()).get();
String reason = mandatory("reason", requestData).asString();
String agent = requireUserPrincipal(request).getName();
long timestamp = controller.clock().instant().getEpochSecond();
EndpointStatus.Status status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
EndpointStatus endpointStatus = new EndpointStatus(status, reason, agent, timestamp);
controller.applications().setGlobalRotationStatus(new DeploymentId(instance.id(), deployment.zone()),
endpointStatus);
return new MessageResponse(String.format("Successfully set %s in %s.%s %s service",
instance.id().toShortString(),
deployment.zone().environment().value(),
deployment.zone().region().value(),
inService ? "in" : "out of"));
}
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");
Map<RoutingEndpoint, EndpointStatus> status = controller.applications().globalRotationStatus(deploymentId);
for (RoutingEndpoint endpoint : status.keySet()) {
EndpointStatus currentStatus = status.get(endpoint);
array.addString(endpoint.upstreamName());
Cursor statusObject = array.addObject();
statusObject.setString("status", currentStatus.getStatus().name());
statusObject.setString("reason", currentStatus.getReason() == null ? "" : currentStatus.getReason());
statusObject.setString("agent", currentStatus.getAgent() == null ? "" : currentStatus.getAgent());
statusObject.setLong("timestamp", currentStatus.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();
MeteringInfo meteringInfo = controller.serviceRegistry().meteringService().getResourceSnapshots(tenant, application);
ResourceAllocation currentSnapshot = meteringInfo.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringInfo.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringInfo.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 = meteringInfo.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 tenant, String application, String instance, HttpRequest request) {
Application app = controller.applications().requireApplication(TenantAndApplicationId.from(tenant, application));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! app.change().isEmpty()) {
app.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
app.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", app.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) {
Map<?,?> result = controller.getServiceApiResponse(tenantName, applicationName, instanceName, environment, region, serviceName, restPath);
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(result, serviceName, restPath);
return response;
}
private HttpResponse createUser(HttpRequest request) {
String user = Optional.of(requireUserPrincipal(request))
.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.map(AthenzIdentity::getName)
.map(UserTenant::normalizeUser)
.orElseThrow(() -> new ForbiddenException("Not authenticated or not a user."));
UserTenant tenant = UserTenant.create(user);
try {
controller.tenants().createUser(tenant);
return new MessageResponse("Created user '" + user + "'");
} catch (AlreadyExistsException e) {
return new MessageResponse("User '" + user + "' already exists");
}
}
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, String instanceName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
try {
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest()));
Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
catch (ZmsClientException e) {
if (e.getErrorCode() == com.yahoo.jdisc.Response.Status.FORBIDDEN)
throw new ForbiddenException("Not authorized to create application", e);
else
throw e;
}
}
/** 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());
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(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 " + change + " for " + 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);
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = Change.of(application.get().require(InstanceName.from(instanceName)).deploymentJobs().statusOf(JobType.component).get().lastSuccess().get().application());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered " + change + " for " + 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) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = application.get().change();
if (change.isEmpty()) {
response.append("No deployment in progress for " + application + " at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '" + change + "' to '" +
controller.applications().requireApplication(id).change() + "' for " + application);
});
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) {
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(),
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);
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<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,
application.get().internal(),
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,
application.get().internal(),
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass,
Optional.of(requireUserPrincipal(request)));
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if ( ! tenant.isPresent())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
if (tenant.get().type() == Tenant.Type.user)
controller.tenants().deleteUser((UserTenant) tenant.get());
else
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) {
TenantName tenant = TenantName.from(tenantName);
ApplicationName application = ApplicationName.from(applicationName);
Optional<Credentials> credentials = controller.tenants().require(tenant).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(tenant, toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteApplication(tenant, application, credentials);
return new MessageResponse("Deleted application " + tenant + "." + application);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteInstance(id, credentials);
return new MessageResponse("Deleted instance " + id.toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
DeploymentId deploymentId = new DeploymentId(instance.id(), ZoneId.from(environment, region));
controller.applications().deactivate(deploymentId.applicationId(), deploymentId.zoneId());
return new MessageResponse("Deactivated " + deploymentId);
}
private HttpResponse notifyJobCompletion(String tenant, String application, HttpRequest request) {
try {
DeploymentJobs.JobReport report = toJobReport(tenant, application, toSlime(request.getData()).get());
if ( report.jobType() == JobType.component
&& controller.applications().requireApplication(TenantAndApplicationId.from(report.applicationId())).internal())
throw new IllegalArgumentException(report.applicationId() + " is set up to be deployed from internally, and no " +
"longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.");
controller.applications().deploymentTrigger().notifyOfCompletion(report);
return new MessageResponse("ok");
} catch (IllegalStateException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
}
private HttpResponse testConfig(ApplicationId id, JobType type) {
var endpoints = controller.applications().clusterEndpoints(id, controller.jobController().testedZoneAndProductionZones(id, type));
return new SlimeJsonResponse(new TestConfigSerializer(controller.system()).configSlime(id,
type,
endpoints,
Collections.emptyMap()));
}
private static DeploymentJobs.JobReport toJobReport(String tenantName, String applicationName, Inspector report) {
Optional<DeploymentJobs.JobError> jobError = Optional.empty();
if (report.field("jobError").valid()) {
jobError = Optional.of(DeploymentJobs.JobError.valueOf(report.field("jobError").asString()));
}
ApplicationId id = ApplicationId.from(tenantName, applicationName, report.field("instance").asString());
JobType type = JobType.fromJobName(report.field("jobName").asString());
long buildNumber = report.field("buildNumber").asLong();
if (type == JobType.component)
return DeploymentJobs.JobReport.ofComponent(id,
report.field("projectId").asLong(),
buildNumber,
jobError,
toSourceRevision(report.field("sourceRevision")));
else
return DeploymentJobs.JobReport.ofJob(id, type, buildNumber, jobError);
}
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<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 user: 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 (Application application : applications)
for (Instance instance : application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, application, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
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 user: 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(JobStatus.JobRun jobRun, Cursor object) {
object.setLong("id", jobRun.id());
object.setString("version", jobRun.platform().toFullString());
if (!jobRun.application().isUnknown())
toSlime(jobRun.application(), object.setObject("revision"));
object.setString("reason", jobRun.reason());
object.setLong("at", jobRun.at().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(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));
}
public static void toSlime(DeploymentCost deploymentCost, Cursor object) {
object.setLong("tco", (long)deploymentCost.getTco());
object.setLong("waste", (long)deploymentCost.getWaste());
object.setDouble("utilization", deploymentCost.getUtilization());
Cursor clustersObject = object.setObject("cluster");
for (Map.Entry<String, ClusterCost> clusterEntry : deploymentCost.getCluster().entrySet())
toSlime(clusterEntry.getValue(), clustersObject.setObject(clusterEntry.getKey()));
}
private static void toSlime(ClusterCost clusterCost, Cursor object) {
object.setLong("count", clusterCost.getClusterInfo().getHostnames().size());
object.setString("resource", getResourceName(clusterCost.getResultUtilization()));
object.setDouble("utilization", clusterCost.getResultUtilization().getMaxUtilization());
object.setLong("tco", (int)clusterCost.getTco());
object.setLong("waste", (int)clusterCost.getWaste());
object.setString("flavor", clusterCost.getClusterInfo().getFlavor());
object.setDouble("flavorCost", clusterCost.getClusterInfo().getFlavorCost());
object.setDouble("flavorCpu", clusterCost.getClusterInfo().getFlavorCPU());
object.setDouble("flavorMem", clusterCost.getClusterInfo().getFlavorMem());
object.setDouble("flavorDisk", clusterCost.getClusterInfo().getFlavorDisk());
object.setString("type", clusterCost.getClusterInfo().getClusterType().name());
Cursor utilObject = object.setObject("util");
utilObject.setDouble("cpu", clusterCost.getResultUtilization().getCpu());
utilObject.setDouble("mem", clusterCost.getResultUtilization().getMemory());
utilObject.setDouble("disk", clusterCost.getResultUtilization().getDisk());
utilObject.setDouble("diskBusy", clusterCost.getResultUtilization().getDiskBusy());
Cursor usageObject = object.setObject("usage");
usageObject.setDouble("cpu", clusterCost.getSystemUtilization().getCpu());
usageObject.setDouble("mem", clusterCost.getSystemUtilization().getMemory());
usageObject.setDouble("disk", clusterCost.getSystemUtilization().getDisk());
usageObject.setDouble("diskBusy", clusterCost.getSystemUtilization().getDiskBusy());
Cursor hostnamesArray = object.setArray("hostnames");
for (String hostname : clusterCost.getClusterInfo().getHostnames())
hostnamesArray.addString(hostname);
}
private static String getResourceName(ClusterUtilization utilization) {
String name = "cpu";
double max = utilization.getMaxUtilization();
if (utilization.getMemory() == max) {
name = "mem";
} else if (utilization.getDisk() == max) {
name = "disk";
} else if (utilization.getDiskBusy() == max) {
name = "diskbusy";
}
return name;
}
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 String tenantType(Tenant tenant) {
switch (tenant.type()) {
case user: return "USER";
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, String instance, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
SourceRevision sourceRevision = toSourceRevision(submitOptions);
String authorEmail = submitOptions.field("authorEmail").asString();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
instance,
sourceRevision,
authorEmail,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
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";
}
} |
Should have one with more instances, but I guess we need instance orchestration first :) | public void multiple_endpoints() {
tester.computeVersionStatus();
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();
ApplicationId id = createTenantAndApplication();
long projectId = 1;
MultiPartStreamer deployData = createApplicationDeployData(Optional.empty(), false);
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 100);
for (var job : List.of(JobType.productionUsWest1, JobType.productionUsEast3, JobType.productionEuWest1)) {
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/" + job.zone(SystemName.main).region().value() + "/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(job)
.application(id)
.projectId(projectId)
.submit();
}
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?endpointId=default", GET)
.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?endpointId=eu", GET)
.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?endpointId=eu", GET)
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"IN\"}}",
200);
} | .instances("instance1") | public void multiple_endpoints() {
tester.computeVersionStatus();
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();
ApplicationId id = createTenantAndApplication();
long projectId = 1;
MultiPartStreamer deployData = createApplicationDeployData(Optional.empty(), false);
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 100);
for (var job : List.of(JobType.productionUsWest1, JobType.productionUsEast3, JobType.productionEuWest1)) {
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/" + job.zone(SystemName.main).region().value() + "/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(job)
.application(id)
.projectId(projectId)
.submit();
}
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?endpointId=default", GET)
.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?endpointId=eu", GET)
.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?endpointId=eu", GET)
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"IN\"}}",
200);
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
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 HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("dummy");
private static final ZoneId TEST_ZONE = ZoneId.from(Environment.test, RegionName.from("us-east-1"));
private static final ZoneId STAGING_ZONE = ZoneId.from(Environment.staging, RegionName.from("us-east-3"));
private ContainerControllerTester controllerTester;
private ContainerTester tester;
@Before
public void before() {
controllerTester = new ContainerControllerTester(container, responseFiles);
tester = controllerTester.containerTester();
}
@Test
public void testApplicationApi() {
tester.computeVersionStatus();
tester.controller().jobController().setRunner(__ -> { });
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),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/user", GET).userIdentity(USER_ID),
new File("user.json"));
tester.assertResponse(request("/application/v4/user", PUT).userIdentity(USER_ID),
"{\"message\":\"Created user 'by-myuser'\"}");
tester.assertResponse(request("/application/v4/user", GET).userIdentity(USER_ID),
new File("user-which-exists.json"));
tester.assertResponse(request("/application/v4/tenant/by-myuser", DELETE).userIdentity(USER_ID),
"{\"tenant\":\"by-myuser\",\"type\":\"USER\",\"applications\":[]}");
tester.assertResponse(request("/application/v4/tenant/", GET).userIdentity(USER_ID),
new File("tenant-list.json"));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT)
.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)
.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),
new File("application-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"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
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)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(entity::data)))
.userIdentity(USER_ID),
new File("deploy-result.json"));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
long screwdriverProjectId = 123;
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value()));
controllerTester.jobCompletion(JobType.component)
.application(id)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackageInstance1)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/instance1/", POST)
.data(createApplicationDeployData(Optional.empty(), false))
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in test.us-east-1\"}");
controllerTester.jobCompletion(JobType.systemTest)
.application(id)
.projectId(screwdriverProjectId)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-east-3/instance/instance1/", POST)
.data(createApplicationDeployData(Optional.empty(), false))
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-east-3/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in staging.us-east-3\"}");
controllerTester.jobCompletion(JobType.stagingTest)
.application(id)
.projectId(screwdriverProjectId)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(createApplicationDeployData(Optional.empty(), false))
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsCentral1)
.application(id)
.projectId(screwdriverProjectId)
.unsuccessful()
.submit();
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(BuildJob.defaultSourceRevision,
BuildJob.defaultBuildNumber - 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),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1.instance1 with version 1.0.41-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(BuildJob.defaultSourceRevision,
BuildJob.defaultBuildNumber)),
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")
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application-reference-2.json"));
ApplicationId app2 = ApplicationId.from("tenant2", "application2", "default");
long screwdriverProjectId2 = 456;
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(app2.application().value()));
controllerTester.controller().applications().deploymentTrigger().triggerChange(TenantAndApplicationId.from(app2), Change.of(Version.fromString("7.0")));
controllerTester.jobCompletion(JobType.component)
.application(app2)
.projectId(screwdriverProjectId2)
.uploadArtifact(applicationPackage)
.submit();
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\":\"-----BEGIN PUBLIC KEY-----\n∠( ᐛ 」∠)_\n-----END PUBLIC KEY-----\"}"),
"{\"message\":\"Added deploy key -----BEGIN PUBLIC KEY-----\\n∠( ᐛ 」∠)_\\n-----END PUBLIC KEY-----\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", PATCH)
.userIdentity(USER_ID)
.data("{\"pemDeployKey\":\"-----BEGIN PUBLIC KEY-----\n∠( ᐛ 」∠)_\n-----END PUBLIC KEY-----\"}"),
"{\"message\":\"Added deploy key -----BEGIN PUBLIC KEY-----\\n∠( ᐛ 」∠)_\\n-----END PUBLIC KEY-----\"}");
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/key", DELETE)
.userIdentity(USER_ID)
.data("{\"key\":\"-----BEGIN PUBLIC KEY-----\\n∠( ᐛ 」∠)_\\n-----END PUBLIC KEY-----\"}"),
"{\"message\":\"Removed deploy key -----BEGIN PUBLIC KEY-----\\n∠( ᐛ 」∠)_\\n-----END PUBLIC KEY-----\"}");
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", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
"{\"message\":\"Deleted application tenant2.application2\"}");
controllerTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
tester.computeVersionStatus();
setDeploymentMaintainedInfo(controllerTester);
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("application.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(controllerTester, 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("application1-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/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.42-commit1' to 'no change' for application 'tenant1.application1'\"}");
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 application 'tenant1.application1' 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\"}");
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 application 'tenant1.application1'\"}");
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\"}");
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 application 'tenant1.application1'\"}");
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 application 'tenant1.application1'\"}");
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", 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)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
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?hostname=host1", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"error-code\":\"INTERNAL_SERVER_ERROR\",\"message\":\"No node with the hostname host1 is known.\"}", 500);
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),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-west-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.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1", POST)
.userIdentity(USER_ID)
.data(createApplicationDeployData(applicationPackage, false)),
new File("deployment-job-accepted.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage)),
"{\"message\":\"Application package version: 1.0.43-d00d, source revision of repository 'repo', branch 'master' with commit 'd00d', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
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();
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService)),
"{\"message\":\"Application package version: 1.0.44-d00d, source revision of repository 'repo', branch 'master' with commit 'd00d', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
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)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService);
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.45-d00d, source revision of repository 'repo', branch 'master' with commit 'd00d', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationId app1 = ApplicationId.from("tenant1", "application1", "instance1");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/jobreport", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(asJson(DeploymentJobs.JobReport.ofComponent(app1,
1234,
123,
Optional.empty(),
BuildJob.defaultSourceRevision))),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"" + app1 + " is set up to be deployed from internally," +
" and no longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.\"}",
400);
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/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 1 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Unregistered 'tenant1.application1.instance1' from internal deployment pipeline.\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/jobreport", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(asJson(DeploymentJobs.JobReport.ofComponent(app1,
1234,
123,
Optional.empty(),
BuildJob.defaultSourceRevision))),
"{\"message\":\"ok\"}");
byte[] data = new byte[0];
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.data(data)
.userIdentity(new UserId("new_user")),
new File("create-user-response.json"));
tester.assertResponse(request("/application/v4/user", GET)
.userIdentity(new UserId("other_user")),
"{\"user\":\"other_user\",\"tenants\":[],\"tenantExists\":false}");
tester.assertResponse(request("/application/v4/", Request.Method.OPTIONS)
.userIdentity(USER_ID),
"");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("tenant-without-applications.json"));
}
private void addIssues(ContainerControllerTester tester, TenantAndApplicationId id) {
tester.controller().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() {
tester.computeVersionStatus();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
ApplicationId id = createTenantAndApplication();
long projectId = 1;
MultiPartStreamer deployData = createApplicationDeployData(Optional.of(applicationPackage), false);
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 100);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsWest1)
.application(id)
.projectId(projectId)
.submit();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
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-east-3/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-east-3\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-east-3/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-east-3\"}",
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"));
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"));
}
@Test
@Test
public void testDeployDirectly() {
tester.computeVersionStatus();
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),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId("application1"));
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);
tester.upgradeSystem(tester.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 testSortsDeploymentsAndJobs() {
tester.computeVersionStatus();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-east-3")
.build();
ApplicationId id = createTenantAndApplication();
long projectId = 1;
MultiPartStreamer deployData = createApplicationDeployData(Optional.empty(), false);
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 100);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-east-3/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsEast3)
.application(id)
.projectId(projectId)
.submit();
applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 101);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsWest1)
.application(id)
.projectId(projectId)
.submit();
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-east-3/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsEast3)
.application(id)
.projectId(projectId)
.submit();
setDeploymentMaintainedInfo(controllerTester);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("application-without-change-multiple-deployments.json"));
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = (MockMeteringClient) controllerTester.containerTester().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)),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246)),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492))));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application1-metering.json"));
}
@Test
public void testErrorResponses() throws Exception {
tester.computeVersionStatus();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT)
.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/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),
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),
"{\"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)
.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),
"{\"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/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz tenant name cannot have prefix 'by-'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/hosted-vespa", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT),
"{\"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),
new File("application-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Application already exists\"}",
400);
ConfigServerMock configServer = serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
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", 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", 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"), "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),
"{\"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),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete application 'tenant1.application1.instance1': Application not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
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),
"{\"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)
.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),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT),
"{\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),
new File("application-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),
new File("application-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete application; more than one instance present: [tenant1.application1, tenant1.application1.instance1]\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT),
"{\"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),
"{\"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 deployment_fails_on_illegal_domain_in_deployment_spec() {
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();
long screwdriverProjectId = 123;
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"), true);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
}
@Test
public void deployment_succeeds_when_correct_domain_is_used() {
ApplicationPackage 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();
long screwdriverProjectId = 123;
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
new File("deploy-result.json"));
}
@Test
public void deployment_fails_for_personal_tenants_when_athenzdomain_specified_and_user_not_admin() {
tester.computeVersionStatus();
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
byte[] data = new byte[0];
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.data(data)
.userIdentity(userId),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.dev)
.region("us-west-1")
.build();
String expectedResult="{\"error-code\":\"BAD_REQUEST\",\"message\":\"User user.new-user is not allowed to launch services in Athenz domain domain1. Please reach out to the domain admin.\"}";
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(userId),
expectedResult,
400);
}
@Test
public void deployment_succeeds_for_personal_tenants_when_user_is_tenant_admin() {
tester.computeVersionStatus();
UserId tenantAdmin = new UserId("new_user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
byte[] data = new byte[0];
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.data(data)
.userIdentity(tenantAdmin),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.dev)
.region("us-west-1")
.build();
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(tenantAdmin),
new File("deploy-result.json"));
}
@Test
public void deployment_fails_when_athenz_service_cannot_be_launched() {
ApplicationPackage 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();
long screwdriverProjectId = 123;
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), false);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
String expectedResult="{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}";
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
expectedResult,
400);
}
@Test
public void redeployment_succeeds_when_not_specifying_versions_or_application_package() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.computeVersionStatus();
ApplicationPackage 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();
long screwdriverProjectId = 123;
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(Optional.empty(), true))
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
}
@Test
public void testJobStatusReporting() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.computeVersionStatus();
long projectId = 1;
Application app = controllerTester.createApplication();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-central-1")
.build();
Version vespaVersion = new Version("6.1");
BuildJob job = new BuildJob(report -> notifyCompletion(report, controllerTester), controllerTester.containerTester().serviceRegistry().artifactRepositoryMock())
.application(app)
.projectId(projectId);
job.type(JobType.component).uploadArtifact(applicationPackage).submit();
controllerTester.deploy(app.id().defaultInstance(), applicationPackage, TEST_ZONE);
job.type(JobType.systemTest).submit();
Request request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(asJson(job.type(JobType.systemTest).report()))
.userIdentity(HOSTED_VESPA_OPERATOR)
.get();
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of system-test for tenant1.application1, but that has not been triggered; last was " +
controllerTester.controller().applications().requireInstance(app.id().defaultInstance()).deploymentJobs().jobStatus().get(JobType.systemTest).lastTriggered().get().at() + "\"}", 400);
request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(asJson(job.type(JobType.productionUsEast3).report()))
.userIdentity(HOSTED_VESPA_OPERATOR)
.get();
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of production-us-east-3 for tenant1.application1, but that has not been triggered; last was never\"}",
400);
JobStatus recordedStatus =
tester.controller().applications().getInstance(app.id().defaultInstance()).get().deploymentJobs().jobStatus().get(JobType.component);
assertNotNull("Status was recorded", recordedStatus);
assertTrue(recordedStatus.isSuccess());
assertEquals(vespaVersion, recordedStatus.lastCompleted().get().platform());
recordedStatus =
tester.controller().applications().getInstance(app.id().defaultInstance()).get().deploymentJobs().jobStatus().get(JobType.productionApNortheast2);
assertNull("Status of never-triggered jobs is empty", recordedStatus);
assertTrue("All jobs have been run", tester.controller().applications().deploymentTrigger().jobsToRun().isEmpty());
}
@Test
public void testJobStatusReportingOutOfCapacity() {
controllerTester.containerTester().computeVersionStatus();
long projectId = 1;
Application app = controllerTester.createApplication();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-central-1")
.build();
BuildJob job = new BuildJob(report -> notifyCompletion(report, controllerTester), controllerTester.containerTester().serviceRegistry().artifactRepositoryMock())
.application(app)
.projectId(projectId);
job.type(JobType.component).uploadArtifact(applicationPackage).submit();
controllerTester.deploy(app.id().defaultInstance(), applicationPackage, TEST_ZONE);
job.type(JobType.systemTest).submit();
controllerTester.deploy(app.id().defaultInstance(), applicationPackage, STAGING_ZONE);
job.type(JobType.stagingTest).error(DeploymentJobs.JobError.outOfCapacity).submit();
JobStatus jobStatus = tester.controller().applications().getInstance(app.id().defaultInstance()).get()
.deploymentJobs()
.jobStatus()
.get(JobType.stagingTest);
assertFalse(jobStatus.isSuccess());
assertEquals(DeploymentJobs.JobError.outOfCapacity, jobStatus.jobError().get());
}
@Test
public void applicationWithRoutingPolicy() {
Application app = controllerTester.createApplication();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
controllerTester.deployCompletely(app, applicationPackage, 1, false);
RoutingPolicy policy = new RoutingPolicy(app.id().defaultInstance(),
ClusterSpec.Id.from("default"),
ZoneId.from(Environment.prod, RegionName.from("us-west-1")),
HostName.from("lb-0-canonical-name"),
Optional.of("dns-zone-1"), Set.of(EndpointId.of("c0")));
tester.controller().curator().writeRoutingPolicies(app.id().defaultInstance(), Set.of(policy));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
new File("application-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private void notifyCompletion(DeploymentJobs.JobReport report, ContainerControllerTester tester) {
assertResponse(request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.userIdentity(HOSTED_VESPA_OPERATOR)
.data(asJson(report))
.get(),
200, "{\"message\":\"ok\"}");
tester.controller().applications().deploymentTrigger().triggerReadyJobs();
}
private static byte[] asJson(DeploymentJobs.JobReport report) {
Slime slime = new Slime();
Cursor cursor = slime.setObject();
cursor.setLong("projectId", report.projectId());
cursor.setString("jobName", report.jobType().jobName());
cursor.setLong("buildNumber", report.buildNumber());
report.jobError().ifPresent(jobError -> cursor.setString("jobError", jobError.name()));
report.version().flatMap(ApplicationVersion::source).ifPresent(sr -> {
Cursor sourceRevision = cursor.setObject("sourceRevision");
sourceRevision.setString("repository", sr.repository());
sourceRevision.setString("branch", sr.branch());
sourceRevision.setString("commit", sr.commit());
});
cursor.setString("tenant", report.applicationId().tenant().value());
cursor.setString("application", report.applicationId().application().value());
cursor.setString("instance", report.applicationId().instance().value());
try {
return SlimeUtils.toJsonBytes(slime);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
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;
}
private MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repo\",\"branch\":\"master\",\"commit\":\"d00d\",\"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) {
AthenzClientFactoryMock mock = (AthenzClientFactoryMock) container.components()
.getComponent(AthenzClientFactoryMock.class.getName());
AthenzDbMock.Domain domainMock = mock.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 configureAthenzIdentity(com.yahoo.vespa.athenz.api.AthenzService service, boolean allowLaunch) {
AthenzClientFactoryMock mock = (AthenzClientFactoryMock) container.components()
.getComponent(AthenzClientFactoryMock.class.getName());
AthenzDbMock.Domain domainMock = mock.getSetup().domains.computeIfAbsent(service.getDomain(), AthenzDbMock.Domain::new);
domainMock.services.put(service.getName(), new AthenzDbMock.Service(allowLaunch));
}
/**
* 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,
com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId applicationId) {
AthenzClientFactoryMock mock = (AthenzClientFactoryMock) container.components()
.getComponent(AthenzClientFactoryMock.class.getName());
AthenzIdentity screwdriverIdentity = HostedAthenzIdentities.from(screwdriverId);
AthenzDbMock.Application athenzApplication = mock.getSetup().domains.get(domain).applications.get(applicationId);
athenzApplication.addRoleMember(ApplicationAction.deploy, screwdriverIdentity);
}
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),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
private void startAndTestChange(ContainerControllerTester controllerTester, ApplicationId application,
long projectId, ApplicationPackage applicationPackage,
MultiPartStreamer deployData, long buildNumber) {
ContainerTester tester = controllerTester.containerTester();
controllerTester.containerTester().serviceRegistry().artifactRepositoryMock()
.put(application, applicationPackage,"1.0." + buildNumber + "-commit1");
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(projectId)
.buildNumber(buildNumber)
.submit();
String testPath = String.format("/application/v4/tenant/%s/application/%s/instance/%s/environment/test/region/us-east-1",
application.tenant().value(), application.application().value(), application.instance().value());
tester.assertResponse(request(testPath, POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request(testPath, DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated " + application + " in test.us-east-1\"}");
controllerTester.jobCompletion(JobType.systemTest)
.application(application)
.projectId(projectId)
.submit();
String stagingPath = String.format("/application/v4/tenant/%s/application/%s/instance/%s/environment/staging/region/us-east-3",
application.tenant().value(), application.application().value(), application.instance().value());
tester.assertResponse(request(stagingPath, POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request(stagingPath, DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated " + application + " in staging.us-east-3\"}");
controllerTester.jobCompletion(JobType.stagingTest)
.application(application)
.projectId(projectId)
.submit();
}
/**
* 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(ContainerControllerTester controllerTester) {
for (Application application : controllerTester.controller().applications().asList()) {
controllerTester.controller().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()) {
Map<ClusterSpec.Id, ClusterInfo> clusterInfo = new HashMap<>();
List<String> hostnames = new ArrayList<>();
hostnames.add("host1");
hostnames.add("host2");
clusterInfo.put(ClusterSpec.Id.from("cluster1"),
new ClusterInfo("flavor1", 37, 2, 4, 50,
ClusterSpec.Type.content, hostnames));
Map<ClusterSpec.Id, ClusterUtilization> clusterUtils = new HashMap<>();
clusterUtils.put(ClusterSpec.Id.from("cluster1"), new ClusterUtilization(0.3, 0.6, 0.4, 0.3));
DeploymentMetrics metrics = new DeploymentMetrics(1, 2, 3, 4, 5,
Optional.of(Instant.ofEpochMilli(123123)), Map.of());
lockedApplication = lockedApplication.with(instance.name(),
lockedInstance -> lockedInstance.withClusterInfo(deployment.zone(), clusterInfo)
.withClusterUtilization(deployment.zone(), clusterUtils)
.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
controllerTester.controller().applications().store(lockedApplication);
}
});
}
}
private ServiceRegistryMock serviceRegistry() {
return (ServiceRegistryMock) tester.container().components().getComponent(ServiceRegistryMock.class.getName());
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator())).run();
}
private RotationStatus rotationStatus(Instance instance) {
return controllerTester.controller().applications().rotationRepository().getRotation(instance)
.map(rotation -> {
var rotationStatus = controllerTester.controller().serviceRegistry().globalRoutingService().getHealthStatus(rotation.name());
var statusMap = new LinkedHashMap<ZoneId, RotationState>();
rotationStatus.forEach((zone, status) -> statusMap.put(zone, RotationState.in));
return RotationStatus.from(Map.of(rotation.id(), statusMap));
})
.orElse(RotationStatus.EMPTY);
}
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));
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 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 OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private Map<String, List<String>> headers = new HashMap<>();
private String recursive;
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(StandardCharsets.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 oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { this.recursive = recursive; 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:
(recursive == null ? "" : "?recursive=" + recursive),
data, method);
request.getHeaders().addAll(headers);
request.getHeaders().put("Content-Type", contentType);
if (identity != null) {
addIdentityToRequest(request, identity);
}
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 HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("dummy");
private static final ZoneId TEST_ZONE = ZoneId.from(Environment.test, RegionName.from("us-east-1"));
private static final ZoneId STAGING_ZONE = ZoneId.from(Environment.staging, RegionName.from("us-east-3"));
private ContainerControllerTester controllerTester;
private ContainerTester tester;
@Before
public void before() {
controllerTester = new ContainerControllerTester(container, responseFiles);
tester = controllerTester.containerTester();
}
@Test
public void testApplicationApi() {
tester.computeVersionStatus();
tester.controller().jobController().setRunner(__ -> { });
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),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/user", GET).userIdentity(USER_ID),
new File("user.json"));
tester.assertResponse(request("/application/v4/user", PUT).userIdentity(USER_ID),
"{\"message\":\"Created user 'by-myuser'\"}");
tester.assertResponse(request("/application/v4/user", GET).userIdentity(USER_ID),
new File("user-which-exists.json"));
tester.assertResponse(request("/application/v4/tenant/by-myuser", DELETE).userIdentity(USER_ID),
"{\"tenant\":\"by-myuser\",\"type\":\"USER\",\"applications\":[]}");
tester.assertResponse(request("/application/v4/tenant/", GET).userIdentity(USER_ID),
new File("tenant-list.json"));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT)
.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)
.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),
new File("application-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"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
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)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(entity::data)))
.userIdentity(USER_ID),
new File("deploy-result.json"));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
long screwdriverProjectId = 123;
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value()));
controllerTester.jobCompletion(JobType.component)
.application(id)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackageInstance1)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/instance1/", POST)
.data(createApplicationDeployData(Optional.empty(), false))
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in test.us-east-1\"}");
controllerTester.jobCompletion(JobType.systemTest)
.application(id)
.projectId(screwdriverProjectId)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-east-3/instance/instance1/", POST)
.data(createApplicationDeployData(Optional.empty(), false))
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-east-3/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in staging.us-east-3\"}");
controllerTester.jobCompletion(JobType.stagingTest)
.application(id)
.projectId(screwdriverProjectId)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(createApplicationDeployData(Optional.empty(), false))
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsCentral1)
.application(id)
.projectId(screwdriverProjectId)
.unsuccessful()
.submit();
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(BuildJob.defaultSourceRevision,
BuildJob.defaultBuildNumber - 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),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1.instance1 with version 1.0.41-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(BuildJob.defaultSourceRevision,
BuildJob.defaultBuildNumber)),
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")
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application-reference-2.json"));
ApplicationId app2 = ApplicationId.from("tenant2", "application2", "default");
long screwdriverProjectId2 = 456;
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(app2.application().value()));
controllerTester.controller().applications().deploymentTrigger().triggerChange(TenantAndApplicationId.from(app2), Change.of(Version.fromString("7.0")));
controllerTester.jobCompletion(JobType.component)
.application(app2)
.projectId(screwdriverProjectId2)
.uploadArtifact(applicationPackage)
.submit();
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/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", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
"{\"message\":\"Deleted application tenant2.application2\"}");
controllerTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
tester.computeVersionStatus();
setDeploymentMaintainedInfo(controllerTester);
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("application.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(controllerTester, 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("application1-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/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.42-commit1' to 'no change' for application 'tenant1.application1'\"}");
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 application 'tenant1.application1' 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\"}");
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 application 'tenant1.application1'\"}");
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\"}");
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 application 'tenant1.application1'\"}");
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 application 'tenant1.application1'\"}");
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", 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)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
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?hostname=host1", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"error-code\":\"INTERNAL_SERVER_ERROR\",\"message\":\"No node with the hostname host1 is known.\"}", 500);
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),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-west-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.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1", POST)
.userIdentity(USER_ID)
.data(createApplicationDeployData(applicationPackage, false)),
new File("deployment-job-accepted.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage)),
"{\"message\":\"Application package version: 1.0.43-d00d, source revision of repository 'repo', branch 'master' with commit 'd00d', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
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();
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService)),
"{\"message\":\"Application package version: 1.0.44-d00d, source revision of repository 'repo', branch 'master' with commit 'd00d', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
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)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService);
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.45-d00d, source revision of repository 'repo', branch 'master' with commit 'd00d', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationId app1 = ApplicationId.from("tenant1", "application1", "instance1");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/jobreport", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(asJson(DeploymentJobs.JobReport.ofComponent(app1,
1234,
123,
Optional.empty(),
BuildJob.defaultSourceRevision))),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"" + app1 + " is set up to be deployed from internally," +
" and no longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.\"}",
400);
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/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 1 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Unregistered 'tenant1.application1.instance1' from internal deployment pipeline.\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/jobreport", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(asJson(DeploymentJobs.JobReport.ofComponent(app1,
1234,
123,
Optional.empty(),
BuildJob.defaultSourceRevision))),
"{\"message\":\"ok\"}");
byte[] data = new byte[0];
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.data(data)
.userIdentity(new UserId("new_user")),
new File("create-user-response.json"));
tester.assertResponse(request("/application/v4/user", GET)
.userIdentity(new UserId("other_user")),
"{\"user\":\"other_user\",\"tenants\":[],\"tenantExists\":false}");
tester.assertResponse(request("/application/v4/", Request.Method.OPTIONS)
.userIdentity(USER_ID),
"");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("tenant-without-applications.json"));
}
private void addIssues(ContainerControllerTester tester, TenantAndApplicationId id) {
tester.controller().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() {
tester.computeVersionStatus();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
ApplicationId id = createTenantAndApplication();
long projectId = 1;
MultiPartStreamer deployData = createApplicationDeployData(Optional.of(applicationPackage), false);
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 100);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsWest1)
.application(id)
.projectId(projectId)
.submit();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
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-east-3/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-east-3\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-east-3/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-east-3\"}",
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"));
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"));
}
@Test
@Test
public void testDeployDirectly() {
tester.computeVersionStatus();
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),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId("application1"));
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);
tester.upgradeSystem(tester.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 testSortsDeploymentsAndJobs() {
tester.computeVersionStatus();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-east-3")
.build();
ApplicationId id = createTenantAndApplication();
long projectId = 1;
MultiPartStreamer deployData = createApplicationDeployData(Optional.empty(), false);
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 100);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-east-3/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsEast3)
.application(id)
.projectId(projectId)
.submit();
applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 101);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsWest1)
.application(id)
.projectId(projectId)
.submit();
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-east-3/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsEast3)
.application(id)
.projectId(projectId)
.submit();
setDeploymentMaintainedInfo(controllerTester);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("application-without-change-multiple-deployments.json"));
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = (MockMeteringClient) controllerTester.containerTester().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)),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246)),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492))));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application1-metering.json"));
}
@Test
public void testErrorResponses() throws Exception {
tester.computeVersionStatus();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT)
.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/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),
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),
"{\"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)
.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),
"{\"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/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz tenant name cannot have prefix 'by-'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/hosted-vespa", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT),
"{\"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),
new File("application-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
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", 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", 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"), "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),
"{\"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),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT)
.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),
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),
"{\"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)
.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),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT),
"{\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),
new File("application-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),
new File("application-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete application; more than one instance present: [tenant1.application1, tenant1.application1.instance1]\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT),
"{\"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),
"{\"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 deployment_fails_on_illegal_domain_in_deployment_spec() {
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();
long screwdriverProjectId = 123;
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"), true);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
}
@Test
public void deployment_succeeds_when_correct_domain_is_used() {
ApplicationPackage 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();
long screwdriverProjectId = 123;
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
new File("deploy-result.json"));
}
@Test
public void deployment_fails_for_personal_tenants_when_athenzdomain_specified_and_user_not_admin() {
tester.computeVersionStatus();
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
byte[] data = new byte[0];
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.data(data)
.userIdentity(userId),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.dev)
.region("us-west-1")
.build();
String expectedResult="{\"error-code\":\"BAD_REQUEST\",\"message\":\"User user.new-user is not allowed to launch services in Athenz domain domain1. Please reach out to the domain admin.\"}";
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(userId),
expectedResult,
400);
}
@Test
public void deployment_succeeds_for_personal_tenants_when_user_is_tenant_admin() {
tester.computeVersionStatus();
UserId tenantAdmin = new UserId("new_user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
byte[] data = new byte[0];
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.data(data)
.userIdentity(tenantAdmin),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.dev)
.region("us-west-1")
.build();
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(tenantAdmin),
new File("deploy-result.json"));
}
@Test
public void deployment_fails_when_athenz_service_cannot_be_launched() {
ApplicationPackage 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();
long screwdriverProjectId = 123;
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), false);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
String expectedResult="{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}";
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
expectedResult,
400);
}
@Test
public void redeployment_succeeds_when_not_specifying_versions_or_application_package() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.computeVersionStatus();
ApplicationPackage 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();
long screwdriverProjectId = 123;
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(Optional.empty(), true))
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
}
@Test
public void testJobStatusReporting() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.computeVersionStatus();
long projectId = 1;
Application app = controllerTester.createApplication();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-central-1")
.build();
Version vespaVersion = new Version("6.1");
BuildJob job = new BuildJob(report -> notifyCompletion(report, controllerTester), controllerTester.containerTester().serviceRegistry().artifactRepositoryMock())
.application(app)
.projectId(projectId);
job.type(JobType.component).uploadArtifact(applicationPackage).submit();
controllerTester.deploy(app.id().defaultInstance(), applicationPackage, TEST_ZONE);
job.type(JobType.systemTest).submit();
Request request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(asJson(job.type(JobType.systemTest).report()))
.userIdentity(HOSTED_VESPA_OPERATOR)
.get();
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of system-test for tenant1.application1, but that has not been triggered; last was " +
controllerTester.controller().applications().requireInstance(app.id().defaultInstance()).deploymentJobs().jobStatus().get(JobType.systemTest).lastTriggered().get().at() + "\"}", 400);
request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(asJson(job.type(JobType.productionUsEast3).report()))
.userIdentity(HOSTED_VESPA_OPERATOR)
.get();
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of production-us-east-3 for tenant1.application1, but that has not been triggered; last was never\"}",
400);
JobStatus recordedStatus =
tester.controller().applications().getInstance(app.id().defaultInstance()).get().deploymentJobs().jobStatus().get(JobType.component);
assertNotNull("Status was recorded", recordedStatus);
assertTrue(recordedStatus.isSuccess());
assertEquals(vespaVersion, recordedStatus.lastCompleted().get().platform());
recordedStatus =
tester.controller().applications().getInstance(app.id().defaultInstance()).get().deploymentJobs().jobStatus().get(JobType.productionApNortheast2);
assertNull("Status of never-triggered jobs is empty", recordedStatus);
assertTrue("All jobs have been run", tester.controller().applications().deploymentTrigger().jobsToRun().isEmpty());
}
@Test
public void testJobStatusReportingOutOfCapacity() {
controllerTester.containerTester().computeVersionStatus();
long projectId = 1;
Application app = controllerTester.createApplication();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-central-1")
.build();
BuildJob job = new BuildJob(report -> notifyCompletion(report, controllerTester), controllerTester.containerTester().serviceRegistry().artifactRepositoryMock())
.application(app)
.projectId(projectId);
job.type(JobType.component).uploadArtifact(applicationPackage).submit();
controllerTester.deploy(app.id().defaultInstance(), applicationPackage, TEST_ZONE);
job.type(JobType.systemTest).submit();
controllerTester.deploy(app.id().defaultInstance(), applicationPackage, STAGING_ZONE);
job.type(JobType.stagingTest).error(DeploymentJobs.JobError.outOfCapacity).submit();
JobStatus jobStatus = tester.controller().applications().getInstance(app.id().defaultInstance()).get()
.deploymentJobs()
.jobStatus()
.get(JobType.stagingTest);
assertFalse(jobStatus.isSuccess());
assertEquals(DeploymentJobs.JobError.outOfCapacity, jobStatus.jobError().get());
}
@Test
public void applicationWithRoutingPolicy() {
Application app = controllerTester.createApplication();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
controllerTester.deployCompletely(app, applicationPackage, 1, false);
RoutingPolicy policy = new RoutingPolicy(app.id().defaultInstance(),
ClusterSpec.Id.from("default"),
ZoneId.from(Environment.prod, RegionName.from("us-west-1")),
HostName.from("lb-0-canonical-name"),
Optional.of("dns-zone-1"), Set.of(EndpointId.of("c0")));
tester.controller().curator().writeRoutingPolicies(app.id().defaultInstance(), Set.of(policy));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
new File("application-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private void notifyCompletion(DeploymentJobs.JobReport report, ContainerControllerTester tester) {
assertResponse(request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.userIdentity(HOSTED_VESPA_OPERATOR)
.data(asJson(report))
.get(),
200, "{\"message\":\"ok\"}");
tester.controller().applications().deploymentTrigger().triggerReadyJobs();
}
private static byte[] asJson(DeploymentJobs.JobReport report) {
Slime slime = new Slime();
Cursor cursor = slime.setObject();
cursor.setLong("projectId", report.projectId());
cursor.setString("jobName", report.jobType().jobName());
cursor.setLong("buildNumber", report.buildNumber());
report.jobError().ifPresent(jobError -> cursor.setString("jobError", jobError.name()));
report.version().flatMap(ApplicationVersion::source).ifPresent(sr -> {
Cursor sourceRevision = cursor.setObject("sourceRevision");
sourceRevision.setString("repository", sr.repository());
sourceRevision.setString("branch", sr.branch());
sourceRevision.setString("commit", sr.commit());
});
cursor.setString("tenant", report.applicationId().tenant().value());
cursor.setString("application", report.applicationId().application().value());
cursor.setString("instance", report.applicationId().instance().value());
try {
return SlimeUtils.toJsonBytes(slime);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
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;
}
private MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repo\",\"branch\":\"master\",\"commit\":\"d00d\",\"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) {
AthenzClientFactoryMock mock = (AthenzClientFactoryMock) container.components()
.getComponent(AthenzClientFactoryMock.class.getName());
AthenzDbMock.Domain domainMock = mock.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 configureAthenzIdentity(com.yahoo.vespa.athenz.api.AthenzService service, boolean allowLaunch) {
AthenzClientFactoryMock mock = (AthenzClientFactoryMock) container.components()
.getComponent(AthenzClientFactoryMock.class.getName());
AthenzDbMock.Domain domainMock = mock.getSetup().domains.computeIfAbsent(service.getDomain(), AthenzDbMock.Domain::new);
domainMock.services.put(service.getName(), new AthenzDbMock.Service(allowLaunch));
}
/**
* 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,
com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId applicationId) {
AthenzClientFactoryMock mock = (AthenzClientFactoryMock) container.components()
.getComponent(AthenzClientFactoryMock.class.getName());
AthenzIdentity screwdriverIdentity = HostedAthenzIdentities.from(screwdriverId);
AthenzDbMock.Application athenzApplication = mock.getSetup().domains.get(domain).applications.get(applicationId);
athenzApplication.addRoleMember(ApplicationAction.deploy, screwdriverIdentity);
}
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),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
private void startAndTestChange(ContainerControllerTester controllerTester, ApplicationId application,
long projectId, ApplicationPackage applicationPackage,
MultiPartStreamer deployData, long buildNumber) {
ContainerTester tester = controllerTester.containerTester();
controllerTester.containerTester().serviceRegistry().artifactRepositoryMock()
.put(application, applicationPackage,"1.0." + buildNumber + "-commit1");
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(projectId)
.buildNumber(buildNumber)
.submit();
String testPath = String.format("/application/v4/tenant/%s/application/%s/instance/%s/environment/test/region/us-east-1",
application.tenant().value(), application.application().value(), application.instance().value());
tester.assertResponse(request(testPath, POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request(testPath, DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated " + application + " in test.us-east-1\"}");
controllerTester.jobCompletion(JobType.systemTest)
.application(application)
.projectId(projectId)
.submit();
String stagingPath = String.format("/application/v4/tenant/%s/application/%s/instance/%s/environment/staging/region/us-east-3",
application.tenant().value(), application.application().value(), application.instance().value());
tester.assertResponse(request(stagingPath, POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request(stagingPath, DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated " + application + " in staging.us-east-3\"}");
controllerTester.jobCompletion(JobType.stagingTest)
.application(application)
.projectId(projectId)
.submit();
}
/**
* 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(ContainerControllerTester controllerTester) {
for (Application application : controllerTester.controller().applications().asList()) {
controllerTester.controller().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()) {
Map<ClusterSpec.Id, ClusterInfo> clusterInfo = new HashMap<>();
List<String> hostnames = new ArrayList<>();
hostnames.add("host1");
hostnames.add("host2");
clusterInfo.put(ClusterSpec.Id.from("cluster1"),
new ClusterInfo("flavor1", 37, 2, 4, 50,
ClusterSpec.Type.content, hostnames));
Map<ClusterSpec.Id, ClusterUtilization> clusterUtils = new HashMap<>();
clusterUtils.put(ClusterSpec.Id.from("cluster1"), new ClusterUtilization(0.3, 0.6, 0.4, 0.3));
DeploymentMetrics metrics = new DeploymentMetrics(1, 2, 3, 4, 5,
Optional.of(Instant.ofEpochMilli(123123)), Map.of());
lockedApplication = lockedApplication.with(instance.name(),
lockedInstance -> lockedInstance.withClusterInfo(deployment.zone(), clusterInfo)
.withClusterUtilization(deployment.zone(), clusterUtils)
.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
controllerTester.controller().applications().store(lockedApplication);
}
});
}
}
private ServiceRegistryMock serviceRegistry() {
return (ServiceRegistryMock) tester.container().components().getComponent(ServiceRegistryMock.class.getName());
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator())).run();
}
private RotationStatus rotationStatus(Instance instance) {
return controllerTester.controller().applications().rotationRepository().getRotation(instance)
.map(rotation -> {
var rotationStatus = controllerTester.controller().serviceRegistry().globalRoutingService().getHealthStatus(rotation.name());
var statusMap = new LinkedHashMap<ZoneId, RotationState>();
rotationStatus.forEach((zone, status) -> statusMap.put(zone, RotationState.in));
return RotationStatus.from(Map.of(rotation.id(), statusMap));
})
.orElse(RotationStatus.EMPTY);
}
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));
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 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 OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private Map<String, List<String>> headers = new HashMap<>();
private String recursive;
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(StandardCharsets.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 oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { this.recursive = recursive; 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:
(recursive == null ? "" : "?recursive=" + recursive),
data, method);
request.getHeaders().addAll(headers);
request.getHeaders().put("Content-Type", contentType);
if (identity != null) {
addIdentityToRequest(request, identity);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} |
Current code is better, but will consider this when I remove outdated code paths again in a couple of weeks. | protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
if ( request.getAttribute(SecurityContext.ATTRIBUTE_NAME) == null
&& request.getHeader("X-Authorization") != null)
try {
ApplicationId id = ApplicationId.fromSerializedForm(request.getHeader("X-Key-Id"));
SecurityContext securityContext = null;
if (request.getHeader("X-Key") != null) {
PublicKey key = KeyUtils.fromPemEncodedPublicKey(new String(Base64.getDecoder().decode(request.getHeader("X-Key")), UTF_8));
if (keyVerifies(key, request)) {
Principal principal = null;
Set<Role> roles = new HashSet<>();
Optional <Application> application = controller.applications().getApplication(TenantAndApplicationId.from(id));
if (application.isPresent() && application.get().deployKeys().contains(key)) {
principal = new SimplePrincipal("headless@" + id.tenant() + "." + id.application());
roles.add(Role.reader(id.tenant()));
roles.add(Role.headless(id.tenant(), id.application()));
}
Optional<CloudTenant> tenant = controller.tenants().get(id.tenant())
.filter(CloudTenant.class::isInstance)
.map(CloudTenant.class::cast);
if (tenant.isPresent() && tenant.get().developerKeys().containsKey(key)) {
principal = tenant.get().developerKeys().get(key);
roles.add(Role.reader(id.tenant()));
roles.add(Role.developer(id.tenant()));
}
if (principal != null)
securityContext = new SecurityContext(principal, roles);
}
}
else if (anyDeployKeyMatches(TenantAndApplicationId.from(id), request))
securityContext = new SecurityContext(new SimplePrincipal("buildService@" + id.tenant() + "." + id.application()),
Set.of(Role.buildService(id.tenant(), id.application())));
if (securityContext != null) {
request.setUserPrincipal(securityContext.principal());
request.setRemoteUser(securityContext.principal().getName());
request.setAttribute(SecurityContext.ATTRIBUTE_NAME, securityContext);
}
}
catch (Exception e) {
logger.log(LogLevel.DEBUG, () -> "Exception verifying signed request: " + Exceptions.toMessageString(e));
}
return Optional.empty();
} | } | protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
if ( request.getAttribute(SecurityContext.ATTRIBUTE_NAME) == null
&& request.getHeader("X-Authorization") != null)
try {
getSecurityContext(request).ifPresent(securityContext -> {
request.setUserPrincipal(securityContext.principal());
request.setRemoteUser(securityContext.principal().getName());
request.setAttribute(SecurityContext.ATTRIBUTE_NAME, securityContext);
});
}
catch (Exception e) {
logger.log(LogLevel.DEBUG, () -> "Exception verifying signed request: " + Exceptions.toMessageString(e));
}
return Optional.empty();
} | class SignatureFilter extends JsonSecurityRequestFilterBase {
private static final Logger logger = Logger.getLogger(SignatureFilter.class.getName());
private final Controller controller;
@Inject
public SignatureFilter(Controller controller) {
this.controller = controller;
}
@Override
private boolean anyDeployKeyMatches(TenantAndApplicationId id, DiscFilterRequest request) {
return controller.applications().getApplication(id).stream()
.map(Application::deployKeys)
.flatMap(Set::stream)
.anyMatch(key -> keyVerifies(key, request));
}
private boolean keyVerifies(PublicKey key, DiscFilterRequest request) {
return new RequestVerifier(key, controller.clock()).verify(Method.valueOf(request.getMethod()),
request.getUri(),
request.getHeader("X-Timestamp"),
request.getHeader("X-Content-Hash"),
request.getHeader("X-Authorization"));
}
private Optional<Principal> getPrincipal(CloudTenant tenant, PublicKey key) {
return Optional.empty();
}
} | class SignatureFilter extends JsonSecurityRequestFilterBase {
private static final Logger logger = Logger.getLogger(SignatureFilter.class.getName());
private final Controller controller;
@Inject
public SignatureFilter(Controller controller) {
this.controller = controller;
}
@Override
private boolean anyDeployKeyMatches(TenantAndApplicationId id, DiscFilterRequest request) {
return controller.applications().getApplication(id).stream()
.map(Application::deployKeys)
.flatMap(Set::stream)
.anyMatch(key -> keyVerifies(key, request));
}
private boolean keyVerifies(PublicKey key, DiscFilterRequest request) {
return new RequestVerifier(key, controller.clock()).verify(Method.valueOf(request.getMethod()),
request.getUri(),
request.getHeader("X-Timestamp"),
request.getHeader("X-Content-Hash"),
request.getHeader("X-Authorization"));
}
private Optional<SecurityContext> getSecurityContext(DiscFilterRequest request) {
ApplicationId id = ApplicationId.fromSerializedForm(request.getHeader("X-Key-Id"));
if (request.getHeader("X-Key") != null) {
PublicKey key = KeyUtils.fromPemEncodedPublicKey(new String(Base64.getDecoder().decode(request.getHeader("X-Key")), UTF_8));
if (keyVerifies(key, request)) {
Optional<CloudTenant> tenant = controller.tenants().get(id.tenant())
.filter(CloudTenant.class::isInstance)
.map(CloudTenant.class::cast);
if (tenant.isPresent() && tenant.get().developerKeys().containsKey(key))
return Optional.of(new SecurityContext(tenant.get().developerKeys().get(key),
Set.of(Role.reader(id.tenant()),
Role.developer(id.tenant()))));
Optional <Application> application = controller.applications().getApplication(TenantAndApplicationId.from(id));
if (application.isPresent() && application.get().deployKeys().contains(key))
return Optional.of(new SecurityContext(new SimplePrincipal("headless@" + id.tenant() + "." + id.application()),
Set.of(Role.reader(id.tenant()),
Role.developer(id.tenant()))));
}
}
else if (anyDeployKeyMatches(TenantAndApplicationId.from(id), request))
return Optional.of(new SecurityContext(new SimplePrincipal("headless@" + id.tenant() + "." + id.application()),
Set.of(Role.reader(id.tenant()),
Role.developer(id.tenant()))));
return Optional.empty();
}
} |
You may want to prefix the message with "invalid public key" or similar. Error messages from the Java are often cryptic... | 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);
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant ->
controller.tenants().store(tenant.withDeveloperKey(developerKey, user)));
return new MessageResponse("Set developer key " + pemDeveloperKey + " for " + user);
} | PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey); | 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);
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant ->
controller.tenants().store(tenant.withDeveloperKey(developerKey, user)));
return new MessageResponse("Set developer key " + pemDeveloperKey + " for " + user);
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
}
@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/user")) return authenticatedUser(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"), "default", 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 application(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}/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}/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}/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/user")) return createUser(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"), "default", 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}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), 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"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createApplication(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/{ignored}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), path.get("instance"), 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}/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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), "default");
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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), path.get("instance"));
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}/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, "user", "tenant");
}
private HttpResponse authenticatedUser(HttpRequest request) {
Principal user = requireUserPrincipal(request);
if (user == null)
throw new NotAuthorizedException("You must be authenticated.");
String userName = user instanceof AthenzPrincipal ? ((AthenzPrincipal) user).getIdentity().getName() : user.getName();
TenantName tenantName = TenantName.from(UserTenant.normalizeUser(userName));
List<Tenant> tenants = controller.tenants().asList(new Credentials(user));
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setString("user", userName);
Cursor tenantsArray = response.setArray("tenants");
for (Tenant tenant : tenants)
tenantInTenantsListToSlime(tenant, request.getUri(), tenantsArray.addObject());
response.setBool("tenantExists", tenants.stream().anyMatch(tenant -> tenant.name().equals(tenantName)));
return new SlimeJsonResponse(slime);
}
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);
Slime slime = new Slime();
Cursor array = slime.setArray();
for (Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true))
for (InstanceName instance : application.instances().keySet())
toSlime(application.id().instance(instance), array.addObject(), request);
}
return new SlimeJsonResponse(slime);
}
private HttpResponse application(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
getApplication(tenantName, applicationName, instanceName), request);
return new SlimeJsonResponse(slime);
}
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);
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant ->
controller.tenants().store(tenant.withoutDeveloperKey(developerKey)));
return new MessageResponse("Removed developer key " + pemDeveloperKey + " for " + user);
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application ->
controller.applications().store(application.withDeployKey(deployKey)));
return new MessageResponse("Added deploy key " + pemDeployKey);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application ->
controller.applications().store(application.withoutDeployKey(deployKey)));
return new MessageResponse("Removed deploy key " + pemDeployKey);
}
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 Application getApplication(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
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()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.canonicalFlavor());
nodeObject.setDouble("vcpu", node.vcpu());
nodeObject.setDouble("memoryGb", node.memoryGb());
nodeObject.setDouble("diskGb", node.diskGb());
nodeObject.setDouble("bandwidthGbps", node.bandwidthGbps());
nodeObject.setBool("fastDisk", node.fastDisk());
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
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";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
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) {
String triggered = controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName())
.stream().map(JobType::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 void toSlime(Cursor object, Instance instance, Application application, HttpRequest request) {
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());
instance.deploymentJobs().statusOf(JobType.component)
.flatMap(JobStatus::lastSuccess)
.map(run -> run.application().source())
.ifPresent(source -> sourceRevisionToSlime(source, object.setObject("source")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if ( ! application.change().isEmpty()) {
toSlime(object.setObject("deploying"), application.change());
}
if ( ! application.outstandingChange().isEmpty()) {
toSlime(object.setObject("outstandingChange"), application.outstandingChange());
}
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedJobs(instance.deploymentJobs().jobStatus().values());
object.setBool("deployedInternally", application.internal());
Cursor deploymentsArray = object.setArray("deploymentJobs");
for (JobStatus job : jobStatus) {
Cursor jobObject = deploymentsArray.addObject();
jobObject.setString("type", job.type().jobName());
jobObject.setBool("success", job.isSuccess());
job.lastTriggered().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastTriggered")));
job.lastCompleted().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastCompleted")));
job.firstFailing().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("firstFailing")));
job.lastSuccess().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastSuccess")));
}
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().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);
});
object.setString("compileVersion", compileVersion(application.id()).toFullString());
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor globalRotationsArray = object.setArray("globalRotations");
instance.endpointsIn(controller.system())
.scope(Endpoint.Scope.global)
.legacy(false)
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
Set<RoutingPolicy> routingPolicies = controller.applications().routingPolicies().get(instance.id());
for (RoutingPolicy policy : routingPolicies) {
policy.rotationEndpointsIn(controller.system()).asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
}
List<Deployment> deployments = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedDeployments(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 (!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().getPath().contains("/instance/") ? "" : "/instance/" + instance.id().instance().value()),
request.getUri()).toString());
}
}
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(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 endpointArray = response.setArray("endpoints");
for (var policy : controller.applications().routingPolicies().get(deploymentId)) {
Cursor endpointObject = endpointArray.addObject();
Endpoint endpoint = policy.endpointIn(controller.system());
endpointObject.setString("cluster", policy.cluster().value());
endpointObject.setBool("tls", endpoint.tls());
endpointObject.setString("url", endpoint.url().toString());
}
Cursor serviceUrlArray = response.setArray("serviceUrls");
controller.applications().getDeploymentEndpoints(deploymentId)
.forEach(endpoint -> serviceUrlArray.addString(endpoint.toString()));
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()));
controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId())).projectId()
.ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
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));
DeploymentCost appCost = deployment.calculateCost();
Cursor costObject = response.setObject("cost");
toSlime(appCost, costObject);
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.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if ( ! revision.isPresent()) 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();
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
}
}
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);
return controller.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 -> ! controller.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);
}
Inspector requestData = toSlime(request.getData()).get();
String reason = mandatory("reason", requestData).asString();
String agent = requireUserPrincipal(request).getName();
long timestamp = controller.clock().instant().getEpochSecond();
EndpointStatus.Status status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
EndpointStatus endpointStatus = new EndpointStatus(status, reason, agent, timestamp);
controller.applications().setGlobalRotationStatus(new DeploymentId(instance.id(), deployment.zone()),
endpointStatus);
return new MessageResponse(String.format("Successfully set %s in %s.%s %s service",
instance.id().toShortString(),
deployment.zone().environment().value(),
deployment.zone().region().value(),
inService ? "in" : "out of"));
}
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");
Map<RoutingEndpoint, EndpointStatus> status = controller.applications().globalRotationStatus(deploymentId);
for (RoutingEndpoint endpoint : status.keySet()) {
EndpointStatus currentStatus = status.get(endpoint);
array.addString(endpoint.upstreamName());
Cursor statusObject = array.addObject();
statusObject.setString("status", currentStatus.getStatus().name());
statusObject.setString("reason", currentStatus.getReason() == null ? "" : currentStatus.getReason());
statusObject.setString("agent", currentStatus.getAgent() == null ? "" : currentStatus.getAgent());
statusObject.setLong("timestamp", currentStatus.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();
MeteringInfo meteringInfo = controller.serviceRegistry().meteringService().getResourceSnapshots(tenant, application);
ResourceAllocation currentSnapshot = meteringInfo.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringInfo.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringInfo.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 = meteringInfo.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 tenant, String application, String instance, HttpRequest request) {
Application app = controller.applications().requireApplication(TenantAndApplicationId.from(tenant, application));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! app.change().isEmpty()) {
app.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
app.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", app.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) {
Map<?,?> result = controller.getServiceApiResponse(tenantName, applicationName, instanceName, environment, region, serviceName, restPath);
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(result, serviceName, restPath);
return response;
}
private HttpResponse createUser(HttpRequest request) {
String user = Optional.of(requireUserPrincipal(request))
.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.map(AthenzIdentity::getName)
.map(UserTenant::normalizeUser)
.orElseThrow(() -> new ForbiddenException("Not authenticated or not a user."));
UserTenant tenant = UserTenant.create(user);
try {
controller.tenants().createUser(tenant);
return new MessageResponse("Created user '" + user + "'");
} catch (AlreadyExistsException e) {
return new MessageResponse("User '" + user + "' already exists");
}
}
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, String instanceName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
try {
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest()));
Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
catch (ZmsClientException e) {
if (e.getErrorCode() == com.yahoo.jdisc.Response.Status.FORBIDDEN)
throw new ForbiddenException("Not authorized to create application", e);
else
throw e;
}
}
/** 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());
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(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 " + change + " for " + 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);
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = Change.of(application.get().require(InstanceName.from(instanceName)).deploymentJobs().statusOf(JobType.component).get().lastSuccess().get().application());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered " + change + " for " + 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) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = application.get().change();
if (change.isEmpty()) {
response.append("No deployment in progress for " + application + " at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '" + change + "' to '" +
controller.applications().requireApplication(id).change() + "' for " + application);
});
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) {
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(),
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);
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<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,
application.get().internal(),
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,
application.get().internal(),
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass,
Optional.of(requireUserPrincipal(request)));
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if ( ! tenant.isPresent())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
if (tenant.get().type() == Tenant.Type.user)
controller.tenants().deleteUser((UserTenant) tenant.get());
else
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) {
TenantName tenant = TenantName.from(tenantName);
ApplicationName application = ApplicationName.from(applicationName);
Optional<Credentials> credentials = controller.tenants().require(tenant).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(tenant, toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteApplication(tenant, application, credentials);
return new MessageResponse("Deleted application " + tenant + "." + application);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteInstance(id, credentials);
return new MessageResponse("Deleted instance " + id.toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
DeploymentId deploymentId = new DeploymentId(instance.id(), ZoneId.from(environment, region));
controller.applications().deactivate(deploymentId.applicationId(), deploymentId.zoneId());
return new MessageResponse("Deactivated " + deploymentId);
}
private HttpResponse notifyJobCompletion(String tenant, String application, HttpRequest request) {
try {
DeploymentJobs.JobReport report = toJobReport(tenant, application, toSlime(request.getData()).get());
if ( report.jobType() == JobType.component
&& controller.applications().requireApplication(TenantAndApplicationId.from(report.applicationId())).internal())
throw new IllegalArgumentException(report.applicationId() + " is set up to be deployed from internally, and no " +
"longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.");
controller.applications().deploymentTrigger().notifyOfCompletion(report);
return new MessageResponse("ok");
} catch (IllegalStateException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
}
private HttpResponse testConfig(ApplicationId id, JobType type) {
var endpoints = controller.applications().clusterEndpoints(id, controller.jobController().testedZoneAndProductionZones(id, type));
return new SlimeJsonResponse(new TestConfigSerializer(controller.system()).configSlime(id,
type,
endpoints,
Collections.emptyMap()));
}
private static DeploymentJobs.JobReport toJobReport(String tenantName, String applicationName, Inspector report) {
Optional<DeploymentJobs.JobError> jobError = Optional.empty();
if (report.field("jobError").valid()) {
jobError = Optional.of(DeploymentJobs.JobError.valueOf(report.field("jobError").asString()));
}
ApplicationId id = ApplicationId.from(tenantName, applicationName, report.field("instance").asString());
JobType type = JobType.fromJobName(report.field("jobName").asString());
long buildNumber = report.field("buildNumber").asLong();
if (type == JobType.component)
return DeploymentJobs.JobReport.ofComponent(id,
report.field("projectId").asLong(),
buildNumber,
jobError,
toSourceRevision(report.field("sourceRevision")));
else
return DeploymentJobs.JobReport.ofJob(id, type, buildNumber, jobError);
}
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<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 user: break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
Cursor pemDeployKeysArray = object.setArray("pemDeployKeys");
for (Application application : applications)
for (PublicKey key : application.deployKeys()) {
Cursor keyObject = pemDeployKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("application", application.id().application().value());
}
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 (Application application : applications)
for (Instance instance : application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, application, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
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 user: 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(JobStatus.JobRun jobRun, Cursor object) {
object.setLong("id", jobRun.id());
object.setString("version", jobRun.platform().toFullString());
if (!jobRun.application().isUnknown())
toSlime(jobRun.application(), object.setObject("revision"));
object.setString("reason", jobRun.reason());
object.setLong("at", jobRun.at().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(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));
}
public static void toSlime(DeploymentCost deploymentCost, Cursor object) {
object.setLong("tco", (long)deploymentCost.getTco());
object.setLong("waste", (long)deploymentCost.getWaste());
object.setDouble("utilization", deploymentCost.getUtilization());
Cursor clustersObject = object.setObject("cluster");
for (Map.Entry<String, ClusterCost> clusterEntry : deploymentCost.getCluster().entrySet())
toSlime(clusterEntry.getValue(), clustersObject.setObject(clusterEntry.getKey()));
}
private static void toSlime(ClusterCost clusterCost, Cursor object) {
object.setLong("count", clusterCost.getClusterInfo().getHostnames().size());
object.setString("resource", getResourceName(clusterCost.getResultUtilization()));
object.setDouble("utilization", clusterCost.getResultUtilization().getMaxUtilization());
object.setLong("tco", (int)clusterCost.getTco());
object.setLong("waste", (int)clusterCost.getWaste());
object.setString("flavor", clusterCost.getClusterInfo().getFlavor());
object.setDouble("flavorCost", clusterCost.getClusterInfo().getFlavorCost());
object.setDouble("flavorCpu", clusterCost.getClusterInfo().getFlavorCPU());
object.setDouble("flavorMem", clusterCost.getClusterInfo().getFlavorMem());
object.setDouble("flavorDisk", clusterCost.getClusterInfo().getFlavorDisk());
object.setString("type", clusterCost.getClusterInfo().getClusterType().name());
Cursor utilObject = object.setObject("util");
utilObject.setDouble("cpu", clusterCost.getResultUtilization().getCpu());
utilObject.setDouble("mem", clusterCost.getResultUtilization().getMemory());
utilObject.setDouble("disk", clusterCost.getResultUtilization().getDisk());
utilObject.setDouble("diskBusy", clusterCost.getResultUtilization().getDiskBusy());
Cursor usageObject = object.setObject("usage");
usageObject.setDouble("cpu", clusterCost.getSystemUtilization().getCpu());
usageObject.setDouble("mem", clusterCost.getSystemUtilization().getMemory());
usageObject.setDouble("disk", clusterCost.getSystemUtilization().getDisk());
usageObject.setDouble("diskBusy", clusterCost.getSystemUtilization().getDiskBusy());
Cursor hostnamesArray = object.setArray("hostnames");
for (String hostname : clusterCost.getClusterInfo().getHostnames())
hostnamesArray.addString(hostname);
}
private static String getResourceName(ClusterUtilization utilization) {
String name = "cpu";
double max = utilization.getMaxUtilization();
if (utilization.getMemory() == max) {
name = "mem";
} else if (utilization.getDisk() == max) {
name = "disk";
} else if (utilization.getDiskBusy() == max) {
name = "diskbusy";
}
return name;
}
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 String tenantType(Tenant tenant) {
switch (tenant.type()) {
case user: return "USER";
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, String instance, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
SourceRevision sourceRevision = toSourceRevision(submitOptions);
String authorEmail = submitOptions.field("authorEmail").asString();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
instance,
sourceRevision,
authorEmail,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
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";
}
} | class ApplicationApiHandler extends LoggingRequestHandler {
private static final String OPTIONAL_PREFIX = "/api";
private final Controller controller;
private final AccessControlRequests accessControlRequests;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx);
this.controller = controller;
this.accessControlRequests = accessControlRequests;
}
@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/user")) return authenticatedUser(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"), "default", 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 application(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}/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}/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}/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/user")) return createUser(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"), "default", 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}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), 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"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createApplication(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/{ignored}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), path.get("instance"), 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}/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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), "default");
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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), path.get("instance"));
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}/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, "user", "tenant");
}
private HttpResponse authenticatedUser(HttpRequest request) {
Principal user = requireUserPrincipal(request);
if (user == null)
throw new NotAuthorizedException("You must be authenticated.");
String userName = user instanceof AthenzPrincipal ? ((AthenzPrincipal) user).getIdentity().getName() : user.getName();
TenantName tenantName = TenantName.from(UserTenant.normalizeUser(userName));
List<Tenant> tenants = controller.tenants().asList(new Credentials(user));
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setString("user", userName);
Cursor tenantsArray = response.setArray("tenants");
for (Tenant tenant : tenants)
tenantInTenantsListToSlime(tenant, request.getUri(), tenantsArray.addObject());
response.setBool("tenantExists", tenants.stream().anyMatch(tenant -> tenant.name().equals(tenantName)));
return new SlimeJsonResponse(slime);
}
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);
Slime slime = new Slime();
Cursor array = slime.setArray();
for (Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true))
for (InstanceName instance : application.instances().keySet())
toSlime(application.id().instance(instance), array.addObject(), request);
}
return new SlimeJsonResponse(slime);
}
private HttpResponse application(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
getApplication(tenantName, applicationName, instanceName), request);
return new SlimeJsonResponse(slime);
}
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);
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant ->
controller.tenants().store(tenant.withoutDeveloperKey(developerKey)));
return new MessageResponse("Removed developer key " + pemDeveloperKey + " for " + user);
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application ->
controller.applications().store(application.withDeployKey(deployKey)));
return new MessageResponse("Added deploy key " + pemDeployKey);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application ->
controller.applications().store(application.withoutDeployKey(deployKey)));
return new MessageResponse("Removed deploy key " + pemDeployKey);
}
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 Application getApplication(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
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()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.canonicalFlavor());
nodeObject.setDouble("vcpu", node.vcpu());
nodeObject.setDouble("memoryGb", node.memoryGb());
nodeObject.setDouble("diskGb", node.diskGb());
nodeObject.setDouble("bandwidthGbps", node.bandwidthGbps());
nodeObject.setBool("fastDisk", node.fastDisk());
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
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";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
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) {
String triggered = controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName())
.stream().map(JobType::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 void toSlime(Cursor object, Instance instance, Application application, HttpRequest request) {
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());
instance.deploymentJobs().statusOf(JobType.component)
.flatMap(JobStatus::lastSuccess)
.map(run -> run.application().source())
.ifPresent(source -> sourceRevisionToSlime(source, object.setObject("source")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if ( ! application.change().isEmpty()) {
toSlime(object.setObject("deploying"), application.change());
}
if ( ! application.outstandingChange().isEmpty()) {
toSlime(object.setObject("outstandingChange"), application.outstandingChange());
}
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedJobs(instance.deploymentJobs().jobStatus().values());
object.setBool("deployedInternally", application.internal());
Cursor deploymentsArray = object.setArray("deploymentJobs");
for (JobStatus job : jobStatus) {
Cursor jobObject = deploymentsArray.addObject();
jobObject.setString("type", job.type().jobName());
jobObject.setBool("success", job.isSuccess());
job.lastTriggered().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastTriggered")));
job.lastCompleted().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastCompleted")));
job.firstFailing().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("firstFailing")));
job.lastSuccess().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastSuccess")));
}
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().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);
});
object.setString("compileVersion", compileVersion(application.id()).toFullString());
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor globalRotationsArray = object.setArray("globalRotations");
instance.endpointsIn(controller.system())
.scope(Endpoint.Scope.global)
.legacy(false)
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
Set<RoutingPolicy> routingPolicies = controller.applications().routingPolicies().get(instance.id());
for (RoutingPolicy policy : routingPolicies) {
policy.rotationEndpointsIn(controller.system()).asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
}
List<Deployment> deployments = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedDeployments(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 (!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().getPath().contains("/instance/") ? "" : "/instance/" + instance.id().instance().value()),
request.getUri()).toString());
}
}
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(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 endpointArray = response.setArray("endpoints");
for (var policy : controller.applications().routingPolicies().get(deploymentId)) {
Cursor endpointObject = endpointArray.addObject();
Endpoint endpoint = policy.endpointIn(controller.system());
endpointObject.setString("cluster", policy.cluster().value());
endpointObject.setBool("tls", endpoint.tls());
endpointObject.setString("url", endpoint.url().toString());
}
Cursor serviceUrlArray = response.setArray("serviceUrls");
controller.applications().getDeploymentEndpoints(deploymentId)
.forEach(endpoint -> serviceUrlArray.addString(endpoint.toString()));
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()));
controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId())).projectId()
.ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
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));
DeploymentCost appCost = deployment.calculateCost();
Cursor costObject = response.setObject("cost");
toSlime(appCost, costObject);
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.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if ( ! revision.isPresent()) 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();
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
}
}
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);
return controller.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 -> ! controller.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);
}
Inspector requestData = toSlime(request.getData()).get();
String reason = mandatory("reason", requestData).asString();
String agent = requireUserPrincipal(request).getName();
long timestamp = controller.clock().instant().getEpochSecond();
EndpointStatus.Status status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
EndpointStatus endpointStatus = new EndpointStatus(status, reason, agent, timestamp);
controller.applications().setGlobalRotationStatus(new DeploymentId(instance.id(), deployment.zone()),
endpointStatus);
return new MessageResponse(String.format("Successfully set %s in %s.%s %s service",
instance.id().toShortString(),
deployment.zone().environment().value(),
deployment.zone().region().value(),
inService ? "in" : "out of"));
}
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");
Map<RoutingEndpoint, EndpointStatus> status = controller.applications().globalRotationStatus(deploymentId);
for (RoutingEndpoint endpoint : status.keySet()) {
EndpointStatus currentStatus = status.get(endpoint);
array.addString(endpoint.upstreamName());
Cursor statusObject = array.addObject();
statusObject.setString("status", currentStatus.getStatus().name());
statusObject.setString("reason", currentStatus.getReason() == null ? "" : currentStatus.getReason());
statusObject.setString("agent", currentStatus.getAgent() == null ? "" : currentStatus.getAgent());
statusObject.setLong("timestamp", currentStatus.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();
MeteringInfo meteringInfo = controller.serviceRegistry().meteringService().getResourceSnapshots(tenant, application);
ResourceAllocation currentSnapshot = meteringInfo.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringInfo.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringInfo.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 = meteringInfo.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 tenant, String application, String instance, HttpRequest request) {
Application app = controller.applications().requireApplication(TenantAndApplicationId.from(tenant, application));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! app.change().isEmpty()) {
app.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
app.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", app.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) {
Map<?,?> result = controller.getServiceApiResponse(tenantName, applicationName, instanceName, environment, region, serviceName, restPath);
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(result, serviceName, restPath);
return response;
}
private HttpResponse createUser(HttpRequest request) {
String user = Optional.of(requireUserPrincipal(request))
.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.map(AthenzIdentity::getName)
.map(UserTenant::normalizeUser)
.orElseThrow(() -> new ForbiddenException("Not authenticated or not a user."));
UserTenant tenant = UserTenant.create(user);
try {
controller.tenants().createUser(tenant);
return new MessageResponse("Created user '" + user + "'");
} catch (AlreadyExistsException e) {
return new MessageResponse("User '" + user + "' already exists");
}
}
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, String instanceName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
try {
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest()));
Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
catch (ZmsClientException e) {
if (e.getErrorCode() == com.yahoo.jdisc.Response.Status.FORBIDDEN)
throw new ForbiddenException("Not authorized to create application", e);
else
throw e;
}
}
/** 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());
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(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 " + change + " for " + 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);
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = Change.of(application.get().require(InstanceName.from(instanceName)).deploymentJobs().statusOf(JobType.component).get().lastSuccess().get().application());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered " + change + " for " + 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) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = application.get().change();
if (change.isEmpty()) {
response.append("No deployment in progress for " + application + " at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '" + change + "' to '" +
controller.applications().requireApplication(id).change() + "' for " + application);
});
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) {
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(),
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);
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<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,
application.get().internal(),
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,
application.get().internal(),
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
ActivateResult result = controller.applications().deploy(applicationId,
zone,
applicationPackage,
applicationVersion,
deployOptionsJsonClass,
Optional.of(requireUserPrincipal(request)));
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
Optional<Tenant> tenant = controller.tenants().get(tenantName);
if ( ! tenant.isPresent())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
if (tenant.get().type() == Tenant.Type.user)
controller.tenants().deleteUser((UserTenant) tenant.get());
else
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) {
TenantName tenant = TenantName.from(tenantName);
ApplicationName application = ApplicationName.from(applicationName);
Optional<Credentials> credentials = controller.tenants().require(tenant).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(tenant, toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteApplication(tenant, application, credentials);
return new MessageResponse("Deleted application " + tenant + "." + application);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteInstance(id, credentials);
return new MessageResponse("Deleted instance " + id.toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
DeploymentId deploymentId = new DeploymentId(instance.id(), ZoneId.from(environment, region));
controller.applications().deactivate(deploymentId.applicationId(), deploymentId.zoneId());
return new MessageResponse("Deactivated " + deploymentId);
}
private HttpResponse notifyJobCompletion(String tenant, String application, HttpRequest request) {
try {
DeploymentJobs.JobReport report = toJobReport(tenant, application, toSlime(request.getData()).get());
if ( report.jobType() == JobType.component
&& controller.applications().requireApplication(TenantAndApplicationId.from(report.applicationId())).internal())
throw new IllegalArgumentException(report.applicationId() + " is set up to be deployed from internally, and no " +
"longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.");
controller.applications().deploymentTrigger().notifyOfCompletion(report);
return new MessageResponse("ok");
} catch (IllegalStateException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
}
private HttpResponse testConfig(ApplicationId id, JobType type) {
var endpoints = controller.applications().clusterEndpoints(id, controller.jobController().testedZoneAndProductionZones(id, type));
return new SlimeJsonResponse(new TestConfigSerializer(controller.system()).configSlime(id,
type,
endpoints,
Collections.emptyMap()));
}
private static DeploymentJobs.JobReport toJobReport(String tenantName, String applicationName, Inspector report) {
Optional<DeploymentJobs.JobError> jobError = Optional.empty();
if (report.field("jobError").valid()) {
jobError = Optional.of(DeploymentJobs.JobError.valueOf(report.field("jobError").asString()));
}
ApplicationId id = ApplicationId.from(tenantName, applicationName, report.field("instance").asString());
JobType type = JobType.fromJobName(report.field("jobName").asString());
long buildNumber = report.field("buildNumber").asLong();
if (type == JobType.component)
return DeploymentJobs.JobReport.ofComponent(id,
report.field("projectId").asLong(),
buildNumber,
jobError,
toSourceRevision(report.field("sourceRevision")));
else
return DeploymentJobs.JobReport.ofJob(id, type, buildNumber, jobError);
}
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<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 user: 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 (Application application : applications)
for (Instance instance : application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, application, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
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 user: 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(JobStatus.JobRun jobRun, Cursor object) {
object.setLong("id", jobRun.id());
object.setString("version", jobRun.platform().toFullString());
if (!jobRun.application().isUnknown())
toSlime(jobRun.application(), object.setObject("revision"));
object.setString("reason", jobRun.reason());
object.setLong("at", jobRun.at().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(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));
}
public static void toSlime(DeploymentCost deploymentCost, Cursor object) {
object.setLong("tco", (long)deploymentCost.getTco());
object.setLong("waste", (long)deploymentCost.getWaste());
object.setDouble("utilization", deploymentCost.getUtilization());
Cursor clustersObject = object.setObject("cluster");
for (Map.Entry<String, ClusterCost> clusterEntry : deploymentCost.getCluster().entrySet())
toSlime(clusterEntry.getValue(), clustersObject.setObject(clusterEntry.getKey()));
}
private static void toSlime(ClusterCost clusterCost, Cursor object) {
object.setLong("count", clusterCost.getClusterInfo().getHostnames().size());
object.setString("resource", getResourceName(clusterCost.getResultUtilization()));
object.setDouble("utilization", clusterCost.getResultUtilization().getMaxUtilization());
object.setLong("tco", (int)clusterCost.getTco());
object.setLong("waste", (int)clusterCost.getWaste());
object.setString("flavor", clusterCost.getClusterInfo().getFlavor());
object.setDouble("flavorCost", clusterCost.getClusterInfo().getFlavorCost());
object.setDouble("flavorCpu", clusterCost.getClusterInfo().getFlavorCPU());
object.setDouble("flavorMem", clusterCost.getClusterInfo().getFlavorMem());
object.setDouble("flavorDisk", clusterCost.getClusterInfo().getFlavorDisk());
object.setString("type", clusterCost.getClusterInfo().getClusterType().name());
Cursor utilObject = object.setObject("util");
utilObject.setDouble("cpu", clusterCost.getResultUtilization().getCpu());
utilObject.setDouble("mem", clusterCost.getResultUtilization().getMemory());
utilObject.setDouble("disk", clusterCost.getResultUtilization().getDisk());
utilObject.setDouble("diskBusy", clusterCost.getResultUtilization().getDiskBusy());
Cursor usageObject = object.setObject("usage");
usageObject.setDouble("cpu", clusterCost.getSystemUtilization().getCpu());
usageObject.setDouble("mem", clusterCost.getSystemUtilization().getMemory());
usageObject.setDouble("disk", clusterCost.getSystemUtilization().getDisk());
usageObject.setDouble("diskBusy", clusterCost.getSystemUtilization().getDiskBusy());
Cursor hostnamesArray = object.setArray("hostnames");
for (String hostname : clusterCost.getClusterInfo().getHostnames())
hostnamesArray.addString(hostname);
}
private static String getResourceName(ClusterUtilization utilization) {
String name = "cpu";
double max = utilization.getMaxUtilization();
if (utilization.getMemory() == max) {
name = "mem";
} else if (utilization.getDisk() == max) {
name = "disk";
} else if (utilization.getDiskBusy() == max) {
name = "diskbusy";
}
return name;
}
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 String tenantType(Tenant tenant) {
switch (tenant.type()) {
case user: return "USER";
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, String instance, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
SourceRevision sourceRevision = toSourceRevision(submitOptions);
String authorEmail = submitOptions.field("authorEmail").asString();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
instance,
sourceRevision,
authorEmail,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
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";
}
} |
```suggestion throw new NotExistsException("Could not delete instance '" + instanceId + "': Instance not found"); ``` | public void deleteInstance(ApplicationId instanceId) {
if (getInstance(instanceId).isEmpty())
throw new NotExistsException("Could not delete application '" + instanceId + "': Application 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(Collectors.joining(", ")));
applicationStore.removeAll(instanceId);
applicationStore.removeAll(TesterId.of(instanceId));
Instance instance = application.get().require(instanceId.instance());
instance.rotations().forEach(assignedRotation -> {
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId());
endpoints.asList().stream()
.map(Endpoint::dnsName)
.forEach(name -> {
controller.nameServiceForwarder().removeRecords(Record.Type.CNAME, RecordName.from(name), Priority.normal);
});
});
curator.writeApplication(application.without(instanceId.instance()).get());
log.info("Deleted " + instanceId);
});
} | throw new NotExistsException("Could not delete application '" + instanceId + "': Application not found"); | 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(Collectors.joining(", ")));
applicationStore.removeAll(instanceId);
applicationStore.removeAll(TesterId.of(instanceId));
Instance instance = application.get().require(instanceId.instance());
instance.rotations().forEach(assignedRotation -> {
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId());
endpoints.asList().stream()
.map(Endpoint::dnsName)
.forEach(name -> {
controller.nameServiceForwarder().removeRecords(Record.Type.CNAME, RecordName.from(name), Priority.normal);
});
});
curator.writeApplication(application.without(instanceId.instance()).get());
log.info("Deleted " + instanceId);
});
} | 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 RotationRepository rotationRepository;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final RoutingGenerator routingGenerator;
private final RoutingPolicies routingPolicies;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final BooleanFlag provisionApplicationCertificate;
private final DeploymentSpecValidator deploymentSpecValidator;
ApplicationController(Controller controller, CuratorDb curator,
AccessControl accessControl, RotationsConfig rotationsConfig,
Clock clock) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.routingGenerator = controller.serviceRegistry().routingGenerator();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
routingPolicies = new RoutingPolicies(controller);
rotationRepository = new RotationRepository(rotationsConfig, this, curator);
deploymentTrigger = new DeploymentTrigger(controller, controller.serviceRegistry().buildService(), clock);
provisionApplicationCertificate = Flags.PROVISION_APPLICATION_CERTIFICATE.bindTo(controller.flagSource());
deploymentSpecValidator = new DeploymentSpecValidator(controller);
Once.after(Duration.ofMinutes(1), () -> {
Instant start = clock.instant();
int count = 0;
for (Application application : curator.readApplications()) {
lockApplicationIfPresent(application.id(), this::store);
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 application with the given id, or null if it is not present */
public Optional<Application> getApplication(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id));
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(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();
}
/** 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 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());
}
/** Change the global endpoint status for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
findGlobalEndpoint(deployment).map(endpoint -> {
try {
configServer.setGlobalRotationStatus(deployment, endpoint.upstreamName(), status);
return endpoint;
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + deployment, e);
}
}).orElseThrow(() -> new IllegalArgumentException("No global endpoint exists for " + deployment));
}
/** Get global endpoint status for given deployment */
public Map<RoutingEndpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
return findGlobalEndpoint(deployment).map(endpoint -> {
try {
EndpointStatus status = configServer.getGlobalRotationStatus(deployment, endpoint.upstreamName());
return Map.of(endpoint, status);
} catch (Exception e) {
throw new RuntimeException("Failed to get rotation status of " + deployment, e);
}
}).orElseGet(Collections::emptyMap);
}
/** Find the global endpoint of given deployment, if any */
private Optional<RoutingEndpoint> findGlobalEndpoint(DeploymentId deployment) {
return routingGenerator.endpoints(deployment).stream()
.filter(RoutingEndpoint::isGlobal)
.findFirst();
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public Application createApplication(TenantAndApplicationId id, Optional<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());
Optional<Tenant> tenant = controller.tenants().get(id.tenant());
if (tenant.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
if (tenant.get().type() != Tenant.Type.user) {
if (credentials.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': No credentials provided");
accessControl.createApplication(id, credentials.get());
}
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) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
lockApplicationOrThrow(TenantAndApplicationId.from(id), 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");
store(application.withNewInstance(id.instance()));
log.info("Created " + id);
});
}
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options);
}
/** Deploys an application. If the application does not exist it is created. */
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 ( getApplication(applicationId).isEmpty()
&& controller.tenants().require(instanceId.tenant()).type() == Tenant.Type.user)
createApplication(applicationId, Optional.empty());
if (getInstance(instanceId).isEmpty())
createInstance(instanceId);
try (Lock deploymentLock = lockForDeployment(instanceId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<ApplicationCertificate> applicationCertificate;
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 + "."));
Optional<JobStatus> job = Optional.ofNullable(application.get().require(instance).deploymentJobs().jobStatus().get(jobType));
if ( job.isEmpty()
|| job.get().lastTriggered().isEmpty()
|| job.get().lastCompleted().isPresent() && job.get().lastCompleted().get().at().isAfter(job.get().lastTriggered().get().at()))
return unexpectedDeployment(instanceId, zone);
JobRun triggered = job.get().lastTriggered().get();
platformVersion = preferOldestVersion ? triggered.sourcePlatform().orElse(triggered.platform())
: triggered.platform();
applicationVersion = preferOldestVersion ? triggered.sourceApplication().orElse(triggered.application())
: triggered.application();
applicationPackage = getApplicationPackage(instanceId, application.get().internal(), applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, instanceId, jobType);
validateRun(application.get(), instance, zone, platformVersion, applicationVersion);
}
if (zone.environment().isProduction())
application = withRotation(application, instance);
endpoints = registerEndpointsInDns(application.get().deploymentSpec(), application.get().require(instanceId.instance()), zone);
if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
applicationCertificate = getApplicationCertificate(application.get().require(instance));
} else {
applicationCertificate = Optional.empty();
}
if ( ! preferOldestVersion
&& ! application.get().internal()
&& ! zone.environment().isManuallyDeployed()) {
storeWithUpdatedConfig(application, applicationPackage);
}
}
options = withVersion(platformVersion, options);
ActivateResult result = deploy(instanceId, applicationPackage, zone, options, endpoints,
applicationCertificate.orElse(null));
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, boolean internal, ApplicationVersion version) {
try {
return internal
? new ApplicationPackage(applicationStore.get(id, version))
: new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()));
}
catch (RuntimeException e) {
try {
log.info("Fetching application package for " + id + " from alternate repository; it is now deployed "
+ (internal ? "internally" : "externally") + "\nException was: " + Exceptions.toMessageString(e));
return internal
? new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()))
: new ApplicationPackage(applicationStore.get(id, version));
}
catch (RuntimeException s) {
e.addSuppressed(s);
throw e;
}
}
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public void storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
deploymentSpecValidator.validate(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
for (InstanceName instanceName : application.get().instances().keySet()) {
application = withoutDeletedDeployments(application, instanceName);
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
application = application.with(instanceName, instance -> withoutUnreferencedDeploymentJobs(deploymentSpec, instance));
}
store(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)
);
DeployOptions options = withVersion(version, DeployOptions.none());
return deploy(application.id(), applicationPackage, zone, options, Set.of(), /* No application cert */ null);
} 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, DeployOptions options) {
return deploy(tester.id(), applicationPackage, zone, options, Set.of(), /* No application cert for tester*/ null);
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, DeployOptions deployOptions, Set<ContainerEndpoint> endpoints,
ApplicationCertificate applicationCertificate) {
DeploymentId deploymentId = new DeploymentId(application, zone);
try {
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(deploymentId, deployOptions, Set.of(), endpoints, applicationCertificate, applicationPackage.zippedContent());
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
routingPolicies.refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
/** Makes sure the application has a global rotation, if eligible. */
private LockedApplication withRotation(LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(application.get().deploymentSpec(),
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
store(application);
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
private Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
var registerLegacyNames = deploymentSpec.globalServiceId().isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId())
.scope(Endpoint.Scope.global);
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
if (!registerLegacyNames) {
endpoints = endpoints.legacy(false);
}
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.asList().forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
private Optional<ApplicationCertificate> getApplicationCertificate(Instance instance) {
boolean provisionCertificate = provisionApplicationCertificate.with(FetchVector.Dimension.APPLICATION_ID,
instance.id().serializedForm()).value();
if (!provisionCertificate) {
return Optional.empty();
}
Optional<ApplicationCertificate> applicationCertificate = curator.readApplicationCertificate(instance.id());
if(applicationCertificate.isPresent())
return applicationCertificate;
ApplicationCertificate newCertificate = controller.serviceRegistry().applicationCertificateProvider().requestCaSignedCertificate(instance.id(), dnsNamesOf(instance.id()));
curator.writeApplicationCertificate(instance.id(), newCertificate);
return Optional.of(newCertificate);
}
/** Returns all valid DNS names of given application */
private List<String> dnsNamesOf(ApplicationId applicationId) {
List<String> endpointDnsNames = new ArrayList<>();
endpointDnsNames.add(Endpoint.createHashedCn(applicationId, controller.system()));
var globalDefaultEndpoint = Endpoint.of(applicationId).named(EndpointId.default_());
var rotationEndpoints = Endpoint.of(applicationId).wildcard();
var zoneLocalEndpoints = controller.zoneRegistry().zones().directlyRouted().zones().stream().flatMap(zone -> Stream.of(
Endpoint.of(applicationId).target(ClusterSpec.Id.from("default"), zone.getId()),
Endpoint.of(applicationId).wildcard(zone.getId())
));
Stream.concat(Stream.of(globalDefaultEndpoint, rotationEndpoints), zoneLocalEndpoints)
.map(Endpoint.EndpointBuilder::directRouting)
.map(endpoint -> endpoint.on(Endpoint.Port.tls()))
.map(endpointBuilder -> endpointBuilder.in(controller.system()))
.map(Endpoint::dnsName).forEach(endpointDnsNames::add);
return Collections.unmodifiableList(endpointDnsNames);
}
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<Deployment> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.filter(deployment -> ! deploymentSpec.includes(deployment.zone().environment(),
Optional.of(deployment.zone().region())))
.collect(Collectors.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(deployment -> deployment.zone().region().value())
.collect(Collectors.joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
for (Deployment deployment : deploymentsToRemove)
application = deactivate(application, instance, deployment.zone());
return application;
}
private Instance withoutUnreferencedDeploymentJobs(DeploymentSpec deploymentSpec, Instance instance) {
for (JobType job : JobList.from(instance).production().mapToList(JobStatus::type)) {
ZoneId zone = job.zone(controller.system());
if (deploymentSpec.includes(zone.environment(), Optional.of(zone.region())))
continue;
instance = instance.withoutDeploymentJob(job);
}
return instance;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/** Returns the endpoints of the deployment, or empty if the request fails */
public List<URI> getDeploymentEndpoints(DeploymentId deploymentId) {
if ( ! getInstance(deploymentId.applicationId())
.map(application -> application.deployments().containsKey(deploymentId.zoneId()))
.orElse(deploymentId.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", deploymentId.toString());
try {
return ImmutableList.copyOf(routingGenerator.endpoints(deploymentId).stream()
.map(RoutingEndpoint::endpoint)
.map(URI::create)
.iterator());
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e);
return Collections.emptyList();
}
}
/** Returns the non-empty endpoints per cluster in the given deployment, or empty if endpoints can't be found. */
public Map<ClusterSpec.Id, URI> clusterEndpoints(DeploymentId id) {
if ( ! getInstance(id.applicationId())
.map(application -> application.deployments().containsKey(id.zoneId()))
.orElse(id.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", id.toString());
try {
var endpoints = routingGenerator.clusterEndpoints(id);
if ( ! endpoints.isEmpty())
return endpoints;
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + id, e);
}
return routingPolicies.get(id).stream()
.filter(policy -> policy.endpointIn(controller.system()).scope() == Endpoint.Scope.zone)
.collect(Collectors.toUnmodifiableMap(policy -> policy.cluster(),
policy -> policy.endpointIn(controller.system()).url()));
}
/** Returns all zone-specific cluster endpoints for the given application, in the given zones. */
public Map<ZoneId, Map<ClusterSpec.Id, URI>> clusterEndpoints(ApplicationId id, Collection<ZoneId> zones) {
Map<ZoneId, Map<ClusterSpec.Id, URI>> deployments = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (ZoneId zone : zones) {
var endpoints = clusterEndpoints(new DeploymentId(id, zone));
if ( ! endpoints.isEmpty())
deployments.put(zone, endpoints);
}
return Collections.unmodifiableMap(deployments);
}
/**
* 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, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(id.tenant());
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + id + "': No credentials provided");
List<ApplicationId> instances = requireApplication(id).instances().keySet().stream()
.map(id::instance)
.collect(Collectors.toUnmodifiableList());
if (instances.size() > 1)
throw new IllegalArgumentException("Could not delete application; more than one instance present: " + instances);
for (ApplicationId instance : instances)
deleteInstance(instance);
if (tenant.type() != Tenant.Type.user)
accessControl.deleteApplication(id, credentials.get());
curator.removeApplication(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
*/
/**
* 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 {
routingPolicies.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(Application application, InstanceName instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = application.require(instance).deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! application.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).",
application.id().instance(instance), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/** Returns the rotation repository, used for managing global rotation assignments */
public RotationRepository rotationRepository() {
return rotationRepository;
}
public RoutingPolicies routingPolicies() {
return routingPolicies;
}
/**
* 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, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
applicationPackage.deploymentSpec().athenzDomain().ifPresent(identityDomain -> {
Tenant tenant = controller.tenants().require(tenantName);
deployer.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.ifPresentOrElse(user -> {
if ( ! ((AthenzFacade) accessControl).hasTenantAdminAccess(user, new AthenzDomain(identityDomain.value())))
throw new IllegalArgumentException("User " + user.getFullName() + " is not allowed to launch " +
"services in Athenz domain " + identityDomain.value() + ". " +
"Please reach out to the domain admin.");
},
() -> {
if (tenant.type() != Tenant.Type.athenz)
throw new IllegalArgumentException("Athenz domain defined in deployment.xml, but no " +
"Athenz domain for tenant " + tenantName.value());
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain.getName(), identityDomain.value()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.value() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
});
});
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(athenzDomain -> {
controller.zoneRegistry().zones().reachable().ids()
.forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService(zone.environment(), zone.region())
.map(service -> new AthenzService(athenzDomain.value(), service.value()))
.ifPresent(service -> {
boolean allowedToLaunch = ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, service);
if (!allowedToLaunch)
throw new IllegalArgumentException("Not allowed to launch Athenz service " + service.getFullName());
});
});
});
}
/** Returns the latest known version within the given major. */
private 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 RotationRepository rotationRepository;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final RoutingGenerator routingGenerator;
private final RoutingPolicies routingPolicies;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final BooleanFlag provisionApplicationCertificate;
private final DeploymentSpecValidator deploymentSpecValidator;
ApplicationController(Controller controller, CuratorDb curator,
AccessControl accessControl, RotationsConfig rotationsConfig,
Clock clock) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.routingGenerator = controller.serviceRegistry().routingGenerator();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
routingPolicies = new RoutingPolicies(controller);
rotationRepository = new RotationRepository(rotationsConfig, this, curator);
deploymentTrigger = new DeploymentTrigger(controller, controller.serviceRegistry().buildService(), clock);
provisionApplicationCertificate = Flags.PROVISION_APPLICATION_CERTIFICATE.bindTo(controller.flagSource());
deploymentSpecValidator = new DeploymentSpecValidator(controller);
Once.after(Duration.ofMinutes(1), () -> {
Instant start = clock.instant();
int count = 0;
for (Application application : curator.readApplications()) {
lockApplicationIfPresent(application.id(), this::store);
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 application with the given id, or null if it is not present */
public Optional<Application> getApplication(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id));
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(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();
}
/** 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 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());
}
/** Change the global endpoint status for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
findGlobalEndpoint(deployment).map(endpoint -> {
try {
configServer.setGlobalRotationStatus(deployment, endpoint.upstreamName(), status);
return endpoint;
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + deployment, e);
}
}).orElseThrow(() -> new IllegalArgumentException("No global endpoint exists for " + deployment));
}
/** Get global endpoint status for given deployment */
public Map<RoutingEndpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
return findGlobalEndpoint(deployment).map(endpoint -> {
try {
EndpointStatus status = configServer.getGlobalRotationStatus(deployment, endpoint.upstreamName());
return Map.of(endpoint, status);
} catch (Exception e) {
throw new RuntimeException("Failed to get rotation status of " + deployment, e);
}
}).orElseGet(Collections::emptyMap);
}
/** Find the global endpoint of given deployment, if any */
private Optional<RoutingEndpoint> findGlobalEndpoint(DeploymentId deployment) {
return routingGenerator.endpoints(deployment).stream()
.filter(RoutingEndpoint::isGlobal)
.findFirst();
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public Application createApplication(TenantAndApplicationId id, Optional<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());
Optional<Tenant> tenant = controller.tenants().get(id.tenant());
if (tenant.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
if (tenant.get().type() != Tenant.Type.user) {
if (credentials.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': No credentials provided");
accessControl.createApplication(id, credentials.get());
}
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) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
lockApplicationOrThrow(TenantAndApplicationId.from(id), 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");
store(application.withNewInstance(id.instance()));
log.info("Created " + id);
});
}
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options);
}
/** Deploys an application. If the application does not exist it is created. */
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 ( getApplication(applicationId).isEmpty()
&& controller.tenants().require(instanceId.tenant()).type() == Tenant.Type.user)
createApplication(applicationId, Optional.empty());
if (getInstance(instanceId).isEmpty())
createInstance(instanceId);
try (Lock deploymentLock = lockForDeployment(instanceId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<ApplicationCertificate> applicationCertificate;
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 + "."));
Optional<JobStatus> job = Optional.ofNullable(application.get().require(instance).deploymentJobs().jobStatus().get(jobType));
if ( job.isEmpty()
|| job.get().lastTriggered().isEmpty()
|| job.get().lastCompleted().isPresent() && job.get().lastCompleted().get().at().isAfter(job.get().lastTriggered().get().at()))
return unexpectedDeployment(instanceId, zone);
JobRun triggered = job.get().lastTriggered().get();
platformVersion = preferOldestVersion ? triggered.sourcePlatform().orElse(triggered.platform())
: triggered.platform();
applicationVersion = preferOldestVersion ? triggered.sourceApplication().orElse(triggered.application())
: triggered.application();
applicationPackage = getApplicationPackage(instanceId, application.get().internal(), applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, instanceId, jobType);
validateRun(application.get(), instance, zone, platformVersion, applicationVersion);
}
if (zone.environment().isProduction())
application = withRotation(application, instance);
endpoints = registerEndpointsInDns(application.get().deploymentSpec(), application.get().require(instanceId.instance()), zone);
if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
applicationCertificate = getApplicationCertificate(application.get().require(instance));
} else {
applicationCertificate = Optional.empty();
}
if ( ! preferOldestVersion
&& ! application.get().internal()
&& ! zone.environment().isManuallyDeployed()) {
storeWithUpdatedConfig(application, applicationPackage);
}
}
options = withVersion(platformVersion, options);
ActivateResult result = deploy(instanceId, applicationPackage, zone, options, endpoints,
applicationCertificate.orElse(null));
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, boolean internal, ApplicationVersion version) {
try {
return internal
? new ApplicationPackage(applicationStore.get(id, version))
: new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()));
}
catch (RuntimeException e) {
try {
log.info("Fetching application package for " + id + " from alternate repository; it is now deployed "
+ (internal ? "internally" : "externally") + "\nException was: " + Exceptions.toMessageString(e));
return internal
? new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()))
: new ApplicationPackage(applicationStore.get(id, version));
}
catch (RuntimeException s) {
e.addSuppressed(s);
throw e;
}
}
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public void storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
deploymentSpecValidator.validate(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
for (InstanceName instanceName : application.get().instances().keySet()) {
application = withoutDeletedDeployments(application, instanceName);
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
application = application.with(instanceName, instance -> withoutUnreferencedDeploymentJobs(deploymentSpec, instance));
}
store(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)
);
DeployOptions options = withVersion(version, DeployOptions.none());
return deploy(application.id(), applicationPackage, zone, options, Set.of(), /* No application cert */ null);
} 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, DeployOptions options) {
return deploy(tester.id(), applicationPackage, zone, options, Set.of(), /* No application cert for tester*/ null);
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, DeployOptions deployOptions, Set<ContainerEndpoint> endpoints,
ApplicationCertificate applicationCertificate) {
DeploymentId deploymentId = new DeploymentId(application, zone);
try {
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(deploymentId, deployOptions, Set.of(), endpoints, applicationCertificate, applicationPackage.zippedContent());
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
routingPolicies.refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
/** Makes sure the application has a global rotation, if eligible. */
private LockedApplication withRotation(LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(application.get().deploymentSpec(),
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
store(application);
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
private Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
var registerLegacyNames = deploymentSpec.globalServiceId().isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId())
.scope(Endpoint.Scope.global);
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
if (!registerLegacyNames) {
endpoints = endpoints.legacy(false);
}
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.asList().forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
private Optional<ApplicationCertificate> getApplicationCertificate(Instance instance) {
boolean provisionCertificate = provisionApplicationCertificate.with(FetchVector.Dimension.APPLICATION_ID,
instance.id().serializedForm()).value();
if (!provisionCertificate) {
return Optional.empty();
}
Optional<ApplicationCertificate> applicationCertificate = curator.readApplicationCertificate(instance.id());
if(applicationCertificate.isPresent())
return applicationCertificate;
ApplicationCertificate newCertificate = controller.serviceRegistry().applicationCertificateProvider().requestCaSignedCertificate(instance.id(), dnsNamesOf(instance.id()));
curator.writeApplicationCertificate(instance.id(), newCertificate);
return Optional.of(newCertificate);
}
/** Returns all valid DNS names of given application */
private List<String> dnsNamesOf(ApplicationId applicationId) {
List<String> endpointDnsNames = new ArrayList<>();
endpointDnsNames.add(Endpoint.createHashedCn(applicationId, controller.system()));
var globalDefaultEndpoint = Endpoint.of(applicationId).named(EndpointId.default_());
var rotationEndpoints = Endpoint.of(applicationId).wildcard();
var zoneLocalEndpoints = controller.zoneRegistry().zones().directlyRouted().zones().stream().flatMap(zone -> Stream.of(
Endpoint.of(applicationId).target(ClusterSpec.Id.from("default"), zone.getId()),
Endpoint.of(applicationId).wildcard(zone.getId())
));
Stream.concat(Stream.of(globalDefaultEndpoint, rotationEndpoints), zoneLocalEndpoints)
.map(Endpoint.EndpointBuilder::directRouting)
.map(endpoint -> endpoint.on(Endpoint.Port.tls()))
.map(endpointBuilder -> endpointBuilder.in(controller.system()))
.map(Endpoint::dnsName).forEach(endpointDnsNames::add);
return Collections.unmodifiableList(endpointDnsNames);
}
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<Deployment> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.filter(deployment -> ! deploymentSpec.includes(deployment.zone().environment(),
Optional.of(deployment.zone().region())))
.collect(Collectors.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(deployment -> deployment.zone().region().value())
.collect(Collectors.joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
for (Deployment deployment : deploymentsToRemove)
application = deactivate(application, instance, deployment.zone());
return application;
}
private Instance withoutUnreferencedDeploymentJobs(DeploymentSpec deploymentSpec, Instance instance) {
for (JobType job : JobList.from(instance).production().mapToList(JobStatus::type)) {
ZoneId zone = job.zone(controller.system());
if (deploymentSpec.includes(zone.environment(), Optional.of(zone.region())))
continue;
instance = instance.withoutDeploymentJob(job);
}
return instance;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/** Returns the endpoints of the deployment, or empty if the request fails */
public List<URI> getDeploymentEndpoints(DeploymentId deploymentId) {
if ( ! getInstance(deploymentId.applicationId())
.map(application -> application.deployments().containsKey(deploymentId.zoneId()))
.orElse(deploymentId.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", deploymentId.toString());
try {
return ImmutableList.copyOf(routingGenerator.endpoints(deploymentId).stream()
.map(RoutingEndpoint::endpoint)
.map(URI::create)
.iterator());
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e);
return Collections.emptyList();
}
}
/** Returns the non-empty endpoints per cluster in the given deployment, or empty if endpoints can't be found. */
public Map<ClusterSpec.Id, URI> clusterEndpoints(DeploymentId id) {
if ( ! getInstance(id.applicationId())
.map(application -> application.deployments().containsKey(id.zoneId()))
.orElse(id.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", id.toString());
try {
var endpoints = routingGenerator.clusterEndpoints(id);
if ( ! endpoints.isEmpty())
return endpoints;
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + id, e);
}
return routingPolicies.get(id).stream()
.filter(policy -> policy.endpointIn(controller.system()).scope() == Endpoint.Scope.zone)
.collect(Collectors.toUnmodifiableMap(policy -> policy.cluster(),
policy -> policy.endpointIn(controller.system()).url()));
}
/** Returns all zone-specific cluster endpoints for the given application, in the given zones. */
public Map<ZoneId, Map<ClusterSpec.Id, URI>> clusterEndpoints(ApplicationId id, Collection<ZoneId> zones) {
Map<ZoneId, Map<ClusterSpec.Id, URI>> deployments = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (ZoneId zone : zones) {
var endpoints = clusterEndpoints(new DeploymentId(id, zone));
if ( ! endpoints.isEmpty())
deployments.put(zone, endpoints);
}
return Collections.unmodifiableMap(deployments);
}
/**
* 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, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(id.tenant());
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + id + "': No credentials provided");
List<ApplicationId> instances = requireApplication(id).instances().keySet().stream()
.map(id::instance)
.collect(Collectors.toUnmodifiableList());
if (instances.size() > 1)
throw new IllegalArgumentException("Could not delete application; more than one instance present: " + instances);
for (ApplicationId instance : instances)
deleteInstance(instance);
if (tenant.type() != Tenant.Type.user)
accessControl.deleteApplication(id, credentials.get());
curator.removeApplication(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
*/
/**
* 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 {
routingPolicies.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(Application application, InstanceName instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = application.require(instance).deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! application.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).",
application.id().instance(instance), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/** Returns the rotation repository, used for managing global rotation assignments */
public RotationRepository rotationRepository() {
return rotationRepository;
}
public RoutingPolicies routingPolicies() {
return routingPolicies;
}
/**
* 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, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
applicationPackage.deploymentSpec().athenzDomain().ifPresent(identityDomain -> {
Tenant tenant = controller.tenants().require(tenantName);
deployer.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.ifPresentOrElse(user -> {
if ( ! ((AthenzFacade) accessControl).hasTenantAdminAccess(user, new AthenzDomain(identityDomain.value())))
throw new IllegalArgumentException("User " + user.getFullName() + " is not allowed to launch " +
"services in Athenz domain " + identityDomain.value() + ". " +
"Please reach out to the domain admin.");
},
() -> {
if (tenant.type() != Tenant.Type.athenz)
throw new IllegalArgumentException("Athenz domain defined in deployment.xml, but no " +
"Athenz domain for tenant " + tenantName.value());
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain.getName(), identityDomain.value()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.value() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
});
});
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(athenzDomain -> {
controller.zoneRegistry().zones().reachable().ids()
.forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService(zone.environment(), zone.region())
.map(service -> new AthenzService(athenzDomain.value(), service.value()))
.ifPresent(service -> {
boolean allowedToLaunch = ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, service);
if (!allowedToLaunch)
throw new IllegalArgumentException("Not allowed to launch Athenz service " + service.getFullName());
});
});
});
}
/** Returns the latest known version within the given major. */
private 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);
}
} |
If you change this to accept a `Stream` you can skip the intermediate lists. | private Collection<ResourceSnapshot> getAllResourceSnapshots() {
return controller().zoneRegistry().zones()
.ofCloud(CloudName.from("aws"))
.reachable().zones().stream()
.map(ZoneApi::getId)
.map(zoneId -> {
List<Node> nodes = nodeRepository.list(zoneId).stream()
.filter(node -> node.owner().isPresent())
.filter(node -> ! node.owner().get().tenant().value().equals("hosted-vespa"))
.collect(Collectors.toList());
return createResourceSnapshotsFromNodes(zoneId, nodes);
})
.flatMap(Collection::stream)
.collect(Collectors.toList());
} | return createResourceSnapshotsFromNodes(zoneId, nodes); | private Collection<ResourceSnapshot> getAllResourceSnapshots() {
return controller().zoneRegistry().zones()
.ofCloud(CloudName.from("aws"))
.reachable().zones().stream()
.map(ZoneApi::getId)
.map(zoneId -> createResourceSnapshotsFromNodes(zoneId, nodeRepository.list(zoneId)))
.flatMap(Collection::stream)
.collect(Collectors.toList());
} | class ResourceMeterMaintainer extends Maintainer {
private final Clock clock;
private final Metric metric;
private final NodeRepository nodeRepository;
private final MeteringClient meteringClient;
private static final String METERING_LAST_REPORTED = "metering_last_reported";
private static final String METERING_TOTAL_REPORTED = "metering_total_reported";
@SuppressWarnings("WeakerAccess")
public ResourceMeterMaintainer(Controller controller,
Duration interval,
JobControl jobControl,
Metric metric,
MeteringClient meteringClient) {
super(controller, interval, jobControl, null, SystemName.all());
this.clock = controller.clock();
this.nodeRepository = controller.serviceRegistry().configServer().nodeRepository();
this.metric = metric;
this.meteringClient = meteringClient;
}
@Override
protected void maintain() {
Collection<ResourceSnapshot> resourceSnapshots = getAllResourceSnapshots();
meteringClient.consume(resourceSnapshots);
metric.set(METERING_LAST_REPORTED, clock.millis() / 1000, metric.createContext(Collections.emptyMap()));
metric.set(METERING_TOTAL_REPORTED,
resourceSnapshots.stream()
.mapToDouble(r -> r.getCpuCores() + r.getMemoryGb() + r.getDiskGb()).sum(),
metric.createContext(Collections.emptyMap()));
}
private Collection<ResourceSnapshot> createResourceSnapshotsFromNodes(ZoneId zoneId, List<Node> nodes) {
return nodes.stream()
.collect(Collectors.groupingBy(node ->
node.owner().get(),
Collectors.collectingAndThen(Collectors.toList(),
nodeList -> ResourceSnapshot.from(
nodeList,
clock.instant(),
zoneId))
)).values();
}
} | class ResourceMeterMaintainer extends Maintainer {
private final Clock clock;
private final Metric metric;
private final NodeRepository nodeRepository;
private final MeteringClient meteringClient;
private static final String METERING_LAST_REPORTED = "metering_last_reported";
private static final String METERING_TOTAL_REPORTED = "metering_total_reported";
@SuppressWarnings("WeakerAccess")
public ResourceMeterMaintainer(Controller controller,
Duration interval,
JobControl jobControl,
Metric metric,
MeteringClient meteringClient) {
super(controller, interval, jobControl, null, SystemName.all());
this.clock = controller.clock();
this.nodeRepository = controller.serviceRegistry().configServer().nodeRepository();
this.metric = metric;
this.meteringClient = meteringClient;
}
@Override
protected void maintain() {
Collection<ResourceSnapshot> resourceSnapshots = getAllResourceSnapshots();
meteringClient.consume(resourceSnapshots);
metric.set(METERING_LAST_REPORTED, clock.millis() / 1000, metric.createContext(Collections.emptyMap()));
metric.set(METERING_TOTAL_REPORTED,
resourceSnapshots.stream()
.mapToDouble(r -> r.getCpuCores() + r.getMemoryGb() + r.getDiskGb()).sum(),
metric.createContext(Collections.emptyMap()));
}
private Collection<ResourceSnapshot> createResourceSnapshotsFromNodes(ZoneId zoneId, List<Node> nodes) {
return nodes.stream()
.filter(unlessNodeOwnerIsHostedVespa())
.collect(Collectors.groupingBy(node ->
node.owner().get(),
Collectors.collectingAndThen(Collectors.toList(),
nodeList -> ResourceSnapshot.from(
nodeList,
clock.instant(),
zoneId))
)).values();
}
private Predicate<Node> unlessNodeOwnerIsHostedVespa() {
return node -> node.owner().map(owner ->
!owner.tenant().value().equals("hosted-vespa")
).orElse(false);
}
} |
Capture predicate in a separate function `unlessNodeOwnerIsHostedVespa`? | private Collection<ResourceSnapshot> getAllResourceSnapshots() {
return controller().zoneRegistry().zones()
.ofCloud(CloudName.from("aws"))
.reachable().zones().stream()
.map(ZoneApi::getId)
.map(zoneId -> {
List<Node> nodes = nodeRepository.list(zoneId).stream()
.filter(node -> node.owner().isPresent())
.filter(node -> ! node.owner().get().tenant().value().equals("hosted-vespa"))
.collect(Collectors.toList());
return createResourceSnapshotsFromNodes(zoneId, nodes);
})
.flatMap(Collection::stream)
.collect(Collectors.toList());
} | .filter(node -> ! node.owner().get().tenant().value().equals("hosted-vespa")) | private Collection<ResourceSnapshot> getAllResourceSnapshots() {
return controller().zoneRegistry().zones()
.ofCloud(CloudName.from("aws"))
.reachable().zones().stream()
.map(ZoneApi::getId)
.map(zoneId -> createResourceSnapshotsFromNodes(zoneId, nodeRepository.list(zoneId)))
.flatMap(Collection::stream)
.collect(Collectors.toList());
} | class ResourceMeterMaintainer extends Maintainer {
private final Clock clock;
private final Metric metric;
private final NodeRepository nodeRepository;
private final MeteringClient meteringClient;
private static final String METERING_LAST_REPORTED = "metering_last_reported";
private static final String METERING_TOTAL_REPORTED = "metering_total_reported";
@SuppressWarnings("WeakerAccess")
public ResourceMeterMaintainer(Controller controller,
Duration interval,
JobControl jobControl,
Metric metric,
MeteringClient meteringClient) {
super(controller, interval, jobControl, null, SystemName.all());
this.clock = controller.clock();
this.nodeRepository = controller.serviceRegistry().configServer().nodeRepository();
this.metric = metric;
this.meteringClient = meteringClient;
}
@Override
protected void maintain() {
Collection<ResourceSnapshot> resourceSnapshots = getAllResourceSnapshots();
meteringClient.consume(resourceSnapshots);
metric.set(METERING_LAST_REPORTED, clock.millis() / 1000, metric.createContext(Collections.emptyMap()));
metric.set(METERING_TOTAL_REPORTED,
resourceSnapshots.stream()
.mapToDouble(r -> r.getCpuCores() + r.getMemoryGb() + r.getDiskGb()).sum(),
metric.createContext(Collections.emptyMap()));
}
private Collection<ResourceSnapshot> createResourceSnapshotsFromNodes(ZoneId zoneId, List<Node> nodes) {
return nodes.stream()
.collect(Collectors.groupingBy(node ->
node.owner().get(),
Collectors.collectingAndThen(Collectors.toList(),
nodeList -> ResourceSnapshot.from(
nodeList,
clock.instant(),
zoneId))
)).values();
}
} | class ResourceMeterMaintainer extends Maintainer {
private final Clock clock;
private final Metric metric;
private final NodeRepository nodeRepository;
private final MeteringClient meteringClient;
private static final String METERING_LAST_REPORTED = "metering_last_reported";
private static final String METERING_TOTAL_REPORTED = "metering_total_reported";
@SuppressWarnings("WeakerAccess")
public ResourceMeterMaintainer(Controller controller,
Duration interval,
JobControl jobControl,
Metric metric,
MeteringClient meteringClient) {
super(controller, interval, jobControl, null, SystemName.all());
this.clock = controller.clock();
this.nodeRepository = controller.serviceRegistry().configServer().nodeRepository();
this.metric = metric;
this.meteringClient = meteringClient;
}
@Override
protected void maintain() {
Collection<ResourceSnapshot> resourceSnapshots = getAllResourceSnapshots();
meteringClient.consume(resourceSnapshots);
metric.set(METERING_LAST_REPORTED, clock.millis() / 1000, metric.createContext(Collections.emptyMap()));
metric.set(METERING_TOTAL_REPORTED,
resourceSnapshots.stream()
.mapToDouble(r -> r.getCpuCores() + r.getMemoryGb() + r.getDiskGb()).sum(),
metric.createContext(Collections.emptyMap()));
}
private Collection<ResourceSnapshot> createResourceSnapshotsFromNodes(ZoneId zoneId, List<Node> nodes) {
return nodes.stream()
.filter(unlessNodeOwnerIsHostedVespa())
.collect(Collectors.groupingBy(node ->
node.owner().get(),
Collectors.collectingAndThen(Collectors.toList(),
nodeList -> ResourceSnapshot.from(
nodeList,
clock.instant(),
zoneId))
)).values();
}
private Predicate<Node> unlessNodeOwnerIsHostedVespa() {
return node -> node.owner().map(owner ->
!owner.tenant().value().equals("hosted-vespa")
).orElse(false);
}
} |
Should be if-else | public void run() {
log.info("Starting cluster monitor thread " + getName());
ExecutorService pingExecutor=Executors.newCachedThreadPool(ThreadFactoryFactory.getDaemonThreadFactory("search.ping"));
while (!isInterrupted()) {
try {
Thread.sleep(configuration.getCheckInterval());
log.finest("Activating ping");
ping(pingExecutor);
}
catch (Throwable e) {
if (shutdown && e instanceof InterruptedException) {
break;
} else {
log.log(Level.WARNING,"Exception in monitor thread", e);
if ( ! (e instanceof Exception) ) {
log.log(Level.WARNING,"Error in monitor thread, will quit", e);
break;
}
}
}
}
pingExecutor.shutdown();
try {
pingExecutor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) { }
log.info("Stopped cluster monitor thread " + getName());
} | } | public void run() {
log.info("Starting cluster monitor thread " + getName());
ExecutorService pingExecutor=Executors.newCachedThreadPool(ThreadFactoryFactory.getDaemonThreadFactory("search.ping"));
while (!isInterrupted()) {
try {
Thread.sleep(configuration.getCheckInterval());
log.finest("Activating ping");
ping(pingExecutor);
}
catch (Throwable e) {
if (shutdown && e instanceof InterruptedException) {
break;
} else if ( ! (e instanceof Exception) ) {
log.log(Level.WARNING,"Error in monitor thread, will quit", e);
break;
} else {
log.log(Level.WARNING,"Exception in monitor thread", e);
}
}
}
pingExecutor.shutdown();
try {
pingExecutor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) { }
log.info("Stopped cluster monitor thread " + getName());
} | class MonitorThread extends Thread {
MonitorThread(String name) {
super(name);
}
} | class MonitorThread extends Thread {
MonitorThread(String name) {
super(name);
}
} |
Fixed | public void run() {
log.info("Starting cluster monitor thread " + getName());
ExecutorService pingExecutor=Executors.newCachedThreadPool(ThreadFactoryFactory.getDaemonThreadFactory("search.ping"));
while (!isInterrupted()) {
try {
Thread.sleep(configuration.getCheckInterval());
log.finest("Activating ping");
ping(pingExecutor);
}
catch (Throwable e) {
if (shutdown && e instanceof InterruptedException) {
break;
} else {
log.log(Level.WARNING,"Exception in monitor thread", e);
if ( ! (e instanceof Exception) ) {
log.log(Level.WARNING,"Error in monitor thread, will quit", e);
break;
}
}
}
}
pingExecutor.shutdown();
try {
pingExecutor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) { }
log.info("Stopped cluster monitor thread " + getName());
} | } | public void run() {
log.info("Starting cluster monitor thread " + getName());
ExecutorService pingExecutor=Executors.newCachedThreadPool(ThreadFactoryFactory.getDaemonThreadFactory("search.ping"));
while (!isInterrupted()) {
try {
Thread.sleep(configuration.getCheckInterval());
log.finest("Activating ping");
ping(pingExecutor);
}
catch (Throwable e) {
if (shutdown && e instanceof InterruptedException) {
break;
} else if ( ! (e instanceof Exception) ) {
log.log(Level.WARNING,"Error in monitor thread, will quit", e);
break;
} else {
log.log(Level.WARNING,"Exception in monitor thread", e);
}
}
}
pingExecutor.shutdown();
try {
pingExecutor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) { }
log.info("Stopped cluster monitor thread " + getName());
} | class MonitorThread extends Thread {
MonitorThread(String name) {
super(name);
}
} | class MonitorThread extends Thread {
MonitorThread(String name) {
super(name);
}
} |
This assigns a `Path` to a `String`? | protected void setup() {
tenant = firstNonBlank(tenant, project.getProperties().getProperty("tenant"));
application = firstNonBlank(application, project.getProperties().getProperty("application"));
instance = firstNonBlank(instance, project.getProperties().getProperty("instance", "default"));
id = ApplicationId.from(tenant, application, instance);
if (privateKey == null || privateKey.isEmpty()) {
if (privateKeyFile == null || privateKeyFile.isEmpty()) {
throw new IllegalArgumentException("Missing 'privateKey' or 'privateKeyFile' properties.");
}
privateKey = Paths.get(privateKeyFile);
}
controller = certificateFile == null
? ControllerHttpClient.withSignatureKey(URI.create(endpoint), privateKey, id)
: ControllerHttpClient.withKeyAndCertificate(URI.create(endpoint), Paths.get(privateKeyFile), Paths.get(certificateFile));
} | privateKey = Paths.get(privateKeyFile); | protected void setup() {
tenant = firstNonBlank(tenant, project.getProperties().getProperty("tenant"));
application = firstNonBlank(application, project.getProperties().getProperty("application"));
instance = firstNonBlank(instance, project.getProperties().getProperty("instance", Properties.user()));
id = ApplicationId.from(tenant, application, instance);
if (privateKey != null) {
controller = ControllerHttpClient.withSignatureKey(URI.create(endpoint), privateKey, id);
} else if (privateKeyFile != null) {
controller = certificateFile == null
? ControllerHttpClient.withSignatureKey(URI.create(endpoint), Paths.get(privateKeyFile), id)
: ControllerHttpClient.withKeyAndCertificate(URI.create(endpoint), Paths.get(privateKeyFile), Paths.get(certificateFile));
} else {
throw new IllegalArgumentException("One of the properties 'privateKey' or 'privateKeyFile' is required.");
}
} | class AbstractVespaMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}", readonly = true)
protected MavenProject project;
@Parameter(property = "endpoint", defaultValue = "https:
protected String endpoint;
@Parameter(property = "tenant")
protected String tenant;
@Parameter(property = "application")
protected String application;
@Parameter(property = "instance")
protected String instance;
@Parameter(property = "privateKey")
protected String privateKey;
@Parameter(property = "privateKeyFile")
protected String privateKeyFile;
@Parameter(property = "certificateFile")
protected String certificateFile;
protected ApplicationId id;
protected ControllerHttpClient controller;
@Override
public final void execute() throws MojoExecutionException, MojoFailureException {
try {
setup();
doExecute();
}
catch (MojoFailureException | MojoExecutionException e) {
throw e;
}
catch (Exception e) {
throw new MojoExecutionException("Execution failed for application '" + id + "':", e);
}
}
/** Override this in subclasses, instead of {@link
protected abstract void doExecute() throws Exception;
protected String projectPathOf(String first, String... rest) {
return project.getBasedir().toPath().resolve(Path.of(first, rest)).toString();
}
/** Returns the first of the given strings which is non-null and non-blank, or throws IllegalArgumentException. */
protected static String firstNonBlank(String... values) {
for (String value : values)
if (value != null && ! value.isBlank())
return value;
throw new IllegalArgumentException("No valid value given");
}
} | class AbstractVespaMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}", readonly = true)
protected MavenProject project;
@Parameter(property = "endpoint", defaultValue = "https:
protected String endpoint;
@Parameter(property = "tenant")
protected String tenant;
@Parameter(property = "application")
protected String application;
@Parameter(property = "instance")
protected String instance;
@Parameter(property = "privateKey")
protected String privateKey;
@Parameter(property = "privateKeyFile")
protected String privateKeyFile;
@Parameter(property = "certificateFile")
protected String certificateFile;
protected ApplicationId id;
protected ControllerHttpClient controller;
@Override
public final void execute() throws MojoExecutionException, MojoFailureException {
try {
setup();
doExecute();
}
catch (MojoFailureException | MojoExecutionException e) {
throw e;
}
catch (Exception e) {
throw new MojoExecutionException("Execution failed for application '" + id + "':", e);
}
}
/** Override this in subclasses, instead of {@link
protected abstract void doExecute() throws Exception;
protected String projectPathOf(String first, String... rest) {
return project.getBasedir().toPath().resolve(Path.of(first, rest)).toString();
}
/** Returns the first of the given strings which is non-null and non-blank, or throws IllegalArgumentException. */
protected static String firstNonBlank(String... values) {
for (String value : values)
if (value != null && ! value.isBlank())
return value;
throw new IllegalArgumentException("No valid value given");
}
} |
```suggestion throw new IllegalArgumentException("One of the properties 'privateKey' or 'privateKeyFile' is required."); ``` | protected void setup() {
tenant = firstNonBlank(tenant, project.getProperties().getProperty("tenant"));
application = firstNonBlank(application, project.getProperties().getProperty("application"));
instance = firstNonBlank(instance, project.getProperties().getProperty("instance", "default"));
id = ApplicationId.from(tenant, application, instance);
if (privateKey == null || privateKey.isEmpty()) {
if (privateKeyFile == null || privateKeyFile.isEmpty()) {
throw new IllegalArgumentException("Missing 'privateKey' or 'privateKeyFile' properties.");
}
privateKey = Paths.get(privateKeyFile);
}
controller = certificateFile == null
? ControllerHttpClient.withSignatureKey(URI.create(endpoint), privateKey, id)
: ControllerHttpClient.withKeyAndCertificate(URI.create(endpoint), Paths.get(privateKeyFile), Paths.get(certificateFile));
} | throw new IllegalArgumentException("Missing 'privateKey' or 'privateKeyFile' properties."); | protected void setup() {
tenant = firstNonBlank(tenant, project.getProperties().getProperty("tenant"));
application = firstNonBlank(application, project.getProperties().getProperty("application"));
instance = firstNonBlank(instance, project.getProperties().getProperty("instance", Properties.user()));
id = ApplicationId.from(tenant, application, instance);
if (privateKey != null) {
controller = ControllerHttpClient.withSignatureKey(URI.create(endpoint), privateKey, id);
} else if (privateKeyFile != null) {
controller = certificateFile == null
? ControllerHttpClient.withSignatureKey(URI.create(endpoint), Paths.get(privateKeyFile), id)
: ControllerHttpClient.withKeyAndCertificate(URI.create(endpoint), Paths.get(privateKeyFile), Paths.get(certificateFile));
} else {
throw new IllegalArgumentException("One of the properties 'privateKey' or 'privateKeyFile' is required.");
}
} | class AbstractVespaMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}", readonly = true)
protected MavenProject project;
@Parameter(property = "endpoint", defaultValue = "https:
protected String endpoint;
@Parameter(property = "tenant")
protected String tenant;
@Parameter(property = "application")
protected String application;
@Parameter(property = "instance")
protected String instance;
@Parameter(property = "privateKey")
protected String privateKey;
@Parameter(property = "privateKeyFile")
protected String privateKeyFile;
@Parameter(property = "certificateFile")
protected String certificateFile;
protected ApplicationId id;
protected ControllerHttpClient controller;
@Override
public final void execute() throws MojoExecutionException, MojoFailureException {
try {
setup();
doExecute();
}
catch (MojoFailureException | MojoExecutionException e) {
throw e;
}
catch (Exception e) {
throw new MojoExecutionException("Execution failed for application '" + id + "':", e);
}
}
/** Override this in subclasses, instead of {@link
protected abstract void doExecute() throws Exception;
protected String projectPathOf(String first, String... rest) {
return project.getBasedir().toPath().resolve(Path.of(first, rest)).toString();
}
/** Returns the first of the given strings which is non-null and non-blank, or throws IllegalArgumentException. */
protected static String firstNonBlank(String... values) {
for (String value : values)
if (value != null && ! value.isBlank())
return value;
throw new IllegalArgumentException("No valid value given");
}
} | class AbstractVespaMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}", readonly = true)
protected MavenProject project;
@Parameter(property = "endpoint", defaultValue = "https:
protected String endpoint;
@Parameter(property = "tenant")
protected String tenant;
@Parameter(property = "application")
protected String application;
@Parameter(property = "instance")
protected String instance;
@Parameter(property = "privateKey")
protected String privateKey;
@Parameter(property = "privateKeyFile")
protected String privateKeyFile;
@Parameter(property = "certificateFile")
protected String certificateFile;
protected ApplicationId id;
protected ControllerHttpClient controller;
@Override
public final void execute() throws MojoExecutionException, MojoFailureException {
try {
setup();
doExecute();
}
catch (MojoFailureException | MojoExecutionException e) {
throw e;
}
catch (Exception e) {
throw new MojoExecutionException("Execution failed for application '" + id + "':", e);
}
}
/** Override this in subclasses, instead of {@link
protected abstract void doExecute() throws Exception;
protected String projectPathOf(String first, String... rest) {
return project.getBasedir().toPath().resolve(Path.of(first, rest)).toString();
}
/** Returns the first of the given strings which is non-null and non-blank, or throws IllegalArgumentException. */
protected static String firstNonBlank(String... values) {
for (String value : values)
if (value != null && ! value.isBlank())
return value;
throw new IllegalArgumentException("No valid value given");
}
} |
```suggestion ``` | public DeploymentInstanceSpec instance(InstanceName name) {
for (Step step : steps) {
if ( ! (step instanceof DeploymentInstanceSpec)) continue;
DeploymentInstanceSpec instanceStep = (DeploymentInstanceSpec)step;
if (instanceStep.name().equals(name))
return instanceStep;
}
return null;
} | DeploymentInstanceSpec instanceStep = (DeploymentInstanceSpec)step; | public DeploymentInstanceSpec instance(InstanceName name) {
for (DeploymentInstanceSpec instance : instances()) {
if (instance.name().equals(name))
return instance;
}
return null;
} | class DeploymentSpec {
/** The empty deployment spec, specifying no zones or rotation, and defaults for all settings */
public static final DeploymentSpec empty = new DeploymentSpec(Optional.empty(),
UpgradePolicy.defaultPolicy,
Optional.empty(),
Collections.emptyList(),
Collections.emptyList(),
"<deployment version='1.0'/>",
Optional.empty(),
Optional.empty(),
Notifications.none(),
List.of());
private final List<Step> steps;
private final Optional<Integer> majorVersion;
private final String xmlForm;
public DeploymentSpec(List<Step> steps,
Optional<Integer> majorVersion,
String xmlForm) {
if (singleInstance(steps)) {
var singleInstance = (DeploymentInstanceSpec)steps.get(0);
this.steps = List.of(singleInstance.withSteps(completeSteps(singleInstance.steps())));
}
else {
this.steps = List.copyOf(completeSteps(steps));
}
this.majorVersion = majorVersion;
this.xmlForm = xmlForm;
validateTotalDelay(steps);
}
public DeploymentSpec(Optional<String> globalServiceId, UpgradePolicy upgradePolicy, Optional<Integer> majorVersion,
List<ChangeBlocker> changeBlockers, List<Step> steps, String xmlForm,
Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService,
Notifications notifications,
List<Endpoint> endpoints) {
this(List.of(new DeploymentInstanceSpec(InstanceName.from("default"),
steps,
upgradePolicy,
changeBlockers,
globalServiceId,
athenzDomain,
athenzService,
notifications,
endpoints)),
majorVersion,
xmlForm);
}
/** Adds missing required steps and reorders steps to a permissible order */
private static List<DeploymentSpec.Step> completeSteps(List<DeploymentSpec.Step> inputSteps) {
List<Step> steps = new ArrayList<>(inputSteps);
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.prod)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.staging))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.staging));
}
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.staging)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.test))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.test));
}
DeploymentSpec.DeclaredZone testStep = remove(Environment.test, steps);
if (testStep != null)
steps.add(0, testStep);
DeploymentSpec.DeclaredZone stagingStep = remove(Environment.staging, steps);
if (stagingStep != null)
steps.add(1, stagingStep);
return steps;
}
/**
* Removes the first occurrence of a deployment step to the given environment and returns it.
*
* @return the removed step, or null if it is not present
*/
private static DeploymentSpec.DeclaredZone remove(Environment environment, List<DeploymentSpec.Step> steps) {
for (int i = 0; i < steps.size(); i++) {
if ( ! (steps.get(i) instanceof DeploymentSpec.DeclaredZone)) continue;
DeploymentSpec.DeclaredZone zoneStep = (DeploymentSpec.DeclaredZone)steps.get(i);
if (zoneStep.environment() == environment) {
steps.remove(i);
return zoneStep;
}
}
return null;
}
/** Throw an IllegalArgumentException if the total delay exceeds 24 hours */
private void validateTotalDelay(List<Step> steps) {
long totalDelaySeconds = steps.stream().mapToLong(step -> (step.delay().getSeconds())).sum();
if (totalDelaySeconds > Duration.ofHours(24).getSeconds())
throw new IllegalArgumentException("The total delay specified is " + Duration.ofSeconds(totalDelaySeconds) +
" but max 24 hours is allowed");
}
private DeploymentInstanceSpec defaultInstance() {
if (singleInstance(steps)) return (DeploymentInstanceSpec)steps.get(0);
throw new IllegalArgumentException("This deployment spec does not support the legacy API " +
"as it has multiple instances: " +
instances().stream().map(Step::toString).collect(Collectors.joining(",")));
}
public Optional<String> globalServiceId() { return defaultInstance().globalServiceId(); }
public UpgradePolicy upgradePolicy() { return defaultInstance().upgradePolicy(); }
/** Returns the major version this application is pinned to, or empty (default) to allow all major versions */
public Optional<Integer> majorVersion() { return majorVersion; }
public boolean canUpgradeAt(Instant instant) { return defaultInstance().canUpgradeAt(instant); }
public boolean canChangeRevisionAt(Instant instant) { return defaultInstance().canChangeRevisionAt(instant); }
public List<ChangeBlocker> changeBlocker() { return defaultInstance().changeBlocker(); }
/** Returns the deployment steps of this in the order they will be performed */
public List<Step> steps() {
if (singleInstance(steps)) return defaultInstance().steps();
return steps;
}
public List<DeclaredZone> zones() {
return defaultInstance().steps().stream()
.flatMap(step -> step.zones().stream())
.collect(Collectors.toList());
}
public Optional<AthenzDomain> athenzDomain() { return defaultInstance().athenzDomain(); }
public Optional<AthenzService> athenzService(Environment environment, RegionName region) {
return defaultInstance().athenzService(environment, region);
}
public Notifications notifications() { return defaultInstance().notifications(); }
public List<Endpoint> endpoints() { return defaultInstance().endpoints(); }
/** Returns the XML form of this spec, or null if it was not created by fromXml, nor is empty */
public String xmlForm() { return xmlForm; }
public boolean includes(Environment environment, Optional<RegionName> region) {
return defaultInstance().deploysTo(environment, region);
}
private static boolean singleInstance(List<DeploymentSpec.Step> steps) {
return steps.size() == 1 && steps.get(0) instanceof DeploymentInstanceSpec;
}
/** Returns the instance step containing the given instance name, or null if not present */
public DeploymentInstanceSpec instance(String name) {
return instance(InstanceName.from(name));
}
/** Returns the instance step containing the given instance name, or null if not present */
/** Returns the instance step containing the given instance name, or throws an IllegalArgumentException if not present */
public DeploymentInstanceSpec requireInstance(String name) {
return requireInstance(InstanceName.from(name));
}
public DeploymentInstanceSpec requireInstance(InstanceName name) {
DeploymentInstanceSpec instance = instance(name);
if (instance == null)
throw new IllegalArgumentException("No instance '" + name + "' in deployment.xml'. Instances: " +
instances().stream().map(spec -> spec.name().toString()).collect(Collectors.joining(",")));
return instance;
}
/** Returns the steps of this which are instances */
public List<DeploymentInstanceSpec> instances() {
return steps.stream()
.filter(step -> step instanceof DeploymentInstanceSpec).map(DeploymentInstanceSpec.class::cast)
.collect(Collectors.toList());
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(Reader reader) {
return new DeploymentSpecXmlReader().read(reader);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm) {
return fromXml(xmlForm, true);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm, boolean validate) {
return new DeploymentSpecXmlReader(validate).read(xmlForm);
}
public static String toMessageString(Throwable t) {
StringBuilder b = new StringBuilder();
String lastMessage = null;
String message;
for (; t != null; t = t.getCause()) {
message = t.getMessage();
if (message == null) continue;
if (message.equals(lastMessage)) continue;
if (b.length() > 0) {
b.append(": ");
}
b.append(message);
lastMessage = message;
}
return b.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeploymentSpec other = (DeploymentSpec) o;
return majorVersion.equals(other.majorVersion) &&
steps.equals(other.steps) &&
xmlForm.equals(other.xmlForm);
}
@Override
public int hashCode() {
return Objects.hash(majorVersion, steps, xmlForm);
}
/** This may be invoked by a continuous build */
public static void main(String[] args) {
if (args.length != 2 && args.length != 3) {
System.err.println("Usage: DeploymentSpec [file] [environment] [region]?" +
"Returns 0 if the specified zone matches the deployment spec, 1 otherwise");
System.exit(1);
}
try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) {
DeploymentSpec spec = DeploymentSpec.fromXml(reader);
Environment environment = Environment.from(args[1]);
Optional<RegionName> region = args.length == 3 ? Optional.of(RegionName.from(args[2])) : Optional.empty();
if (spec.includes(environment, region))
System.exit(0);
else
System.exit(1);
}
catch (Exception e) {
System.err.println("Exception checking deployment spec: " + toMessageString(e));
System.exit(1);
}
}
/** A deployment step */
public abstract static class Step {
/** Returns whether this step deploys to the given region */
public final boolean deploysTo(Environment environment) {
return deploysTo(environment, Optional.empty());
}
/** Returns whether this step deploys to the given environment, and (if specified) region */
public abstract boolean deploysTo(Environment environment, Optional<RegionName> region);
/** Returns the zones deployed to in this step */
public List<DeclaredZone> zones() { return Collections.emptyList(); }
/** The delay introduced by this step (beyond the time it takes to execute the step). Default is zero. */
public Duration delay() { return Duration.ZERO; }
/** Returns all the steps nested in this. This default implementatiino returns an empty list. */
public List<Step> steps() { return List.of(); }
}
/** A deployment step which is to wait for some time before progressing to the next step */
public static class Delay extends Step {
private final Duration duration;
public Delay(Duration duration) {
this.duration = duration;
}
public Duration duration() { return duration; }
@Override
public Duration delay() { return duration; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) { return false; }
@Override
public String toString() {
return "delay " + duration;
}
}
/** A deployment step which is to run deployment in a particular zone */
public static class DeclaredZone extends Step {
private final Environment environment;
private final Optional<RegionName> region;
private final boolean active;
private final Optional<AthenzService> athenzService;
private final Optional<String> testerFlavor;
public DeclaredZone(Environment environment) {
this(environment, Optional.empty(), false);
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active) {
this(environment, region, active, Optional.empty(), Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active, Optional<AthenzService> athenzService) {
this(environment, region, active, athenzService, Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active,
Optional<AthenzService> athenzService, Optional<String> testerFlavor) {
if (environment != Environment.prod && region.isPresent())
throw new IllegalArgumentException("Non-prod environments cannot specify a region");
if (environment == Environment.prod && region.isEmpty())
throw new IllegalArgumentException("Prod environments must be specified with a region");
this.environment = environment;
this.region = region;
this.active = active;
this.athenzService = athenzService;
this.testerFlavor = testerFlavor;
}
public Environment environment() { return environment; }
/** The region name, or empty if not declared */
public Optional<RegionName> region() { return region; }
/** Returns whether this zone should receive production traffic */
public boolean active() { return active; }
public Optional<String> testerFlavor() { return testerFlavor; }
public Optional<AthenzService> athenzService() { return athenzService; }
@Override
public List<DeclaredZone> zones() { return Collections.singletonList(this); }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
if (environment != this.environment) return false;
if (region.isPresent() && ! region.equals(this.region)) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hash(environment, region);
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if ( ! (o instanceof DeclaredZone)) return false;
DeclaredZone other = (DeclaredZone)o;
if (this.environment != other.environment) return false;
if ( ! this.region.equals(other.region())) return false;
return true;
}
@Override
public String toString() {
return environment + (region.map(regionName -> "." + regionName).orElse(""));
}
}
/** A deployment step which is to run multiple steps (zones or instances) in parallel */
public static class ParallelZones extends Step {
private final List<Step> steps;
public ParallelZones(List<Step> steps) {
this.steps = List.copyOf(steps);
}
/** Returns the steps inside this which are zones */
@Override
public List<DeclaredZone> zones() {
return this.steps.stream()
.filter(step -> step instanceof DeclaredZone)
.map(DeclaredZone.class::cast)
.collect(Collectors.toList());
}
/** Returns all the steps nested in this */
@Override
public List<Step> steps() { return steps; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
return steps().stream().anyMatch(zone -> zone.deploysTo(environment, region));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ParallelZones)) return false;
ParallelZones that = (ParallelZones) o;
return Objects.equals(steps, that.steps);
}
@Override
public int hashCode() {
return Objects.hash(steps);
}
@Override
public String toString() {
return steps.size() + " parallel steps";
}
}
/** Controls when this application will be upgraded to new Vespa versions */
public enum UpgradePolicy {
/** Canary: Applications with this policy will upgrade before any other */
canary,
/** Default: Will upgrade after all canary applications upgraded successfully. The default. */
defaultPolicy,
/** Will upgrade after most default applications upgraded successfully */
conservative
}
/** A blocking of changes in a given time window */
public static class ChangeBlocker {
private final boolean revision;
private final boolean version;
private final TimeWindow window;
public ChangeBlocker(boolean revision, boolean version, TimeWindow window) {
this.revision = revision;
this.version = version;
this.window = window;
}
public boolean blocksRevisions() { return revision; }
public boolean blocksVersions() { return version; }
public TimeWindow window() { return window; }
@Override
public String toString() {
return "change blocker revision=" + revision + " version=" + version + " window=" + window;
}
}
} | class DeploymentSpec {
/** The empty deployment spec, specifying no zones or rotation, and defaults for all settings */
public static final DeploymentSpec empty = new DeploymentSpec(Optional.empty(),
UpgradePolicy.defaultPolicy,
Optional.empty(),
Collections.emptyList(),
Collections.emptyList(),
"<deployment version='1.0'/>",
Optional.empty(),
Optional.empty(),
Notifications.none(),
List.of());
private final List<Step> steps;
private final Optional<Integer> majorVersion;
private final String xmlForm;
public DeploymentSpec(List<Step> steps,
Optional<Integer> majorVersion,
String xmlForm) {
if (singleInstance(steps)) {
var singleInstance = (DeploymentInstanceSpec)steps.get(0);
this.steps = List.of(singleInstance.withSteps(completeSteps(singleInstance.steps())));
}
else {
this.steps = List.copyOf(completeSteps(steps));
}
this.majorVersion = majorVersion;
this.xmlForm = xmlForm;
validateTotalDelay(steps);
}
public DeploymentSpec(Optional<String> globalServiceId, UpgradePolicy upgradePolicy, Optional<Integer> majorVersion,
List<ChangeBlocker> changeBlockers, List<Step> steps, String xmlForm,
Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService,
Notifications notifications,
List<Endpoint> endpoints) {
this(List.of(new DeploymentInstanceSpec(InstanceName.from("default"),
steps,
upgradePolicy,
changeBlockers,
globalServiceId,
athenzDomain,
athenzService,
notifications,
endpoints)),
majorVersion,
xmlForm);
}
/** Adds missing required steps and reorders steps to a permissible order */
private static List<DeploymentSpec.Step> completeSteps(List<DeploymentSpec.Step> inputSteps) {
List<Step> steps = new ArrayList<>(inputSteps);
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.prod)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.staging))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.staging));
}
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.staging)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.test))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.test));
}
DeploymentSpec.DeclaredZone testStep = remove(Environment.test, steps);
if (testStep != null)
steps.add(0, testStep);
DeploymentSpec.DeclaredZone stagingStep = remove(Environment.staging, steps);
if (stagingStep != null)
steps.add(1, stagingStep);
return steps;
}
/**
* Removes the first occurrence of a deployment step to the given environment and returns it.
*
* @return the removed step, or null if it is not present
*/
private static DeploymentSpec.DeclaredZone remove(Environment environment, List<DeploymentSpec.Step> steps) {
for (int i = 0; i < steps.size(); i++) {
if ( ! (steps.get(i) instanceof DeploymentSpec.DeclaredZone)) continue;
DeploymentSpec.DeclaredZone zoneStep = (DeploymentSpec.DeclaredZone)steps.get(i);
if (zoneStep.environment() == environment) {
steps.remove(i);
return zoneStep;
}
}
return null;
}
/** Throw an IllegalArgumentException if the total delay exceeds 24 hours */
private void validateTotalDelay(List<Step> steps) {
long totalDelaySeconds = steps.stream().mapToLong(step -> (step.delay().getSeconds())).sum();
if (totalDelaySeconds > Duration.ofHours(24).getSeconds())
throw new IllegalArgumentException("The total delay specified is " + Duration.ofSeconds(totalDelaySeconds) +
" but max 24 hours is allowed");
}
private DeploymentInstanceSpec defaultInstance() {
if (singleInstance(steps)) return (DeploymentInstanceSpec)steps.get(0);
throw new IllegalArgumentException("This deployment spec does not support the legacy API " +
"as it has multiple instances: " +
instances().stream().map(Step::toString).collect(Collectors.joining(",")));
}
public Optional<String> globalServiceId() { return defaultInstance().globalServiceId(); }
public UpgradePolicy upgradePolicy() { return defaultInstance().upgradePolicy(); }
/** Returns the major version this application is pinned to, or empty (default) to allow all major versions */
public Optional<Integer> majorVersion() { return majorVersion; }
public boolean canUpgradeAt(Instant instant) { return defaultInstance().canUpgradeAt(instant); }
public boolean canChangeRevisionAt(Instant instant) { return defaultInstance().canChangeRevisionAt(instant); }
public List<ChangeBlocker> changeBlocker() { return defaultInstance().changeBlocker(); }
/** Returns the deployment steps of this in the order they will be performed */
public List<Step> steps() {
if (singleInstance(steps)) return defaultInstance().steps();
return steps;
}
public List<DeclaredZone> zones() {
return defaultInstance().steps().stream()
.flatMap(step -> step.zones().stream())
.collect(Collectors.toList());
}
public Optional<AthenzDomain> athenzDomain() { return defaultInstance().athenzDomain(); }
public Optional<AthenzService> athenzService(Environment environment, RegionName region) {
return defaultInstance().athenzService(environment, region);
}
public Notifications notifications() { return defaultInstance().notifications(); }
public List<Endpoint> endpoints() { return defaultInstance().endpoints(); }
/** Returns the XML form of this spec, or null if it was not created by fromXml, nor is empty */
public String xmlForm() { return xmlForm; }
public boolean includes(Environment environment, Optional<RegionName> region) {
return defaultInstance().deploysTo(environment, region);
}
private static boolean singleInstance(List<DeploymentSpec.Step> steps) {
return steps.size() == 1 && steps.get(0) instanceof DeploymentInstanceSpec;
}
/** Returns the instance step containing the given instance name, or null if not present */
public DeploymentInstanceSpec instance(String name) {
return instance(InstanceName.from(name));
}
/** Returns the instance step containing the given instance name, or null if not present */
/** Returns the instance step containing the given instance name, or throws an IllegalArgumentException if not present */
public DeploymentInstanceSpec requireInstance(String name) {
return requireInstance(InstanceName.from(name));
}
public DeploymentInstanceSpec requireInstance(InstanceName name) {
DeploymentInstanceSpec instance = instance(name);
if (instance == null)
throw new IllegalArgumentException("No instance '" + name + "' in deployment.xml'. Instances: " +
instances().stream().map(spec -> spec.name().toString()).collect(Collectors.joining(",")));
return instance;
}
/** Returns the steps of this which are instances */
public List<DeploymentInstanceSpec> instances() {
return steps.stream()
.filter(step -> step instanceof DeploymentInstanceSpec).map(DeploymentInstanceSpec.class::cast)
.collect(Collectors.toList());
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(Reader reader) {
return new DeploymentSpecXmlReader().read(reader);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm) {
return fromXml(xmlForm, true);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm, boolean validate) {
return new DeploymentSpecXmlReader(validate).read(xmlForm);
}
public static String toMessageString(Throwable t) {
StringBuilder b = new StringBuilder();
String lastMessage = null;
String message;
for (; t != null; t = t.getCause()) {
message = t.getMessage();
if (message == null) continue;
if (message.equals(lastMessage)) continue;
if (b.length() > 0) {
b.append(": ");
}
b.append(message);
lastMessage = message;
}
return b.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeploymentSpec other = (DeploymentSpec) o;
return majorVersion.equals(other.majorVersion) &&
steps.equals(other.steps) &&
xmlForm.equals(other.xmlForm);
}
@Override
public int hashCode() {
return Objects.hash(majorVersion, steps, xmlForm);
}
/** This may be invoked by a continuous build */
public static void main(String[] args) {
if (args.length != 2 && args.length != 3) {
System.err.println("Usage: DeploymentSpec [file] [environment] [region]?" +
"Returns 0 if the specified zone matches the deployment spec, 1 otherwise");
System.exit(1);
}
try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) {
DeploymentSpec spec = DeploymentSpec.fromXml(reader);
Environment environment = Environment.from(args[1]);
Optional<RegionName> region = args.length == 3 ? Optional.of(RegionName.from(args[2])) : Optional.empty();
if (spec.includes(environment, region))
System.exit(0);
else
System.exit(1);
}
catch (Exception e) {
System.err.println("Exception checking deployment spec: " + toMessageString(e));
System.exit(1);
}
}
/** A deployment step */
public abstract static class Step {
/** Returns whether this step deploys to the given region */
public final boolean deploysTo(Environment environment) {
return deploysTo(environment, Optional.empty());
}
/** Returns whether this step deploys to the given environment, and (if specified) region */
public abstract boolean deploysTo(Environment environment, Optional<RegionName> region);
/** Returns the zones deployed to in this step */
public List<DeclaredZone> zones() { return Collections.emptyList(); }
/** The delay introduced by this step (beyond the time it takes to execute the step). Default is zero. */
public Duration delay() { return Duration.ZERO; }
/** Returns all the steps nested in this. This default implementatiino returns an empty list. */
public List<Step> steps() { return List.of(); }
}
/** A deployment step which is to wait for some time before progressing to the next step */
public static class Delay extends Step {
private final Duration duration;
public Delay(Duration duration) {
this.duration = duration;
}
public Duration duration() { return duration; }
@Override
public Duration delay() { return duration; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) { return false; }
@Override
public String toString() {
return "delay " + duration;
}
}
/** A deployment step which is to run deployment in a particular zone */
public static class DeclaredZone extends Step {
private final Environment environment;
private final Optional<RegionName> region;
private final boolean active;
private final Optional<AthenzService> athenzService;
private final Optional<String> testerFlavor;
public DeclaredZone(Environment environment) {
this(environment, Optional.empty(), false);
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active) {
this(environment, region, active, Optional.empty(), Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active, Optional<AthenzService> athenzService) {
this(environment, region, active, athenzService, Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active,
Optional<AthenzService> athenzService, Optional<String> testerFlavor) {
if (environment != Environment.prod && region.isPresent())
throw new IllegalArgumentException("Non-prod environments cannot specify a region");
if (environment == Environment.prod && region.isEmpty())
throw new IllegalArgumentException("Prod environments must be specified with a region");
this.environment = environment;
this.region = region;
this.active = active;
this.athenzService = athenzService;
this.testerFlavor = testerFlavor;
}
public Environment environment() { return environment; }
/** The region name, or empty if not declared */
public Optional<RegionName> region() { return region; }
/** Returns whether this zone should receive production traffic */
public boolean active() { return active; }
public Optional<String> testerFlavor() { return testerFlavor; }
public Optional<AthenzService> athenzService() { return athenzService; }
@Override
public List<DeclaredZone> zones() { return Collections.singletonList(this); }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
if (environment != this.environment) return false;
if (region.isPresent() && ! region.equals(this.region)) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hash(environment, region);
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if ( ! (o instanceof DeclaredZone)) return false;
DeclaredZone other = (DeclaredZone)o;
if (this.environment != other.environment) return false;
if ( ! this.region.equals(other.region())) return false;
return true;
}
@Override
public String toString() {
return environment + (region.map(regionName -> "." + regionName).orElse(""));
}
}
/** A deployment step which is to run multiple steps (zones or instances) in parallel */
public static class ParallelZones extends Step {
private final List<Step> steps;
public ParallelZones(List<Step> steps) {
this.steps = List.copyOf(steps);
}
/** Returns the steps inside this which are zones */
@Override
public List<DeclaredZone> zones() {
return this.steps.stream()
.filter(step -> step instanceof DeclaredZone)
.map(DeclaredZone.class::cast)
.collect(Collectors.toList());
}
/** Returns all the steps nested in this */
@Override
public List<Step> steps() { return steps; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
return steps().stream().anyMatch(zone -> zone.deploysTo(environment, region));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ParallelZones)) return false;
ParallelZones that = (ParallelZones) o;
return Objects.equals(steps, that.steps);
}
@Override
public int hashCode() {
return Objects.hash(steps);
}
@Override
public String toString() {
return steps.size() + " parallel steps";
}
}
/** Controls when this application will be upgraded to new Vespa versions */
public enum UpgradePolicy {
/** Canary: Applications with this policy will upgrade before any other */
canary,
/** Default: Will upgrade after all canary applications upgraded successfully. The default. */
defaultPolicy,
/** Will upgrade after most default applications upgraded successfully */
conservative
}
/** A blocking of changes in a given time window */
public static class ChangeBlocker {
private final boolean revision;
private final boolean version;
private final TimeWindow window;
public ChangeBlocker(boolean revision, boolean version, TimeWindow window) {
this.revision = revision;
this.version = version;
this.window = window;
}
public boolean blocksRevisions() { return revision; }
public boolean blocksVersions() { return version; }
public TimeWindow window() { return window; }
@Override
public String toString() {
return "change blocker revision=" + revision + " version=" + version + " window=" + window;
}
}
} |
```suggestion ``` | public DeploymentInstanceSpec instance(InstanceName name) {
for (Step step : steps) {
if ( ! (step instanceof DeploymentInstanceSpec)) continue;
DeploymentInstanceSpec instanceStep = (DeploymentInstanceSpec)step;
if (instanceStep.name().equals(name))
return instanceStep;
}
return null;
} | if ( ! (step instanceof DeploymentInstanceSpec)) continue; | public DeploymentInstanceSpec instance(InstanceName name) {
for (DeploymentInstanceSpec instance : instances()) {
if (instance.name().equals(name))
return instance;
}
return null;
} | class DeploymentSpec {
/** The empty deployment spec, specifying no zones or rotation, and defaults for all settings */
public static final DeploymentSpec empty = new DeploymentSpec(Optional.empty(),
UpgradePolicy.defaultPolicy,
Optional.empty(),
Collections.emptyList(),
Collections.emptyList(),
"<deployment version='1.0'/>",
Optional.empty(),
Optional.empty(),
Notifications.none(),
List.of());
private final List<Step> steps;
private final Optional<Integer> majorVersion;
private final String xmlForm;
public DeploymentSpec(List<Step> steps,
Optional<Integer> majorVersion,
String xmlForm) {
if (singleInstance(steps)) {
var singleInstance = (DeploymentInstanceSpec)steps.get(0);
this.steps = List.of(singleInstance.withSteps(completeSteps(singleInstance.steps())));
}
else {
this.steps = List.copyOf(completeSteps(steps));
}
this.majorVersion = majorVersion;
this.xmlForm = xmlForm;
validateTotalDelay(steps);
}
public DeploymentSpec(Optional<String> globalServiceId, UpgradePolicy upgradePolicy, Optional<Integer> majorVersion,
List<ChangeBlocker> changeBlockers, List<Step> steps, String xmlForm,
Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService,
Notifications notifications,
List<Endpoint> endpoints) {
this(List.of(new DeploymentInstanceSpec(InstanceName.from("default"),
steps,
upgradePolicy,
changeBlockers,
globalServiceId,
athenzDomain,
athenzService,
notifications,
endpoints)),
majorVersion,
xmlForm);
}
/** Adds missing required steps and reorders steps to a permissible order */
private static List<DeploymentSpec.Step> completeSteps(List<DeploymentSpec.Step> inputSteps) {
List<Step> steps = new ArrayList<>(inputSteps);
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.prod)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.staging))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.staging));
}
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.staging)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.test))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.test));
}
DeploymentSpec.DeclaredZone testStep = remove(Environment.test, steps);
if (testStep != null)
steps.add(0, testStep);
DeploymentSpec.DeclaredZone stagingStep = remove(Environment.staging, steps);
if (stagingStep != null)
steps.add(1, stagingStep);
return steps;
}
/**
* Removes the first occurrence of a deployment step to the given environment and returns it.
*
* @return the removed step, or null if it is not present
*/
private static DeploymentSpec.DeclaredZone remove(Environment environment, List<DeploymentSpec.Step> steps) {
for (int i = 0; i < steps.size(); i++) {
if ( ! (steps.get(i) instanceof DeploymentSpec.DeclaredZone)) continue;
DeploymentSpec.DeclaredZone zoneStep = (DeploymentSpec.DeclaredZone)steps.get(i);
if (zoneStep.environment() == environment) {
steps.remove(i);
return zoneStep;
}
}
return null;
}
/** Throw an IllegalArgumentException if the total delay exceeds 24 hours */
private void validateTotalDelay(List<Step> steps) {
long totalDelaySeconds = steps.stream().mapToLong(step -> (step.delay().getSeconds())).sum();
if (totalDelaySeconds > Duration.ofHours(24).getSeconds())
throw new IllegalArgumentException("The total delay specified is " + Duration.ofSeconds(totalDelaySeconds) +
" but max 24 hours is allowed");
}
private DeploymentInstanceSpec defaultInstance() {
if (singleInstance(steps)) return (DeploymentInstanceSpec)steps.get(0);
throw new IllegalArgumentException("This deployment spec does not support the legacy API " +
"as it has multiple instances: " +
instances().stream().map(Step::toString).collect(Collectors.joining(",")));
}
public Optional<String> globalServiceId() { return defaultInstance().globalServiceId(); }
public UpgradePolicy upgradePolicy() { return defaultInstance().upgradePolicy(); }
/** Returns the major version this application is pinned to, or empty (default) to allow all major versions */
public Optional<Integer> majorVersion() { return majorVersion; }
public boolean canUpgradeAt(Instant instant) { return defaultInstance().canUpgradeAt(instant); }
public boolean canChangeRevisionAt(Instant instant) { return defaultInstance().canChangeRevisionAt(instant); }
public List<ChangeBlocker> changeBlocker() { return defaultInstance().changeBlocker(); }
/** Returns the deployment steps of this in the order they will be performed */
public List<Step> steps() {
if (singleInstance(steps)) return defaultInstance().steps();
return steps;
}
public List<DeclaredZone> zones() {
return defaultInstance().steps().stream()
.flatMap(step -> step.zones().stream())
.collect(Collectors.toList());
}
public Optional<AthenzDomain> athenzDomain() { return defaultInstance().athenzDomain(); }
public Optional<AthenzService> athenzService(Environment environment, RegionName region) {
return defaultInstance().athenzService(environment, region);
}
public Notifications notifications() { return defaultInstance().notifications(); }
public List<Endpoint> endpoints() { return defaultInstance().endpoints(); }
/** Returns the XML form of this spec, or null if it was not created by fromXml, nor is empty */
public String xmlForm() { return xmlForm; }
public boolean includes(Environment environment, Optional<RegionName> region) {
return defaultInstance().deploysTo(environment, region);
}
private static boolean singleInstance(List<DeploymentSpec.Step> steps) {
return steps.size() == 1 && steps.get(0) instanceof DeploymentInstanceSpec;
}
/** Returns the instance step containing the given instance name, or null if not present */
public DeploymentInstanceSpec instance(String name) {
return instance(InstanceName.from(name));
}
/** Returns the instance step containing the given instance name, or null if not present */
/** Returns the instance step containing the given instance name, or throws an IllegalArgumentException if not present */
public DeploymentInstanceSpec requireInstance(String name) {
return requireInstance(InstanceName.from(name));
}
public DeploymentInstanceSpec requireInstance(InstanceName name) {
DeploymentInstanceSpec instance = instance(name);
if (instance == null)
throw new IllegalArgumentException("No instance '" + name + "' in deployment.xml'. Instances: " +
instances().stream().map(spec -> spec.name().toString()).collect(Collectors.joining(",")));
return instance;
}
/** Returns the steps of this which are instances */
public List<DeploymentInstanceSpec> instances() {
return steps.stream()
.filter(step -> step instanceof DeploymentInstanceSpec).map(DeploymentInstanceSpec.class::cast)
.collect(Collectors.toList());
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(Reader reader) {
return new DeploymentSpecXmlReader().read(reader);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm) {
return fromXml(xmlForm, true);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm, boolean validate) {
return new DeploymentSpecXmlReader(validate).read(xmlForm);
}
public static String toMessageString(Throwable t) {
StringBuilder b = new StringBuilder();
String lastMessage = null;
String message;
for (; t != null; t = t.getCause()) {
message = t.getMessage();
if (message == null) continue;
if (message.equals(lastMessage)) continue;
if (b.length() > 0) {
b.append(": ");
}
b.append(message);
lastMessage = message;
}
return b.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeploymentSpec other = (DeploymentSpec) o;
return majorVersion.equals(other.majorVersion) &&
steps.equals(other.steps) &&
xmlForm.equals(other.xmlForm);
}
@Override
public int hashCode() {
return Objects.hash(majorVersion, steps, xmlForm);
}
/** This may be invoked by a continuous build */
public static void main(String[] args) {
if (args.length != 2 && args.length != 3) {
System.err.println("Usage: DeploymentSpec [file] [environment] [region]?" +
"Returns 0 if the specified zone matches the deployment spec, 1 otherwise");
System.exit(1);
}
try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) {
DeploymentSpec spec = DeploymentSpec.fromXml(reader);
Environment environment = Environment.from(args[1]);
Optional<RegionName> region = args.length == 3 ? Optional.of(RegionName.from(args[2])) : Optional.empty();
if (spec.includes(environment, region))
System.exit(0);
else
System.exit(1);
}
catch (Exception e) {
System.err.println("Exception checking deployment spec: " + toMessageString(e));
System.exit(1);
}
}
/** A deployment step */
public abstract static class Step {
/** Returns whether this step deploys to the given region */
public final boolean deploysTo(Environment environment) {
return deploysTo(environment, Optional.empty());
}
/** Returns whether this step deploys to the given environment, and (if specified) region */
public abstract boolean deploysTo(Environment environment, Optional<RegionName> region);
/** Returns the zones deployed to in this step */
public List<DeclaredZone> zones() { return Collections.emptyList(); }
/** The delay introduced by this step (beyond the time it takes to execute the step). Default is zero. */
public Duration delay() { return Duration.ZERO; }
/** Returns all the steps nested in this. This default implementatiino returns an empty list. */
public List<Step> steps() { return List.of(); }
}
/** A deployment step which is to wait for some time before progressing to the next step */
public static class Delay extends Step {
private final Duration duration;
public Delay(Duration duration) {
this.duration = duration;
}
public Duration duration() { return duration; }
@Override
public Duration delay() { return duration; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) { return false; }
@Override
public String toString() {
return "delay " + duration;
}
}
/** A deployment step which is to run deployment in a particular zone */
public static class DeclaredZone extends Step {
private final Environment environment;
private final Optional<RegionName> region;
private final boolean active;
private final Optional<AthenzService> athenzService;
private final Optional<String> testerFlavor;
public DeclaredZone(Environment environment) {
this(environment, Optional.empty(), false);
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active) {
this(environment, region, active, Optional.empty(), Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active, Optional<AthenzService> athenzService) {
this(environment, region, active, athenzService, Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active,
Optional<AthenzService> athenzService, Optional<String> testerFlavor) {
if (environment != Environment.prod && region.isPresent())
throw new IllegalArgumentException("Non-prod environments cannot specify a region");
if (environment == Environment.prod && region.isEmpty())
throw new IllegalArgumentException("Prod environments must be specified with a region");
this.environment = environment;
this.region = region;
this.active = active;
this.athenzService = athenzService;
this.testerFlavor = testerFlavor;
}
public Environment environment() { return environment; }
/** The region name, or empty if not declared */
public Optional<RegionName> region() { return region; }
/** Returns whether this zone should receive production traffic */
public boolean active() { return active; }
public Optional<String> testerFlavor() { return testerFlavor; }
public Optional<AthenzService> athenzService() { return athenzService; }
@Override
public List<DeclaredZone> zones() { return Collections.singletonList(this); }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
if (environment != this.environment) return false;
if (region.isPresent() && ! region.equals(this.region)) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hash(environment, region);
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if ( ! (o instanceof DeclaredZone)) return false;
DeclaredZone other = (DeclaredZone)o;
if (this.environment != other.environment) return false;
if ( ! this.region.equals(other.region())) return false;
return true;
}
@Override
public String toString() {
return environment + (region.map(regionName -> "." + regionName).orElse(""));
}
}
/** A deployment step which is to run multiple steps (zones or instances) in parallel */
public static class ParallelZones extends Step {
private final List<Step> steps;
public ParallelZones(List<Step> steps) {
this.steps = List.copyOf(steps);
}
/** Returns the steps inside this which are zones */
@Override
public List<DeclaredZone> zones() {
return this.steps.stream()
.filter(step -> step instanceof DeclaredZone)
.map(DeclaredZone.class::cast)
.collect(Collectors.toList());
}
/** Returns all the steps nested in this */
@Override
public List<Step> steps() { return steps; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
return steps().stream().anyMatch(zone -> zone.deploysTo(environment, region));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ParallelZones)) return false;
ParallelZones that = (ParallelZones) o;
return Objects.equals(steps, that.steps);
}
@Override
public int hashCode() {
return Objects.hash(steps);
}
@Override
public String toString() {
return steps.size() + " parallel steps";
}
}
/** Controls when this application will be upgraded to new Vespa versions */
public enum UpgradePolicy {
/** Canary: Applications with this policy will upgrade before any other */
canary,
/** Default: Will upgrade after all canary applications upgraded successfully. The default. */
defaultPolicy,
/** Will upgrade after most default applications upgraded successfully */
conservative
}
/** A blocking of changes in a given time window */
public static class ChangeBlocker {
private final boolean revision;
private final boolean version;
private final TimeWindow window;
public ChangeBlocker(boolean revision, boolean version, TimeWindow window) {
this.revision = revision;
this.version = version;
this.window = window;
}
public boolean blocksRevisions() { return revision; }
public boolean blocksVersions() { return version; }
public TimeWindow window() { return window; }
@Override
public String toString() {
return "change blocker revision=" + revision + " version=" + version + " window=" + window;
}
}
} | class DeploymentSpec {
/** The empty deployment spec, specifying no zones or rotation, and defaults for all settings */
public static final DeploymentSpec empty = new DeploymentSpec(Optional.empty(),
UpgradePolicy.defaultPolicy,
Optional.empty(),
Collections.emptyList(),
Collections.emptyList(),
"<deployment version='1.0'/>",
Optional.empty(),
Optional.empty(),
Notifications.none(),
List.of());
private final List<Step> steps;
private final Optional<Integer> majorVersion;
private final String xmlForm;
public DeploymentSpec(List<Step> steps,
Optional<Integer> majorVersion,
String xmlForm) {
if (singleInstance(steps)) {
var singleInstance = (DeploymentInstanceSpec)steps.get(0);
this.steps = List.of(singleInstance.withSteps(completeSteps(singleInstance.steps())));
}
else {
this.steps = List.copyOf(completeSteps(steps));
}
this.majorVersion = majorVersion;
this.xmlForm = xmlForm;
validateTotalDelay(steps);
}
public DeploymentSpec(Optional<String> globalServiceId, UpgradePolicy upgradePolicy, Optional<Integer> majorVersion,
List<ChangeBlocker> changeBlockers, List<Step> steps, String xmlForm,
Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService,
Notifications notifications,
List<Endpoint> endpoints) {
this(List.of(new DeploymentInstanceSpec(InstanceName.from("default"),
steps,
upgradePolicy,
changeBlockers,
globalServiceId,
athenzDomain,
athenzService,
notifications,
endpoints)),
majorVersion,
xmlForm);
}
/** Adds missing required steps and reorders steps to a permissible order */
private static List<DeploymentSpec.Step> completeSteps(List<DeploymentSpec.Step> inputSteps) {
List<Step> steps = new ArrayList<>(inputSteps);
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.prod)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.staging))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.staging));
}
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.staging)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.test))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.test));
}
DeploymentSpec.DeclaredZone testStep = remove(Environment.test, steps);
if (testStep != null)
steps.add(0, testStep);
DeploymentSpec.DeclaredZone stagingStep = remove(Environment.staging, steps);
if (stagingStep != null)
steps.add(1, stagingStep);
return steps;
}
/**
* Removes the first occurrence of a deployment step to the given environment and returns it.
*
* @return the removed step, or null if it is not present
*/
private static DeploymentSpec.DeclaredZone remove(Environment environment, List<DeploymentSpec.Step> steps) {
for (int i = 0; i < steps.size(); i++) {
if ( ! (steps.get(i) instanceof DeploymentSpec.DeclaredZone)) continue;
DeploymentSpec.DeclaredZone zoneStep = (DeploymentSpec.DeclaredZone)steps.get(i);
if (zoneStep.environment() == environment) {
steps.remove(i);
return zoneStep;
}
}
return null;
}
/** Throw an IllegalArgumentException if the total delay exceeds 24 hours */
private void validateTotalDelay(List<Step> steps) {
long totalDelaySeconds = steps.stream().mapToLong(step -> (step.delay().getSeconds())).sum();
if (totalDelaySeconds > Duration.ofHours(24).getSeconds())
throw new IllegalArgumentException("The total delay specified is " + Duration.ofSeconds(totalDelaySeconds) +
" but max 24 hours is allowed");
}
private DeploymentInstanceSpec defaultInstance() {
if (singleInstance(steps)) return (DeploymentInstanceSpec)steps.get(0);
throw new IllegalArgumentException("This deployment spec does not support the legacy API " +
"as it has multiple instances: " +
instances().stream().map(Step::toString).collect(Collectors.joining(",")));
}
public Optional<String> globalServiceId() { return defaultInstance().globalServiceId(); }
public UpgradePolicy upgradePolicy() { return defaultInstance().upgradePolicy(); }
/** Returns the major version this application is pinned to, or empty (default) to allow all major versions */
public Optional<Integer> majorVersion() { return majorVersion; }
public boolean canUpgradeAt(Instant instant) { return defaultInstance().canUpgradeAt(instant); }
public boolean canChangeRevisionAt(Instant instant) { return defaultInstance().canChangeRevisionAt(instant); }
public List<ChangeBlocker> changeBlocker() { return defaultInstance().changeBlocker(); }
/** Returns the deployment steps of this in the order they will be performed */
public List<Step> steps() {
if (singleInstance(steps)) return defaultInstance().steps();
return steps;
}
public List<DeclaredZone> zones() {
return defaultInstance().steps().stream()
.flatMap(step -> step.zones().stream())
.collect(Collectors.toList());
}
public Optional<AthenzDomain> athenzDomain() { return defaultInstance().athenzDomain(); }
public Optional<AthenzService> athenzService(Environment environment, RegionName region) {
return defaultInstance().athenzService(environment, region);
}
public Notifications notifications() { return defaultInstance().notifications(); }
public List<Endpoint> endpoints() { return defaultInstance().endpoints(); }
/** Returns the XML form of this spec, or null if it was not created by fromXml, nor is empty */
public String xmlForm() { return xmlForm; }
public boolean includes(Environment environment, Optional<RegionName> region) {
return defaultInstance().deploysTo(environment, region);
}
private static boolean singleInstance(List<DeploymentSpec.Step> steps) {
return steps.size() == 1 && steps.get(0) instanceof DeploymentInstanceSpec;
}
/** Returns the instance step containing the given instance name, or null if not present */
public DeploymentInstanceSpec instance(String name) {
return instance(InstanceName.from(name));
}
/** Returns the instance step containing the given instance name, or null if not present */
/** Returns the instance step containing the given instance name, or throws an IllegalArgumentException if not present */
public DeploymentInstanceSpec requireInstance(String name) {
return requireInstance(InstanceName.from(name));
}
public DeploymentInstanceSpec requireInstance(InstanceName name) {
DeploymentInstanceSpec instance = instance(name);
if (instance == null)
throw new IllegalArgumentException("No instance '" + name + "' in deployment.xml'. Instances: " +
instances().stream().map(spec -> spec.name().toString()).collect(Collectors.joining(",")));
return instance;
}
/** Returns the steps of this which are instances */
public List<DeploymentInstanceSpec> instances() {
return steps.stream()
.filter(step -> step instanceof DeploymentInstanceSpec).map(DeploymentInstanceSpec.class::cast)
.collect(Collectors.toList());
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(Reader reader) {
return new DeploymentSpecXmlReader().read(reader);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm) {
return fromXml(xmlForm, true);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm, boolean validate) {
return new DeploymentSpecXmlReader(validate).read(xmlForm);
}
public static String toMessageString(Throwable t) {
StringBuilder b = new StringBuilder();
String lastMessage = null;
String message;
for (; t != null; t = t.getCause()) {
message = t.getMessage();
if (message == null) continue;
if (message.equals(lastMessage)) continue;
if (b.length() > 0) {
b.append(": ");
}
b.append(message);
lastMessage = message;
}
return b.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeploymentSpec other = (DeploymentSpec) o;
return majorVersion.equals(other.majorVersion) &&
steps.equals(other.steps) &&
xmlForm.equals(other.xmlForm);
}
@Override
public int hashCode() {
return Objects.hash(majorVersion, steps, xmlForm);
}
/** This may be invoked by a continuous build */
public static void main(String[] args) {
if (args.length != 2 && args.length != 3) {
System.err.println("Usage: DeploymentSpec [file] [environment] [region]?" +
"Returns 0 if the specified zone matches the deployment spec, 1 otherwise");
System.exit(1);
}
try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) {
DeploymentSpec spec = DeploymentSpec.fromXml(reader);
Environment environment = Environment.from(args[1]);
Optional<RegionName> region = args.length == 3 ? Optional.of(RegionName.from(args[2])) : Optional.empty();
if (spec.includes(environment, region))
System.exit(0);
else
System.exit(1);
}
catch (Exception e) {
System.err.println("Exception checking deployment spec: " + toMessageString(e));
System.exit(1);
}
}
/** A deployment step */
public abstract static class Step {
/** Returns whether this step deploys to the given region */
public final boolean deploysTo(Environment environment) {
return deploysTo(environment, Optional.empty());
}
/** Returns whether this step deploys to the given environment, and (if specified) region */
public abstract boolean deploysTo(Environment environment, Optional<RegionName> region);
/** Returns the zones deployed to in this step */
public List<DeclaredZone> zones() { return Collections.emptyList(); }
/** The delay introduced by this step (beyond the time it takes to execute the step). Default is zero. */
public Duration delay() { return Duration.ZERO; }
/** Returns all the steps nested in this. This default implementatiino returns an empty list. */
public List<Step> steps() { return List.of(); }
}
/** A deployment step which is to wait for some time before progressing to the next step */
public static class Delay extends Step {
private final Duration duration;
public Delay(Duration duration) {
this.duration = duration;
}
public Duration duration() { return duration; }
@Override
public Duration delay() { return duration; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) { return false; }
@Override
public String toString() {
return "delay " + duration;
}
}
/** A deployment step which is to run deployment in a particular zone */
public static class DeclaredZone extends Step {
private final Environment environment;
private final Optional<RegionName> region;
private final boolean active;
private final Optional<AthenzService> athenzService;
private final Optional<String> testerFlavor;
public DeclaredZone(Environment environment) {
this(environment, Optional.empty(), false);
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active) {
this(environment, region, active, Optional.empty(), Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active, Optional<AthenzService> athenzService) {
this(environment, region, active, athenzService, Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active,
Optional<AthenzService> athenzService, Optional<String> testerFlavor) {
if (environment != Environment.prod && region.isPresent())
throw new IllegalArgumentException("Non-prod environments cannot specify a region");
if (environment == Environment.prod && region.isEmpty())
throw new IllegalArgumentException("Prod environments must be specified with a region");
this.environment = environment;
this.region = region;
this.active = active;
this.athenzService = athenzService;
this.testerFlavor = testerFlavor;
}
public Environment environment() { return environment; }
/** The region name, or empty if not declared */
public Optional<RegionName> region() { return region; }
/** Returns whether this zone should receive production traffic */
public boolean active() { return active; }
public Optional<String> testerFlavor() { return testerFlavor; }
public Optional<AthenzService> athenzService() { return athenzService; }
@Override
public List<DeclaredZone> zones() { return Collections.singletonList(this); }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
if (environment != this.environment) return false;
if (region.isPresent() && ! region.equals(this.region)) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hash(environment, region);
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if ( ! (o instanceof DeclaredZone)) return false;
DeclaredZone other = (DeclaredZone)o;
if (this.environment != other.environment) return false;
if ( ! this.region.equals(other.region())) return false;
return true;
}
@Override
public String toString() {
return environment + (region.map(regionName -> "." + regionName).orElse(""));
}
}
/** A deployment step which is to run multiple steps (zones or instances) in parallel */
public static class ParallelZones extends Step {
private final List<Step> steps;
public ParallelZones(List<Step> steps) {
this.steps = List.copyOf(steps);
}
/** Returns the steps inside this which are zones */
@Override
public List<DeclaredZone> zones() {
return this.steps.stream()
.filter(step -> step instanceof DeclaredZone)
.map(DeclaredZone.class::cast)
.collect(Collectors.toList());
}
/** Returns all the steps nested in this */
@Override
public List<Step> steps() { return steps; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
return steps().stream().anyMatch(zone -> zone.deploysTo(environment, region));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ParallelZones)) return false;
ParallelZones that = (ParallelZones) o;
return Objects.equals(steps, that.steps);
}
@Override
public int hashCode() {
return Objects.hash(steps);
}
@Override
public String toString() {
return steps.size() + " parallel steps";
}
}
/** Controls when this application will be upgraded to new Vespa versions */
public enum UpgradePolicy {
/** Canary: Applications with this policy will upgrade before any other */
canary,
/** Default: Will upgrade after all canary applications upgraded successfully. The default. */
defaultPolicy,
/** Will upgrade after most default applications upgraded successfully */
conservative
}
/** A blocking of changes in a given time window */
public static class ChangeBlocker {
private final boolean revision;
private final boolean version;
private final TimeWindow window;
public ChangeBlocker(boolean revision, boolean version, TimeWindow window) {
this.revision = revision;
this.version = version;
this.window = window;
}
public boolean blocksRevisions() { return revision; }
public boolean blocksVersions() { return version; }
public TimeWindow window() { return window; }
@Override
public String toString() {
return "change blocker revision=" + revision + " version=" + version + " window=" + window;
}
}
} |
```suggestion for (Step instanceStep : instances()) { ``` | public DeploymentInstanceSpec instance(InstanceName name) {
for (Step step : steps) {
if ( ! (step instanceof DeploymentInstanceSpec)) continue;
DeploymentInstanceSpec instanceStep = (DeploymentInstanceSpec)step;
if (instanceStep.name().equals(name))
return instanceStep;
}
return null;
} | for (Step step : steps) { | public DeploymentInstanceSpec instance(InstanceName name) {
for (DeploymentInstanceSpec instance : instances()) {
if (instance.name().equals(name))
return instance;
}
return null;
} | class DeploymentSpec {
/** The empty deployment spec, specifying no zones or rotation, and defaults for all settings */
public static final DeploymentSpec empty = new DeploymentSpec(Optional.empty(),
UpgradePolicy.defaultPolicy,
Optional.empty(),
Collections.emptyList(),
Collections.emptyList(),
"<deployment version='1.0'/>",
Optional.empty(),
Optional.empty(),
Notifications.none(),
List.of());
private final List<Step> steps;
private final Optional<Integer> majorVersion;
private final String xmlForm;
public DeploymentSpec(List<Step> steps,
Optional<Integer> majorVersion,
String xmlForm) {
if (singleInstance(steps)) {
var singleInstance = (DeploymentInstanceSpec)steps.get(0);
this.steps = List.of(singleInstance.withSteps(completeSteps(singleInstance.steps())));
}
else {
this.steps = List.copyOf(completeSteps(steps));
}
this.majorVersion = majorVersion;
this.xmlForm = xmlForm;
validateTotalDelay(steps);
}
public DeploymentSpec(Optional<String> globalServiceId, UpgradePolicy upgradePolicy, Optional<Integer> majorVersion,
List<ChangeBlocker> changeBlockers, List<Step> steps, String xmlForm,
Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService,
Notifications notifications,
List<Endpoint> endpoints) {
this(List.of(new DeploymentInstanceSpec(InstanceName.from("default"),
steps,
upgradePolicy,
changeBlockers,
globalServiceId,
athenzDomain,
athenzService,
notifications,
endpoints)),
majorVersion,
xmlForm);
}
/** Adds missing required steps and reorders steps to a permissible order */
private static List<DeploymentSpec.Step> completeSteps(List<DeploymentSpec.Step> inputSteps) {
List<Step> steps = new ArrayList<>(inputSteps);
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.prod)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.staging))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.staging));
}
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.staging)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.test))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.test));
}
DeploymentSpec.DeclaredZone testStep = remove(Environment.test, steps);
if (testStep != null)
steps.add(0, testStep);
DeploymentSpec.DeclaredZone stagingStep = remove(Environment.staging, steps);
if (stagingStep != null)
steps.add(1, stagingStep);
return steps;
}
/**
* Removes the first occurrence of a deployment step to the given environment and returns it.
*
* @return the removed step, or null if it is not present
*/
private static DeploymentSpec.DeclaredZone remove(Environment environment, List<DeploymentSpec.Step> steps) {
for (int i = 0; i < steps.size(); i++) {
if ( ! (steps.get(i) instanceof DeploymentSpec.DeclaredZone)) continue;
DeploymentSpec.DeclaredZone zoneStep = (DeploymentSpec.DeclaredZone)steps.get(i);
if (zoneStep.environment() == environment) {
steps.remove(i);
return zoneStep;
}
}
return null;
}
/** Throw an IllegalArgumentException if the total delay exceeds 24 hours */
private void validateTotalDelay(List<Step> steps) {
long totalDelaySeconds = steps.stream().mapToLong(step -> (step.delay().getSeconds())).sum();
if (totalDelaySeconds > Duration.ofHours(24).getSeconds())
throw new IllegalArgumentException("The total delay specified is " + Duration.ofSeconds(totalDelaySeconds) +
" but max 24 hours is allowed");
}
private DeploymentInstanceSpec defaultInstance() {
if (singleInstance(steps)) return (DeploymentInstanceSpec)steps.get(0);
throw new IllegalArgumentException("This deployment spec does not support the legacy API " +
"as it has multiple instances: " +
instances().stream().map(Step::toString).collect(Collectors.joining(",")));
}
public Optional<String> globalServiceId() { return defaultInstance().globalServiceId(); }
public UpgradePolicy upgradePolicy() { return defaultInstance().upgradePolicy(); }
/** Returns the major version this application is pinned to, or empty (default) to allow all major versions */
public Optional<Integer> majorVersion() { return majorVersion; }
public boolean canUpgradeAt(Instant instant) { return defaultInstance().canUpgradeAt(instant); }
public boolean canChangeRevisionAt(Instant instant) { return defaultInstance().canChangeRevisionAt(instant); }
public List<ChangeBlocker> changeBlocker() { return defaultInstance().changeBlocker(); }
/** Returns the deployment steps of this in the order they will be performed */
public List<Step> steps() {
if (singleInstance(steps)) return defaultInstance().steps();
return steps;
}
public List<DeclaredZone> zones() {
return defaultInstance().steps().stream()
.flatMap(step -> step.zones().stream())
.collect(Collectors.toList());
}
public Optional<AthenzDomain> athenzDomain() { return defaultInstance().athenzDomain(); }
public Optional<AthenzService> athenzService(Environment environment, RegionName region) {
return defaultInstance().athenzService(environment, region);
}
public Notifications notifications() { return defaultInstance().notifications(); }
public List<Endpoint> endpoints() { return defaultInstance().endpoints(); }
/** Returns the XML form of this spec, or null if it was not created by fromXml, nor is empty */
public String xmlForm() { return xmlForm; }
public boolean includes(Environment environment, Optional<RegionName> region) {
return defaultInstance().deploysTo(environment, region);
}
private static boolean singleInstance(List<DeploymentSpec.Step> steps) {
return steps.size() == 1 && steps.get(0) instanceof DeploymentInstanceSpec;
}
/** Returns the instance step containing the given instance name, or null if not present */
public DeploymentInstanceSpec instance(String name) {
return instance(InstanceName.from(name));
}
/** Returns the instance step containing the given instance name, or null if not present */
/** Returns the instance step containing the given instance name, or throws an IllegalArgumentException if not present */
public DeploymentInstanceSpec requireInstance(String name) {
return requireInstance(InstanceName.from(name));
}
public DeploymentInstanceSpec requireInstance(InstanceName name) {
DeploymentInstanceSpec instance = instance(name);
if (instance == null)
throw new IllegalArgumentException("No instance '" + name + "' in deployment.xml'. Instances: " +
instances().stream().map(spec -> spec.name().toString()).collect(Collectors.joining(",")));
return instance;
}
/** Returns the steps of this which are instances */
public List<DeploymentInstanceSpec> instances() {
return steps.stream()
.filter(step -> step instanceof DeploymentInstanceSpec).map(DeploymentInstanceSpec.class::cast)
.collect(Collectors.toList());
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(Reader reader) {
return new DeploymentSpecXmlReader().read(reader);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm) {
return fromXml(xmlForm, true);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm, boolean validate) {
return new DeploymentSpecXmlReader(validate).read(xmlForm);
}
public static String toMessageString(Throwable t) {
StringBuilder b = new StringBuilder();
String lastMessage = null;
String message;
for (; t != null; t = t.getCause()) {
message = t.getMessage();
if (message == null) continue;
if (message.equals(lastMessage)) continue;
if (b.length() > 0) {
b.append(": ");
}
b.append(message);
lastMessage = message;
}
return b.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeploymentSpec other = (DeploymentSpec) o;
return majorVersion.equals(other.majorVersion) &&
steps.equals(other.steps) &&
xmlForm.equals(other.xmlForm);
}
@Override
public int hashCode() {
return Objects.hash(majorVersion, steps, xmlForm);
}
/** This may be invoked by a continuous build */
public static void main(String[] args) {
if (args.length != 2 && args.length != 3) {
System.err.println("Usage: DeploymentSpec [file] [environment] [region]?" +
"Returns 0 if the specified zone matches the deployment spec, 1 otherwise");
System.exit(1);
}
try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) {
DeploymentSpec spec = DeploymentSpec.fromXml(reader);
Environment environment = Environment.from(args[1]);
Optional<RegionName> region = args.length == 3 ? Optional.of(RegionName.from(args[2])) : Optional.empty();
if (spec.includes(environment, region))
System.exit(0);
else
System.exit(1);
}
catch (Exception e) {
System.err.println("Exception checking deployment spec: " + toMessageString(e));
System.exit(1);
}
}
/** A deployment step */
public abstract static class Step {
/** Returns whether this step deploys to the given region */
public final boolean deploysTo(Environment environment) {
return deploysTo(environment, Optional.empty());
}
/** Returns whether this step deploys to the given environment, and (if specified) region */
public abstract boolean deploysTo(Environment environment, Optional<RegionName> region);
/** Returns the zones deployed to in this step */
public List<DeclaredZone> zones() { return Collections.emptyList(); }
/** The delay introduced by this step (beyond the time it takes to execute the step). Default is zero. */
public Duration delay() { return Duration.ZERO; }
/** Returns all the steps nested in this. This default implementatiino returns an empty list. */
public List<Step> steps() { return List.of(); }
}
/** A deployment step which is to wait for some time before progressing to the next step */
public static class Delay extends Step {
private final Duration duration;
public Delay(Duration duration) {
this.duration = duration;
}
public Duration duration() { return duration; }
@Override
public Duration delay() { return duration; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) { return false; }
@Override
public String toString() {
return "delay " + duration;
}
}
/** A deployment step which is to run deployment in a particular zone */
public static class DeclaredZone extends Step {
private final Environment environment;
private final Optional<RegionName> region;
private final boolean active;
private final Optional<AthenzService> athenzService;
private final Optional<String> testerFlavor;
public DeclaredZone(Environment environment) {
this(environment, Optional.empty(), false);
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active) {
this(environment, region, active, Optional.empty(), Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active, Optional<AthenzService> athenzService) {
this(environment, region, active, athenzService, Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active,
Optional<AthenzService> athenzService, Optional<String> testerFlavor) {
if (environment != Environment.prod && region.isPresent())
throw new IllegalArgumentException("Non-prod environments cannot specify a region");
if (environment == Environment.prod && region.isEmpty())
throw new IllegalArgumentException("Prod environments must be specified with a region");
this.environment = environment;
this.region = region;
this.active = active;
this.athenzService = athenzService;
this.testerFlavor = testerFlavor;
}
public Environment environment() { return environment; }
/** The region name, or empty if not declared */
public Optional<RegionName> region() { return region; }
/** Returns whether this zone should receive production traffic */
public boolean active() { return active; }
public Optional<String> testerFlavor() { return testerFlavor; }
public Optional<AthenzService> athenzService() { return athenzService; }
@Override
public List<DeclaredZone> zones() { return Collections.singletonList(this); }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
if (environment != this.environment) return false;
if (region.isPresent() && ! region.equals(this.region)) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hash(environment, region);
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if ( ! (o instanceof DeclaredZone)) return false;
DeclaredZone other = (DeclaredZone)o;
if (this.environment != other.environment) return false;
if ( ! this.region.equals(other.region())) return false;
return true;
}
@Override
public String toString() {
return environment + (region.map(regionName -> "." + regionName).orElse(""));
}
}
/** A deployment step which is to run multiple steps (zones or instances) in parallel */
public static class ParallelZones extends Step {
private final List<Step> steps;
public ParallelZones(List<Step> steps) {
this.steps = List.copyOf(steps);
}
/** Returns the steps inside this which are zones */
@Override
public List<DeclaredZone> zones() {
return this.steps.stream()
.filter(step -> step instanceof DeclaredZone)
.map(DeclaredZone.class::cast)
.collect(Collectors.toList());
}
/** Returns all the steps nested in this */
@Override
public List<Step> steps() { return steps; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
return steps().stream().anyMatch(zone -> zone.deploysTo(environment, region));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ParallelZones)) return false;
ParallelZones that = (ParallelZones) o;
return Objects.equals(steps, that.steps);
}
@Override
public int hashCode() {
return Objects.hash(steps);
}
@Override
public String toString() {
return steps.size() + " parallel steps";
}
}
/** Controls when this application will be upgraded to new Vespa versions */
public enum UpgradePolicy {
/** Canary: Applications with this policy will upgrade before any other */
canary,
/** Default: Will upgrade after all canary applications upgraded successfully. The default. */
defaultPolicy,
/** Will upgrade after most default applications upgraded successfully */
conservative
}
/** A blocking of changes in a given time window */
public static class ChangeBlocker {
private final boolean revision;
private final boolean version;
private final TimeWindow window;
public ChangeBlocker(boolean revision, boolean version, TimeWindow window) {
this.revision = revision;
this.version = version;
this.window = window;
}
public boolean blocksRevisions() { return revision; }
public boolean blocksVersions() { return version; }
public TimeWindow window() { return window; }
@Override
public String toString() {
return "change blocker revision=" + revision + " version=" + version + " window=" + window;
}
}
} | class DeploymentSpec {
/** The empty deployment spec, specifying no zones or rotation, and defaults for all settings */
public static final DeploymentSpec empty = new DeploymentSpec(Optional.empty(),
UpgradePolicy.defaultPolicy,
Optional.empty(),
Collections.emptyList(),
Collections.emptyList(),
"<deployment version='1.0'/>",
Optional.empty(),
Optional.empty(),
Notifications.none(),
List.of());
private final List<Step> steps;
private final Optional<Integer> majorVersion;
private final String xmlForm;
public DeploymentSpec(List<Step> steps,
Optional<Integer> majorVersion,
String xmlForm) {
if (singleInstance(steps)) {
var singleInstance = (DeploymentInstanceSpec)steps.get(0);
this.steps = List.of(singleInstance.withSteps(completeSteps(singleInstance.steps())));
}
else {
this.steps = List.copyOf(completeSteps(steps));
}
this.majorVersion = majorVersion;
this.xmlForm = xmlForm;
validateTotalDelay(steps);
}
public DeploymentSpec(Optional<String> globalServiceId, UpgradePolicy upgradePolicy, Optional<Integer> majorVersion,
List<ChangeBlocker> changeBlockers, List<Step> steps, String xmlForm,
Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService,
Notifications notifications,
List<Endpoint> endpoints) {
this(List.of(new DeploymentInstanceSpec(InstanceName.from("default"),
steps,
upgradePolicy,
changeBlockers,
globalServiceId,
athenzDomain,
athenzService,
notifications,
endpoints)),
majorVersion,
xmlForm);
}
/** Adds missing required steps and reorders steps to a permissible order */
private static List<DeploymentSpec.Step> completeSteps(List<DeploymentSpec.Step> inputSteps) {
List<Step> steps = new ArrayList<>(inputSteps);
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.prod)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.staging))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.staging));
}
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.staging)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.test))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.test));
}
DeploymentSpec.DeclaredZone testStep = remove(Environment.test, steps);
if (testStep != null)
steps.add(0, testStep);
DeploymentSpec.DeclaredZone stagingStep = remove(Environment.staging, steps);
if (stagingStep != null)
steps.add(1, stagingStep);
return steps;
}
/**
* Removes the first occurrence of a deployment step to the given environment and returns it.
*
* @return the removed step, or null if it is not present
*/
private static DeploymentSpec.DeclaredZone remove(Environment environment, List<DeploymentSpec.Step> steps) {
for (int i = 0; i < steps.size(); i++) {
if ( ! (steps.get(i) instanceof DeploymentSpec.DeclaredZone)) continue;
DeploymentSpec.DeclaredZone zoneStep = (DeploymentSpec.DeclaredZone)steps.get(i);
if (zoneStep.environment() == environment) {
steps.remove(i);
return zoneStep;
}
}
return null;
}
/** Throw an IllegalArgumentException if the total delay exceeds 24 hours */
private void validateTotalDelay(List<Step> steps) {
long totalDelaySeconds = steps.stream().mapToLong(step -> (step.delay().getSeconds())).sum();
if (totalDelaySeconds > Duration.ofHours(24).getSeconds())
throw new IllegalArgumentException("The total delay specified is " + Duration.ofSeconds(totalDelaySeconds) +
" but max 24 hours is allowed");
}
private DeploymentInstanceSpec defaultInstance() {
if (singleInstance(steps)) return (DeploymentInstanceSpec)steps.get(0);
throw new IllegalArgumentException("This deployment spec does not support the legacy API " +
"as it has multiple instances: " +
instances().stream().map(Step::toString).collect(Collectors.joining(",")));
}
public Optional<String> globalServiceId() { return defaultInstance().globalServiceId(); }
public UpgradePolicy upgradePolicy() { return defaultInstance().upgradePolicy(); }
/** Returns the major version this application is pinned to, or empty (default) to allow all major versions */
public Optional<Integer> majorVersion() { return majorVersion; }
public boolean canUpgradeAt(Instant instant) { return defaultInstance().canUpgradeAt(instant); }
public boolean canChangeRevisionAt(Instant instant) { return defaultInstance().canChangeRevisionAt(instant); }
public List<ChangeBlocker> changeBlocker() { return defaultInstance().changeBlocker(); }
/** Returns the deployment steps of this in the order they will be performed */
public List<Step> steps() {
if (singleInstance(steps)) return defaultInstance().steps();
return steps;
}
public List<DeclaredZone> zones() {
return defaultInstance().steps().stream()
.flatMap(step -> step.zones().stream())
.collect(Collectors.toList());
}
public Optional<AthenzDomain> athenzDomain() { return defaultInstance().athenzDomain(); }
public Optional<AthenzService> athenzService(Environment environment, RegionName region) {
return defaultInstance().athenzService(environment, region);
}
public Notifications notifications() { return defaultInstance().notifications(); }
public List<Endpoint> endpoints() { return defaultInstance().endpoints(); }
/** Returns the XML form of this spec, or null if it was not created by fromXml, nor is empty */
public String xmlForm() { return xmlForm; }
public boolean includes(Environment environment, Optional<RegionName> region) {
return defaultInstance().deploysTo(environment, region);
}
private static boolean singleInstance(List<DeploymentSpec.Step> steps) {
return steps.size() == 1 && steps.get(0) instanceof DeploymentInstanceSpec;
}
/** Returns the instance step containing the given instance name, or null if not present */
public DeploymentInstanceSpec instance(String name) {
return instance(InstanceName.from(name));
}
/** Returns the instance step containing the given instance name, or null if not present */
/** Returns the instance step containing the given instance name, or throws an IllegalArgumentException if not present */
public DeploymentInstanceSpec requireInstance(String name) {
return requireInstance(InstanceName.from(name));
}
public DeploymentInstanceSpec requireInstance(InstanceName name) {
DeploymentInstanceSpec instance = instance(name);
if (instance == null)
throw new IllegalArgumentException("No instance '" + name + "' in deployment.xml'. Instances: " +
instances().stream().map(spec -> spec.name().toString()).collect(Collectors.joining(",")));
return instance;
}
/** Returns the steps of this which are instances */
public List<DeploymentInstanceSpec> instances() {
return steps.stream()
.filter(step -> step instanceof DeploymentInstanceSpec).map(DeploymentInstanceSpec.class::cast)
.collect(Collectors.toList());
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(Reader reader) {
return new DeploymentSpecXmlReader().read(reader);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm) {
return fromXml(xmlForm, true);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm, boolean validate) {
return new DeploymentSpecXmlReader(validate).read(xmlForm);
}
public static String toMessageString(Throwable t) {
StringBuilder b = new StringBuilder();
String lastMessage = null;
String message;
for (; t != null; t = t.getCause()) {
message = t.getMessage();
if (message == null) continue;
if (message.equals(lastMessage)) continue;
if (b.length() > 0) {
b.append(": ");
}
b.append(message);
lastMessage = message;
}
return b.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeploymentSpec other = (DeploymentSpec) o;
return majorVersion.equals(other.majorVersion) &&
steps.equals(other.steps) &&
xmlForm.equals(other.xmlForm);
}
@Override
public int hashCode() {
return Objects.hash(majorVersion, steps, xmlForm);
}
/** This may be invoked by a continuous build */
public static void main(String[] args) {
if (args.length != 2 && args.length != 3) {
System.err.println("Usage: DeploymentSpec [file] [environment] [region]?" +
"Returns 0 if the specified zone matches the deployment spec, 1 otherwise");
System.exit(1);
}
try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) {
DeploymentSpec spec = DeploymentSpec.fromXml(reader);
Environment environment = Environment.from(args[1]);
Optional<RegionName> region = args.length == 3 ? Optional.of(RegionName.from(args[2])) : Optional.empty();
if (spec.includes(environment, region))
System.exit(0);
else
System.exit(1);
}
catch (Exception e) {
System.err.println("Exception checking deployment spec: " + toMessageString(e));
System.exit(1);
}
}
/** A deployment step */
public abstract static class Step {
/** Returns whether this step deploys to the given region */
public final boolean deploysTo(Environment environment) {
return deploysTo(environment, Optional.empty());
}
/** Returns whether this step deploys to the given environment, and (if specified) region */
public abstract boolean deploysTo(Environment environment, Optional<RegionName> region);
/** Returns the zones deployed to in this step */
public List<DeclaredZone> zones() { return Collections.emptyList(); }
/** The delay introduced by this step (beyond the time it takes to execute the step). Default is zero. */
public Duration delay() { return Duration.ZERO; }
/** Returns all the steps nested in this. This default implementatiino returns an empty list. */
public List<Step> steps() { return List.of(); }
}
/** A deployment step which is to wait for some time before progressing to the next step */
public static class Delay extends Step {
private final Duration duration;
public Delay(Duration duration) {
this.duration = duration;
}
public Duration duration() { return duration; }
@Override
public Duration delay() { return duration; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) { return false; }
@Override
public String toString() {
return "delay " + duration;
}
}
/** A deployment step which is to run deployment in a particular zone */
public static class DeclaredZone extends Step {
private final Environment environment;
private final Optional<RegionName> region;
private final boolean active;
private final Optional<AthenzService> athenzService;
private final Optional<String> testerFlavor;
public DeclaredZone(Environment environment) {
this(environment, Optional.empty(), false);
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active) {
this(environment, region, active, Optional.empty(), Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active, Optional<AthenzService> athenzService) {
this(environment, region, active, athenzService, Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active,
Optional<AthenzService> athenzService, Optional<String> testerFlavor) {
if (environment != Environment.prod && region.isPresent())
throw new IllegalArgumentException("Non-prod environments cannot specify a region");
if (environment == Environment.prod && region.isEmpty())
throw new IllegalArgumentException("Prod environments must be specified with a region");
this.environment = environment;
this.region = region;
this.active = active;
this.athenzService = athenzService;
this.testerFlavor = testerFlavor;
}
public Environment environment() { return environment; }
/** The region name, or empty if not declared */
public Optional<RegionName> region() { return region; }
/** Returns whether this zone should receive production traffic */
public boolean active() { return active; }
public Optional<String> testerFlavor() { return testerFlavor; }
public Optional<AthenzService> athenzService() { return athenzService; }
@Override
public List<DeclaredZone> zones() { return Collections.singletonList(this); }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
if (environment != this.environment) return false;
if (region.isPresent() && ! region.equals(this.region)) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hash(environment, region);
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if ( ! (o instanceof DeclaredZone)) return false;
DeclaredZone other = (DeclaredZone)o;
if (this.environment != other.environment) return false;
if ( ! this.region.equals(other.region())) return false;
return true;
}
@Override
public String toString() {
return environment + (region.map(regionName -> "." + regionName).orElse(""));
}
}
/** A deployment step which is to run multiple steps (zones or instances) in parallel */
public static class ParallelZones extends Step {
private final List<Step> steps;
public ParallelZones(List<Step> steps) {
this.steps = List.copyOf(steps);
}
/** Returns the steps inside this which are zones */
@Override
public List<DeclaredZone> zones() {
return this.steps.stream()
.filter(step -> step instanceof DeclaredZone)
.map(DeclaredZone.class::cast)
.collect(Collectors.toList());
}
/** Returns all the steps nested in this */
@Override
public List<Step> steps() { return steps; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
return steps().stream().anyMatch(zone -> zone.deploysTo(environment, region));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ParallelZones)) return false;
ParallelZones that = (ParallelZones) o;
return Objects.equals(steps, that.steps);
}
@Override
public int hashCode() {
return Objects.hash(steps);
}
@Override
public String toString() {
return steps.size() + " parallel steps";
}
}
/** Controls when this application will be upgraded to new Vespa versions */
public enum UpgradePolicy {
/** Canary: Applications with this policy will upgrade before any other */
canary,
/** Default: Will upgrade after all canary applications upgraded successfully. The default. */
defaultPolicy,
/** Will upgrade after most default applications upgraded successfully */
conservative
}
/** A blocking of changes in a given time window */
public static class ChangeBlocker {
private final boolean revision;
private final boolean version;
private final TimeWindow window;
public ChangeBlocker(boolean revision, boolean version, TimeWindow window) {
this.revision = revision;
this.version = version;
this.window = window;
}
public boolean blocksRevisions() { return revision; }
public boolean blocksVersions() { return version; }
public TimeWindow window() { return window; }
@Override
public String toString() {
return "change blocker revision=" + revision + " version=" + version + " window=" + window;
}
}
} |
Why doesn't the suggestion support multi-line comments!? | public DeploymentInstanceSpec instance(InstanceName name) {
for (Step step : steps) {
if ( ! (step instanceof DeploymentInstanceSpec)) continue;
DeploymentInstanceSpec instanceStep = (DeploymentInstanceSpec)step;
if (instanceStep.name().equals(name))
return instanceStep;
}
return null;
} | DeploymentInstanceSpec instanceStep = (DeploymentInstanceSpec)step; | public DeploymentInstanceSpec instance(InstanceName name) {
for (DeploymentInstanceSpec instance : instances()) {
if (instance.name().equals(name))
return instance;
}
return null;
} | class DeploymentSpec {
/** The empty deployment spec, specifying no zones or rotation, and defaults for all settings */
public static final DeploymentSpec empty = new DeploymentSpec(Optional.empty(),
UpgradePolicy.defaultPolicy,
Optional.empty(),
Collections.emptyList(),
Collections.emptyList(),
"<deployment version='1.0'/>",
Optional.empty(),
Optional.empty(),
Notifications.none(),
List.of());
private final List<Step> steps;
private final Optional<Integer> majorVersion;
private final String xmlForm;
public DeploymentSpec(List<Step> steps,
Optional<Integer> majorVersion,
String xmlForm) {
if (singleInstance(steps)) {
var singleInstance = (DeploymentInstanceSpec)steps.get(0);
this.steps = List.of(singleInstance.withSteps(completeSteps(singleInstance.steps())));
}
else {
this.steps = List.copyOf(completeSteps(steps));
}
this.majorVersion = majorVersion;
this.xmlForm = xmlForm;
validateTotalDelay(steps);
}
public DeploymentSpec(Optional<String> globalServiceId, UpgradePolicy upgradePolicy, Optional<Integer> majorVersion,
List<ChangeBlocker> changeBlockers, List<Step> steps, String xmlForm,
Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService,
Notifications notifications,
List<Endpoint> endpoints) {
this(List.of(new DeploymentInstanceSpec(InstanceName.from("default"),
steps,
upgradePolicy,
changeBlockers,
globalServiceId,
athenzDomain,
athenzService,
notifications,
endpoints)),
majorVersion,
xmlForm);
}
/** Adds missing required steps and reorders steps to a permissible order */
private static List<DeploymentSpec.Step> completeSteps(List<DeploymentSpec.Step> inputSteps) {
List<Step> steps = new ArrayList<>(inputSteps);
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.prod)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.staging))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.staging));
}
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.staging)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.test))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.test));
}
DeploymentSpec.DeclaredZone testStep = remove(Environment.test, steps);
if (testStep != null)
steps.add(0, testStep);
DeploymentSpec.DeclaredZone stagingStep = remove(Environment.staging, steps);
if (stagingStep != null)
steps.add(1, stagingStep);
return steps;
}
/**
* Removes the first occurrence of a deployment step to the given environment and returns it.
*
* @return the removed step, or null if it is not present
*/
private static DeploymentSpec.DeclaredZone remove(Environment environment, List<DeploymentSpec.Step> steps) {
for (int i = 0; i < steps.size(); i++) {
if ( ! (steps.get(i) instanceof DeploymentSpec.DeclaredZone)) continue;
DeploymentSpec.DeclaredZone zoneStep = (DeploymentSpec.DeclaredZone)steps.get(i);
if (zoneStep.environment() == environment) {
steps.remove(i);
return zoneStep;
}
}
return null;
}
/** Throw an IllegalArgumentException if the total delay exceeds 24 hours */
private void validateTotalDelay(List<Step> steps) {
long totalDelaySeconds = steps.stream().mapToLong(step -> (step.delay().getSeconds())).sum();
if (totalDelaySeconds > Duration.ofHours(24).getSeconds())
throw new IllegalArgumentException("The total delay specified is " + Duration.ofSeconds(totalDelaySeconds) +
" but max 24 hours is allowed");
}
private DeploymentInstanceSpec defaultInstance() {
if (singleInstance(steps)) return (DeploymentInstanceSpec)steps.get(0);
throw new IllegalArgumentException("This deployment spec does not support the legacy API " +
"as it has multiple instances: " +
instances().stream().map(Step::toString).collect(Collectors.joining(",")));
}
public Optional<String> globalServiceId() { return defaultInstance().globalServiceId(); }
public UpgradePolicy upgradePolicy() { return defaultInstance().upgradePolicy(); }
/** Returns the major version this application is pinned to, or empty (default) to allow all major versions */
public Optional<Integer> majorVersion() { return majorVersion; }
public boolean canUpgradeAt(Instant instant) { return defaultInstance().canUpgradeAt(instant); }
public boolean canChangeRevisionAt(Instant instant) { return defaultInstance().canChangeRevisionAt(instant); }
public List<ChangeBlocker> changeBlocker() { return defaultInstance().changeBlocker(); }
/** Returns the deployment steps of this in the order they will be performed */
public List<Step> steps() {
if (singleInstance(steps)) return defaultInstance().steps();
return steps;
}
public List<DeclaredZone> zones() {
return defaultInstance().steps().stream()
.flatMap(step -> step.zones().stream())
.collect(Collectors.toList());
}
public Optional<AthenzDomain> athenzDomain() { return defaultInstance().athenzDomain(); }
public Optional<AthenzService> athenzService(Environment environment, RegionName region) {
return defaultInstance().athenzService(environment, region);
}
public Notifications notifications() { return defaultInstance().notifications(); }
public List<Endpoint> endpoints() { return defaultInstance().endpoints(); }
/** Returns the XML form of this spec, or null if it was not created by fromXml, nor is empty */
public String xmlForm() { return xmlForm; }
public boolean includes(Environment environment, Optional<RegionName> region) {
return defaultInstance().deploysTo(environment, region);
}
private static boolean singleInstance(List<DeploymentSpec.Step> steps) {
return steps.size() == 1 && steps.get(0) instanceof DeploymentInstanceSpec;
}
/** Returns the instance step containing the given instance name, or null if not present */
public DeploymentInstanceSpec instance(String name) {
return instance(InstanceName.from(name));
}
/** Returns the instance step containing the given instance name, or null if not present */
/** Returns the instance step containing the given instance name, or throws an IllegalArgumentException if not present */
public DeploymentInstanceSpec requireInstance(String name) {
return requireInstance(InstanceName.from(name));
}
public DeploymentInstanceSpec requireInstance(InstanceName name) {
DeploymentInstanceSpec instance = instance(name);
if (instance == null)
throw new IllegalArgumentException("No instance '" + name + "' in deployment.xml'. Instances: " +
instances().stream().map(spec -> spec.name().toString()).collect(Collectors.joining(",")));
return instance;
}
/** Returns the steps of this which are instances */
public List<DeploymentInstanceSpec> instances() {
return steps.stream()
.filter(step -> step instanceof DeploymentInstanceSpec).map(DeploymentInstanceSpec.class::cast)
.collect(Collectors.toList());
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(Reader reader) {
return new DeploymentSpecXmlReader().read(reader);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm) {
return fromXml(xmlForm, true);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm, boolean validate) {
return new DeploymentSpecXmlReader(validate).read(xmlForm);
}
public static String toMessageString(Throwable t) {
StringBuilder b = new StringBuilder();
String lastMessage = null;
String message;
for (; t != null; t = t.getCause()) {
message = t.getMessage();
if (message == null) continue;
if (message.equals(lastMessage)) continue;
if (b.length() > 0) {
b.append(": ");
}
b.append(message);
lastMessage = message;
}
return b.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeploymentSpec other = (DeploymentSpec) o;
return majorVersion.equals(other.majorVersion) &&
steps.equals(other.steps) &&
xmlForm.equals(other.xmlForm);
}
@Override
public int hashCode() {
return Objects.hash(majorVersion, steps, xmlForm);
}
/** This may be invoked by a continuous build */
public static void main(String[] args) {
if (args.length != 2 && args.length != 3) {
System.err.println("Usage: DeploymentSpec [file] [environment] [region]?" +
"Returns 0 if the specified zone matches the deployment spec, 1 otherwise");
System.exit(1);
}
try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) {
DeploymentSpec spec = DeploymentSpec.fromXml(reader);
Environment environment = Environment.from(args[1]);
Optional<RegionName> region = args.length == 3 ? Optional.of(RegionName.from(args[2])) : Optional.empty();
if (spec.includes(environment, region))
System.exit(0);
else
System.exit(1);
}
catch (Exception e) {
System.err.println("Exception checking deployment spec: " + toMessageString(e));
System.exit(1);
}
}
/** A deployment step */
public abstract static class Step {
/** Returns whether this step deploys to the given region */
public final boolean deploysTo(Environment environment) {
return deploysTo(environment, Optional.empty());
}
/** Returns whether this step deploys to the given environment, and (if specified) region */
public abstract boolean deploysTo(Environment environment, Optional<RegionName> region);
/** Returns the zones deployed to in this step */
public List<DeclaredZone> zones() { return Collections.emptyList(); }
/** The delay introduced by this step (beyond the time it takes to execute the step). Default is zero. */
public Duration delay() { return Duration.ZERO; }
/** Returns all the steps nested in this. This default implementatiino returns an empty list. */
public List<Step> steps() { return List.of(); }
}
/** A deployment step which is to wait for some time before progressing to the next step */
public static class Delay extends Step {
private final Duration duration;
public Delay(Duration duration) {
this.duration = duration;
}
public Duration duration() { return duration; }
@Override
public Duration delay() { return duration; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) { return false; }
@Override
public String toString() {
return "delay " + duration;
}
}
/** A deployment step which is to run deployment in a particular zone */
public static class DeclaredZone extends Step {
private final Environment environment;
private final Optional<RegionName> region;
private final boolean active;
private final Optional<AthenzService> athenzService;
private final Optional<String> testerFlavor;
public DeclaredZone(Environment environment) {
this(environment, Optional.empty(), false);
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active) {
this(environment, region, active, Optional.empty(), Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active, Optional<AthenzService> athenzService) {
this(environment, region, active, athenzService, Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active,
Optional<AthenzService> athenzService, Optional<String> testerFlavor) {
if (environment != Environment.prod && region.isPresent())
throw new IllegalArgumentException("Non-prod environments cannot specify a region");
if (environment == Environment.prod && region.isEmpty())
throw new IllegalArgumentException("Prod environments must be specified with a region");
this.environment = environment;
this.region = region;
this.active = active;
this.athenzService = athenzService;
this.testerFlavor = testerFlavor;
}
public Environment environment() { return environment; }
/** The region name, or empty if not declared */
public Optional<RegionName> region() { return region; }
/** Returns whether this zone should receive production traffic */
public boolean active() { return active; }
public Optional<String> testerFlavor() { return testerFlavor; }
public Optional<AthenzService> athenzService() { return athenzService; }
@Override
public List<DeclaredZone> zones() { return Collections.singletonList(this); }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
if (environment != this.environment) return false;
if (region.isPresent() && ! region.equals(this.region)) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hash(environment, region);
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if ( ! (o instanceof DeclaredZone)) return false;
DeclaredZone other = (DeclaredZone)o;
if (this.environment != other.environment) return false;
if ( ! this.region.equals(other.region())) return false;
return true;
}
@Override
public String toString() {
return environment + (region.map(regionName -> "." + regionName).orElse(""));
}
}
/** A deployment step which is to run multiple steps (zones or instances) in parallel */
public static class ParallelZones extends Step {
private final List<Step> steps;
public ParallelZones(List<Step> steps) {
this.steps = List.copyOf(steps);
}
/** Returns the steps inside this which are zones */
@Override
public List<DeclaredZone> zones() {
return this.steps.stream()
.filter(step -> step instanceof DeclaredZone)
.map(DeclaredZone.class::cast)
.collect(Collectors.toList());
}
/** Returns all the steps nested in this */
@Override
public List<Step> steps() { return steps; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
return steps().stream().anyMatch(zone -> zone.deploysTo(environment, region));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ParallelZones)) return false;
ParallelZones that = (ParallelZones) o;
return Objects.equals(steps, that.steps);
}
@Override
public int hashCode() {
return Objects.hash(steps);
}
@Override
public String toString() {
return steps.size() + " parallel steps";
}
}
/** Controls when this application will be upgraded to new Vespa versions */
public enum UpgradePolicy {
/** Canary: Applications with this policy will upgrade before any other */
canary,
/** Default: Will upgrade after all canary applications upgraded successfully. The default. */
defaultPolicy,
/** Will upgrade after most default applications upgraded successfully */
conservative
}
/** A blocking of changes in a given time window */
public static class ChangeBlocker {
private final boolean revision;
private final boolean version;
private final TimeWindow window;
public ChangeBlocker(boolean revision, boolean version, TimeWindow window) {
this.revision = revision;
this.version = version;
this.window = window;
}
public boolean blocksRevisions() { return revision; }
public boolean blocksVersions() { return version; }
public TimeWindow window() { return window; }
@Override
public String toString() {
return "change blocker revision=" + revision + " version=" + version + " window=" + window;
}
}
} | class DeploymentSpec {
/** The empty deployment spec, specifying no zones or rotation, and defaults for all settings */
public static final DeploymentSpec empty = new DeploymentSpec(Optional.empty(),
UpgradePolicy.defaultPolicy,
Optional.empty(),
Collections.emptyList(),
Collections.emptyList(),
"<deployment version='1.0'/>",
Optional.empty(),
Optional.empty(),
Notifications.none(),
List.of());
private final List<Step> steps;
private final Optional<Integer> majorVersion;
private final String xmlForm;
public DeploymentSpec(List<Step> steps,
Optional<Integer> majorVersion,
String xmlForm) {
if (singleInstance(steps)) {
var singleInstance = (DeploymentInstanceSpec)steps.get(0);
this.steps = List.of(singleInstance.withSteps(completeSteps(singleInstance.steps())));
}
else {
this.steps = List.copyOf(completeSteps(steps));
}
this.majorVersion = majorVersion;
this.xmlForm = xmlForm;
validateTotalDelay(steps);
}
public DeploymentSpec(Optional<String> globalServiceId, UpgradePolicy upgradePolicy, Optional<Integer> majorVersion,
List<ChangeBlocker> changeBlockers, List<Step> steps, String xmlForm,
Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService,
Notifications notifications,
List<Endpoint> endpoints) {
this(List.of(new DeploymentInstanceSpec(InstanceName.from("default"),
steps,
upgradePolicy,
changeBlockers,
globalServiceId,
athenzDomain,
athenzService,
notifications,
endpoints)),
majorVersion,
xmlForm);
}
/** Adds missing required steps and reorders steps to a permissible order */
private static List<DeploymentSpec.Step> completeSteps(List<DeploymentSpec.Step> inputSteps) {
List<Step> steps = new ArrayList<>(inputSteps);
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.prod)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.staging))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.staging));
}
if (steps.stream().anyMatch(step -> step.deploysTo(Environment.staging)) &&
steps.stream().noneMatch(step -> step.deploysTo(Environment.test))) {
steps.add(new DeploymentSpec.DeclaredZone(Environment.test));
}
DeploymentSpec.DeclaredZone testStep = remove(Environment.test, steps);
if (testStep != null)
steps.add(0, testStep);
DeploymentSpec.DeclaredZone stagingStep = remove(Environment.staging, steps);
if (stagingStep != null)
steps.add(1, stagingStep);
return steps;
}
/**
* Removes the first occurrence of a deployment step to the given environment and returns it.
*
* @return the removed step, or null if it is not present
*/
private static DeploymentSpec.DeclaredZone remove(Environment environment, List<DeploymentSpec.Step> steps) {
for (int i = 0; i < steps.size(); i++) {
if ( ! (steps.get(i) instanceof DeploymentSpec.DeclaredZone)) continue;
DeploymentSpec.DeclaredZone zoneStep = (DeploymentSpec.DeclaredZone)steps.get(i);
if (zoneStep.environment() == environment) {
steps.remove(i);
return zoneStep;
}
}
return null;
}
/** Throw an IllegalArgumentException if the total delay exceeds 24 hours */
private void validateTotalDelay(List<Step> steps) {
long totalDelaySeconds = steps.stream().mapToLong(step -> (step.delay().getSeconds())).sum();
if (totalDelaySeconds > Duration.ofHours(24).getSeconds())
throw new IllegalArgumentException("The total delay specified is " + Duration.ofSeconds(totalDelaySeconds) +
" but max 24 hours is allowed");
}
private DeploymentInstanceSpec defaultInstance() {
if (singleInstance(steps)) return (DeploymentInstanceSpec)steps.get(0);
throw new IllegalArgumentException("This deployment spec does not support the legacy API " +
"as it has multiple instances: " +
instances().stream().map(Step::toString).collect(Collectors.joining(",")));
}
public Optional<String> globalServiceId() { return defaultInstance().globalServiceId(); }
public UpgradePolicy upgradePolicy() { return defaultInstance().upgradePolicy(); }
/** Returns the major version this application is pinned to, or empty (default) to allow all major versions */
public Optional<Integer> majorVersion() { return majorVersion; }
public boolean canUpgradeAt(Instant instant) { return defaultInstance().canUpgradeAt(instant); }
public boolean canChangeRevisionAt(Instant instant) { return defaultInstance().canChangeRevisionAt(instant); }
public List<ChangeBlocker> changeBlocker() { return defaultInstance().changeBlocker(); }
/** Returns the deployment steps of this in the order they will be performed */
public List<Step> steps() {
if (singleInstance(steps)) return defaultInstance().steps();
return steps;
}
public List<DeclaredZone> zones() {
return defaultInstance().steps().stream()
.flatMap(step -> step.zones().stream())
.collect(Collectors.toList());
}
public Optional<AthenzDomain> athenzDomain() { return defaultInstance().athenzDomain(); }
public Optional<AthenzService> athenzService(Environment environment, RegionName region) {
return defaultInstance().athenzService(environment, region);
}
public Notifications notifications() { return defaultInstance().notifications(); }
public List<Endpoint> endpoints() { return defaultInstance().endpoints(); }
/** Returns the XML form of this spec, or null if it was not created by fromXml, nor is empty */
public String xmlForm() { return xmlForm; }
public boolean includes(Environment environment, Optional<RegionName> region) {
return defaultInstance().deploysTo(environment, region);
}
private static boolean singleInstance(List<DeploymentSpec.Step> steps) {
return steps.size() == 1 && steps.get(0) instanceof DeploymentInstanceSpec;
}
/** Returns the instance step containing the given instance name, or null if not present */
public DeploymentInstanceSpec instance(String name) {
return instance(InstanceName.from(name));
}
/** Returns the instance step containing the given instance name, or null if not present */
/** Returns the instance step containing the given instance name, or throws an IllegalArgumentException if not present */
public DeploymentInstanceSpec requireInstance(String name) {
return requireInstance(InstanceName.from(name));
}
public DeploymentInstanceSpec requireInstance(InstanceName name) {
DeploymentInstanceSpec instance = instance(name);
if (instance == null)
throw new IllegalArgumentException("No instance '" + name + "' in deployment.xml'. Instances: " +
instances().stream().map(spec -> spec.name().toString()).collect(Collectors.joining(",")));
return instance;
}
/** Returns the steps of this which are instances */
public List<DeploymentInstanceSpec> instances() {
return steps.stream()
.filter(step -> step instanceof DeploymentInstanceSpec).map(DeploymentInstanceSpec.class::cast)
.collect(Collectors.toList());
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(Reader reader) {
return new DeploymentSpecXmlReader().read(reader);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm) {
return fromXml(xmlForm, true);
}
/**
* Creates a deployment spec from XML.
*
* @throws IllegalArgumentException if the XML is invalid
*/
public static DeploymentSpec fromXml(String xmlForm, boolean validate) {
return new DeploymentSpecXmlReader(validate).read(xmlForm);
}
public static String toMessageString(Throwable t) {
StringBuilder b = new StringBuilder();
String lastMessage = null;
String message;
for (; t != null; t = t.getCause()) {
message = t.getMessage();
if (message == null) continue;
if (message.equals(lastMessage)) continue;
if (b.length() > 0) {
b.append(": ");
}
b.append(message);
lastMessage = message;
}
return b.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeploymentSpec other = (DeploymentSpec) o;
return majorVersion.equals(other.majorVersion) &&
steps.equals(other.steps) &&
xmlForm.equals(other.xmlForm);
}
@Override
public int hashCode() {
return Objects.hash(majorVersion, steps, xmlForm);
}
/** This may be invoked by a continuous build */
public static void main(String[] args) {
if (args.length != 2 && args.length != 3) {
System.err.println("Usage: DeploymentSpec [file] [environment] [region]?" +
"Returns 0 if the specified zone matches the deployment spec, 1 otherwise");
System.exit(1);
}
try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) {
DeploymentSpec spec = DeploymentSpec.fromXml(reader);
Environment environment = Environment.from(args[1]);
Optional<RegionName> region = args.length == 3 ? Optional.of(RegionName.from(args[2])) : Optional.empty();
if (spec.includes(environment, region))
System.exit(0);
else
System.exit(1);
}
catch (Exception e) {
System.err.println("Exception checking deployment spec: " + toMessageString(e));
System.exit(1);
}
}
/** A deployment step */
public abstract static class Step {
/** Returns whether this step deploys to the given region */
public final boolean deploysTo(Environment environment) {
return deploysTo(environment, Optional.empty());
}
/** Returns whether this step deploys to the given environment, and (if specified) region */
public abstract boolean deploysTo(Environment environment, Optional<RegionName> region);
/** Returns the zones deployed to in this step */
public List<DeclaredZone> zones() { return Collections.emptyList(); }
/** The delay introduced by this step (beyond the time it takes to execute the step). Default is zero. */
public Duration delay() { return Duration.ZERO; }
/** Returns all the steps nested in this. This default implementatiino returns an empty list. */
public List<Step> steps() { return List.of(); }
}
/** A deployment step which is to wait for some time before progressing to the next step */
public static class Delay extends Step {
private final Duration duration;
public Delay(Duration duration) {
this.duration = duration;
}
public Duration duration() { return duration; }
@Override
public Duration delay() { return duration; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) { return false; }
@Override
public String toString() {
return "delay " + duration;
}
}
/** A deployment step which is to run deployment in a particular zone */
public static class DeclaredZone extends Step {
private final Environment environment;
private final Optional<RegionName> region;
private final boolean active;
private final Optional<AthenzService> athenzService;
private final Optional<String> testerFlavor;
public DeclaredZone(Environment environment) {
this(environment, Optional.empty(), false);
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active) {
this(environment, region, active, Optional.empty(), Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active, Optional<AthenzService> athenzService) {
this(environment, region, active, athenzService, Optional.empty());
}
public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active,
Optional<AthenzService> athenzService, Optional<String> testerFlavor) {
if (environment != Environment.prod && region.isPresent())
throw new IllegalArgumentException("Non-prod environments cannot specify a region");
if (environment == Environment.prod && region.isEmpty())
throw new IllegalArgumentException("Prod environments must be specified with a region");
this.environment = environment;
this.region = region;
this.active = active;
this.athenzService = athenzService;
this.testerFlavor = testerFlavor;
}
public Environment environment() { return environment; }
/** The region name, or empty if not declared */
public Optional<RegionName> region() { return region; }
/** Returns whether this zone should receive production traffic */
public boolean active() { return active; }
public Optional<String> testerFlavor() { return testerFlavor; }
public Optional<AthenzService> athenzService() { return athenzService; }
@Override
public List<DeclaredZone> zones() { return Collections.singletonList(this); }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
if (environment != this.environment) return false;
if (region.isPresent() && ! region.equals(this.region)) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hash(environment, region);
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if ( ! (o instanceof DeclaredZone)) return false;
DeclaredZone other = (DeclaredZone)o;
if (this.environment != other.environment) return false;
if ( ! this.region.equals(other.region())) return false;
return true;
}
@Override
public String toString() {
return environment + (region.map(regionName -> "." + regionName).orElse(""));
}
}
/** A deployment step which is to run multiple steps (zones or instances) in parallel */
public static class ParallelZones extends Step {
private final List<Step> steps;
public ParallelZones(List<Step> steps) {
this.steps = List.copyOf(steps);
}
/** Returns the steps inside this which are zones */
@Override
public List<DeclaredZone> zones() {
return this.steps.stream()
.filter(step -> step instanceof DeclaredZone)
.map(DeclaredZone.class::cast)
.collect(Collectors.toList());
}
/** Returns all the steps nested in this */
@Override
public List<Step> steps() { return steps; }
@Override
public boolean deploysTo(Environment environment, Optional<RegionName> region) {
return steps().stream().anyMatch(zone -> zone.deploysTo(environment, region));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ParallelZones)) return false;
ParallelZones that = (ParallelZones) o;
return Objects.equals(steps, that.steps);
}
@Override
public int hashCode() {
return Objects.hash(steps);
}
@Override
public String toString() {
return steps.size() + " parallel steps";
}
}
/** Controls when this application will be upgraded to new Vespa versions */
public enum UpgradePolicy {
/** Canary: Applications with this policy will upgrade before any other */
canary,
/** Default: Will upgrade after all canary applications upgraded successfully. The default. */
defaultPolicy,
/** Will upgrade after most default applications upgraded successfully */
conservative
}
/** A blocking of changes in a given time window */
public static class ChangeBlocker {
private final boolean revision;
private final boolean version;
private final TimeWindow window;
public ChangeBlocker(boolean revision, boolean version, TimeWindow window) {
this.revision = revision;
this.version = version;
this.window = window;
}
public boolean blocksRevisions() { return revision; }
public boolean blocksVersions() { return version; }
public TimeWindow window() { return window; }
@Override
public String toString() {
return "change blocker revision=" + revision + " version=" + version + " window=" + window;
}
}
} |
There's both a default and instance1 in there somewhere, but yes we need more tests when we do the orchestration part at least (but perhaps not in the API). | public void multiple_endpoints() {
tester.computeVersionStatus();
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();
ApplicationId id = createTenantAndApplication();
long projectId = 1;
MultiPartStreamer deployData = createApplicationDeployData(Optional.empty(), false);
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 100);
for (var job : List.of(JobType.productionUsWest1, JobType.productionUsEast3, JobType.productionEuWest1)) {
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/" + job.zone(SystemName.main).region().value() + "/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(job)
.application(id)
.projectId(projectId)
.submit();
}
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?endpointId=default", GET)
.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?endpointId=eu", GET)
.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?endpointId=eu", GET)
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"IN\"}}",
200);
} | .instances("instance1") | public void multiple_endpoints() {
tester.computeVersionStatus();
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();
ApplicationId id = createTenantAndApplication();
long projectId = 1;
MultiPartStreamer deployData = createApplicationDeployData(Optional.empty(), false);
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 100);
for (var job : List.of(JobType.productionUsWest1, JobType.productionUsEast3, JobType.productionEuWest1)) {
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/" + job.zone(SystemName.main).region().value() + "/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(job)
.application(id)
.projectId(projectId)
.submit();
}
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?endpointId=default", GET)
.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?endpointId=eu", GET)
.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?endpointId=eu", GET)
.userIdentity(USER_ID),
"{\"bcpStatus\":{\"rotationStatus\":\"IN\"}}",
200);
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
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 HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("dummy");
private static final ZoneId TEST_ZONE = ZoneId.from(Environment.test, RegionName.from("us-east-1"));
private static final ZoneId STAGING_ZONE = ZoneId.from(Environment.staging, RegionName.from("us-east-3"));
private ContainerControllerTester controllerTester;
private ContainerTester tester;
@Before
public void before() {
controllerTester = new ContainerControllerTester(container, responseFiles);
tester = controllerTester.containerTester();
}
@Test
public void testApplicationApi() {
tester.computeVersionStatus();
tester.controller().jobController().setRunner(__ -> { });
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),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/user", GET).userIdentity(USER_ID),
new File("user.json"));
tester.assertResponse(request("/application/v4/user", PUT).userIdentity(USER_ID),
"{\"message\":\"Created user 'by-myuser'\"}");
tester.assertResponse(request("/application/v4/user", GET).userIdentity(USER_ID),
new File("user-which-exists.json"));
tester.assertResponse(request("/application/v4/tenant/by-myuser", DELETE).userIdentity(USER_ID),
"{\"tenant\":\"by-myuser\",\"type\":\"USER\",\"applications\":[]}");
tester.assertResponse(request("/application/v4/tenant/", GET).userIdentity(USER_ID),
new File("tenant-list.json"));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT)
.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)
.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),
new File("application-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"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
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)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(entity::data)))
.userIdentity(USER_ID),
new File("deploy-result.json"));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
long screwdriverProjectId = 123;
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value()));
controllerTester.jobCompletion(JobType.component)
.application(id)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackageInstance1)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/instance1/", POST)
.data(createApplicationDeployData(Optional.empty(), false))
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in test.us-east-1\"}");
controllerTester.jobCompletion(JobType.systemTest)
.application(id)
.projectId(screwdriverProjectId)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-east-3/instance/instance1/", POST)
.data(createApplicationDeployData(Optional.empty(), false))
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-east-3/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in staging.us-east-3\"}");
controllerTester.jobCompletion(JobType.stagingTest)
.application(id)
.projectId(screwdriverProjectId)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(createApplicationDeployData(Optional.empty(), false))
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsCentral1)
.application(id)
.projectId(screwdriverProjectId)
.unsuccessful()
.submit();
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(BuildJob.defaultSourceRevision,
BuildJob.defaultBuildNumber - 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),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1.instance1 with version 1.0.41-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(BuildJob.defaultSourceRevision,
BuildJob.defaultBuildNumber)),
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")
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application-reference-2.json"));
ApplicationId app2 = ApplicationId.from("tenant2", "application2", "default");
long screwdriverProjectId2 = 456;
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(app2.application().value()));
controllerTester.controller().applications().deploymentTrigger().triggerChange(TenantAndApplicationId.from(app2), Change.of(Version.fromString("7.0")));
controllerTester.jobCompletion(JobType.component)
.application(app2)
.projectId(screwdriverProjectId2)
.uploadArtifact(applicationPackage)
.submit();
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\":\"-----BEGIN PUBLIC KEY-----\n∠( ᐛ 」∠)_\n-----END PUBLIC KEY-----\"}"),
"{\"message\":\"Added deploy key -----BEGIN PUBLIC KEY-----\\n∠( ᐛ 」∠)_\\n-----END PUBLIC KEY-----\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", PATCH)
.userIdentity(USER_ID)
.data("{\"pemDeployKey\":\"-----BEGIN PUBLIC KEY-----\n∠( ᐛ 」∠)_\n-----END PUBLIC KEY-----\"}"),
"{\"message\":\"Added deploy key -----BEGIN PUBLIC KEY-----\\n∠( ᐛ 」∠)_\\n-----END PUBLIC KEY-----\"}");
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/key", DELETE)
.userIdentity(USER_ID)
.data("{\"key\":\"-----BEGIN PUBLIC KEY-----\\n∠( ᐛ 」∠)_\\n-----END PUBLIC KEY-----\"}"),
"{\"message\":\"Removed deploy key -----BEGIN PUBLIC KEY-----\\n∠( ᐛ 」∠)_\\n-----END PUBLIC KEY-----\"}");
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", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
"{\"message\":\"Deleted application tenant2.application2\"}");
controllerTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
tester.computeVersionStatus();
setDeploymentMaintainedInfo(controllerTester);
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("application.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(controllerTester, 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("application1-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/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.42-commit1' to 'no change' for application 'tenant1.application1'\"}");
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 application 'tenant1.application1' 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\"}");
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 application 'tenant1.application1'\"}");
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\"}");
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 application 'tenant1.application1'\"}");
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 application 'tenant1.application1'\"}");
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", 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)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
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?hostname=host1", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"error-code\":\"INTERNAL_SERVER_ERROR\",\"message\":\"No node with the hostname host1 is known.\"}", 500);
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),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-west-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.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1", POST)
.userIdentity(USER_ID)
.data(createApplicationDeployData(applicationPackage, false)),
new File("deployment-job-accepted.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage)),
"{\"message\":\"Application package version: 1.0.43-d00d, source revision of repository 'repo', branch 'master' with commit 'd00d', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
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();
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService)),
"{\"message\":\"Application package version: 1.0.44-d00d, source revision of repository 'repo', branch 'master' with commit 'd00d', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
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)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService);
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.45-d00d, source revision of repository 'repo', branch 'master' with commit 'd00d', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationId app1 = ApplicationId.from("tenant1", "application1", "instance1");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/jobreport", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(asJson(DeploymentJobs.JobReport.ofComponent(app1,
1234,
123,
Optional.empty(),
BuildJob.defaultSourceRevision))),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"" + app1 + " is set up to be deployed from internally," +
" and no longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.\"}",
400);
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/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 1 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Unregistered 'tenant1.application1.instance1' from internal deployment pipeline.\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/jobreport", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(asJson(DeploymentJobs.JobReport.ofComponent(app1,
1234,
123,
Optional.empty(),
BuildJob.defaultSourceRevision))),
"{\"message\":\"ok\"}");
byte[] data = new byte[0];
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.data(data)
.userIdentity(new UserId("new_user")),
new File("create-user-response.json"));
tester.assertResponse(request("/application/v4/user", GET)
.userIdentity(new UserId("other_user")),
"{\"user\":\"other_user\",\"tenants\":[],\"tenantExists\":false}");
tester.assertResponse(request("/application/v4/", Request.Method.OPTIONS)
.userIdentity(USER_ID),
"");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("tenant-without-applications.json"));
}
private void addIssues(ContainerControllerTester tester, TenantAndApplicationId id) {
tester.controller().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() {
tester.computeVersionStatus();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
ApplicationId id = createTenantAndApplication();
long projectId = 1;
MultiPartStreamer deployData = createApplicationDeployData(Optional.of(applicationPackage), false);
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 100);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsWest1)
.application(id)
.projectId(projectId)
.submit();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
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-east-3/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-east-3\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-east-3/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-east-3\"}",
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"));
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"));
}
@Test
@Test
public void testDeployDirectly() {
tester.computeVersionStatus();
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),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId("application1"));
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);
tester.upgradeSystem(tester.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 testSortsDeploymentsAndJobs() {
tester.computeVersionStatus();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-east-3")
.build();
ApplicationId id = createTenantAndApplication();
long projectId = 1;
MultiPartStreamer deployData = createApplicationDeployData(Optional.empty(), false);
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 100);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-east-3/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsEast3)
.application(id)
.projectId(projectId)
.submit();
applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 101);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsWest1)
.application(id)
.projectId(projectId)
.submit();
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-east-3/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsEast3)
.application(id)
.projectId(projectId)
.submit();
setDeploymentMaintainedInfo(controllerTester);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("application-without-change-multiple-deployments.json"));
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = (MockMeteringClient) controllerTester.containerTester().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)),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246)),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492))));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application1-metering.json"));
}
@Test
public void testErrorResponses() throws Exception {
tester.computeVersionStatus();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT)
.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/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),
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),
"{\"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)
.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),
"{\"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/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz tenant name cannot have prefix 'by-'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/hosted-vespa", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT),
"{\"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),
new File("application-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Application already exists\"}",
400);
ConfigServerMock configServer = serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
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", 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", 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"), "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),
"{\"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),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete application 'tenant1.application1.instance1': Application not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
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),
"{\"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)
.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),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT),
"{\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),
new File("application-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),
new File("application-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete application; more than one instance present: [tenant1.application1, tenant1.application1.instance1]\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT),
"{\"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),
"{\"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 deployment_fails_on_illegal_domain_in_deployment_spec() {
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();
long screwdriverProjectId = 123;
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"), true);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
}
@Test
public void deployment_succeeds_when_correct_domain_is_used() {
ApplicationPackage 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();
long screwdriverProjectId = 123;
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
new File("deploy-result.json"));
}
@Test
public void deployment_fails_for_personal_tenants_when_athenzdomain_specified_and_user_not_admin() {
tester.computeVersionStatus();
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
byte[] data = new byte[0];
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.data(data)
.userIdentity(userId),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.dev)
.region("us-west-1")
.build();
String expectedResult="{\"error-code\":\"BAD_REQUEST\",\"message\":\"User user.new-user is not allowed to launch services in Athenz domain domain1. Please reach out to the domain admin.\"}";
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(userId),
expectedResult,
400);
}
@Test
public void deployment_succeeds_for_personal_tenants_when_user_is_tenant_admin() {
tester.computeVersionStatus();
UserId tenantAdmin = new UserId("new_user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
byte[] data = new byte[0];
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.data(data)
.userIdentity(tenantAdmin),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.dev)
.region("us-west-1")
.build();
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(tenantAdmin),
new File("deploy-result.json"));
}
@Test
public void deployment_fails_when_athenz_service_cannot_be_launched() {
ApplicationPackage 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();
long screwdriverProjectId = 123;
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), false);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
String expectedResult="{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}";
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
expectedResult,
400);
}
@Test
public void redeployment_succeeds_when_not_specifying_versions_or_application_package() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.computeVersionStatus();
ApplicationPackage 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();
long screwdriverProjectId = 123;
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(Optional.empty(), true))
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
}
@Test
public void testJobStatusReporting() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.computeVersionStatus();
long projectId = 1;
Application app = controllerTester.createApplication();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-central-1")
.build();
Version vespaVersion = new Version("6.1");
BuildJob job = new BuildJob(report -> notifyCompletion(report, controllerTester), controllerTester.containerTester().serviceRegistry().artifactRepositoryMock())
.application(app)
.projectId(projectId);
job.type(JobType.component).uploadArtifact(applicationPackage).submit();
controllerTester.deploy(app.id().defaultInstance(), applicationPackage, TEST_ZONE);
job.type(JobType.systemTest).submit();
Request request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(asJson(job.type(JobType.systemTest).report()))
.userIdentity(HOSTED_VESPA_OPERATOR)
.get();
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of system-test for tenant1.application1, but that has not been triggered; last was " +
controllerTester.controller().applications().requireInstance(app.id().defaultInstance()).deploymentJobs().jobStatus().get(JobType.systemTest).lastTriggered().get().at() + "\"}", 400);
request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(asJson(job.type(JobType.productionUsEast3).report()))
.userIdentity(HOSTED_VESPA_OPERATOR)
.get();
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of production-us-east-3 for tenant1.application1, but that has not been triggered; last was never\"}",
400);
JobStatus recordedStatus =
tester.controller().applications().getInstance(app.id().defaultInstance()).get().deploymentJobs().jobStatus().get(JobType.component);
assertNotNull("Status was recorded", recordedStatus);
assertTrue(recordedStatus.isSuccess());
assertEquals(vespaVersion, recordedStatus.lastCompleted().get().platform());
recordedStatus =
tester.controller().applications().getInstance(app.id().defaultInstance()).get().deploymentJobs().jobStatus().get(JobType.productionApNortheast2);
assertNull("Status of never-triggered jobs is empty", recordedStatus);
assertTrue("All jobs have been run", tester.controller().applications().deploymentTrigger().jobsToRun().isEmpty());
}
@Test
public void testJobStatusReportingOutOfCapacity() {
controllerTester.containerTester().computeVersionStatus();
long projectId = 1;
Application app = controllerTester.createApplication();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-central-1")
.build();
BuildJob job = new BuildJob(report -> notifyCompletion(report, controllerTester), controllerTester.containerTester().serviceRegistry().artifactRepositoryMock())
.application(app)
.projectId(projectId);
job.type(JobType.component).uploadArtifact(applicationPackage).submit();
controllerTester.deploy(app.id().defaultInstance(), applicationPackage, TEST_ZONE);
job.type(JobType.systemTest).submit();
controllerTester.deploy(app.id().defaultInstance(), applicationPackage, STAGING_ZONE);
job.type(JobType.stagingTest).error(DeploymentJobs.JobError.outOfCapacity).submit();
JobStatus jobStatus = tester.controller().applications().getInstance(app.id().defaultInstance()).get()
.deploymentJobs()
.jobStatus()
.get(JobType.stagingTest);
assertFalse(jobStatus.isSuccess());
assertEquals(DeploymentJobs.JobError.outOfCapacity, jobStatus.jobError().get());
}
@Test
public void applicationWithRoutingPolicy() {
Application app = controllerTester.createApplication();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
controllerTester.deployCompletely(app, applicationPackage, 1, false);
RoutingPolicy policy = new RoutingPolicy(app.id().defaultInstance(),
ClusterSpec.Id.from("default"),
ZoneId.from(Environment.prod, RegionName.from("us-west-1")),
HostName.from("lb-0-canonical-name"),
Optional.of("dns-zone-1"), Set.of(EndpointId.of("c0")));
tester.controller().curator().writeRoutingPolicies(app.id().defaultInstance(), Set.of(policy));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
new File("application-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private void notifyCompletion(DeploymentJobs.JobReport report, ContainerControllerTester tester) {
assertResponse(request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.userIdentity(HOSTED_VESPA_OPERATOR)
.data(asJson(report))
.get(),
200, "{\"message\":\"ok\"}");
tester.controller().applications().deploymentTrigger().triggerReadyJobs();
}
private static byte[] asJson(DeploymentJobs.JobReport report) {
Slime slime = new Slime();
Cursor cursor = slime.setObject();
cursor.setLong("projectId", report.projectId());
cursor.setString("jobName", report.jobType().jobName());
cursor.setLong("buildNumber", report.buildNumber());
report.jobError().ifPresent(jobError -> cursor.setString("jobError", jobError.name()));
report.version().flatMap(ApplicationVersion::source).ifPresent(sr -> {
Cursor sourceRevision = cursor.setObject("sourceRevision");
sourceRevision.setString("repository", sr.repository());
sourceRevision.setString("branch", sr.branch());
sourceRevision.setString("commit", sr.commit());
});
cursor.setString("tenant", report.applicationId().tenant().value());
cursor.setString("application", report.applicationId().application().value());
cursor.setString("instance", report.applicationId().instance().value());
try {
return SlimeUtils.toJsonBytes(slime);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
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;
}
private MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repo\",\"branch\":\"master\",\"commit\":\"d00d\",\"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) {
AthenzClientFactoryMock mock = (AthenzClientFactoryMock) container.components()
.getComponent(AthenzClientFactoryMock.class.getName());
AthenzDbMock.Domain domainMock = mock.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 configureAthenzIdentity(com.yahoo.vespa.athenz.api.AthenzService service, boolean allowLaunch) {
AthenzClientFactoryMock mock = (AthenzClientFactoryMock) container.components()
.getComponent(AthenzClientFactoryMock.class.getName());
AthenzDbMock.Domain domainMock = mock.getSetup().domains.computeIfAbsent(service.getDomain(), AthenzDbMock.Domain::new);
domainMock.services.put(service.getName(), new AthenzDbMock.Service(allowLaunch));
}
/**
* 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,
com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId applicationId) {
AthenzClientFactoryMock mock = (AthenzClientFactoryMock) container.components()
.getComponent(AthenzClientFactoryMock.class.getName());
AthenzIdentity screwdriverIdentity = HostedAthenzIdentities.from(screwdriverId);
AthenzDbMock.Application athenzApplication = mock.getSetup().domains.get(domain).applications.get(applicationId);
athenzApplication.addRoleMember(ApplicationAction.deploy, screwdriverIdentity);
}
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),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
private void startAndTestChange(ContainerControllerTester controllerTester, ApplicationId application,
long projectId, ApplicationPackage applicationPackage,
MultiPartStreamer deployData, long buildNumber) {
ContainerTester tester = controllerTester.containerTester();
controllerTester.containerTester().serviceRegistry().artifactRepositoryMock()
.put(application, applicationPackage,"1.0." + buildNumber + "-commit1");
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(projectId)
.buildNumber(buildNumber)
.submit();
String testPath = String.format("/application/v4/tenant/%s/application/%s/instance/%s/environment/test/region/us-east-1",
application.tenant().value(), application.application().value(), application.instance().value());
tester.assertResponse(request(testPath, POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request(testPath, DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated " + application + " in test.us-east-1\"}");
controllerTester.jobCompletion(JobType.systemTest)
.application(application)
.projectId(projectId)
.submit();
String stagingPath = String.format("/application/v4/tenant/%s/application/%s/instance/%s/environment/staging/region/us-east-3",
application.tenant().value(), application.application().value(), application.instance().value());
tester.assertResponse(request(stagingPath, POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request(stagingPath, DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated " + application + " in staging.us-east-3\"}");
controllerTester.jobCompletion(JobType.stagingTest)
.application(application)
.projectId(projectId)
.submit();
}
/**
* 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(ContainerControllerTester controllerTester) {
for (Application application : controllerTester.controller().applications().asList()) {
controllerTester.controller().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()) {
Map<ClusterSpec.Id, ClusterInfo> clusterInfo = new HashMap<>();
List<String> hostnames = new ArrayList<>();
hostnames.add("host1");
hostnames.add("host2");
clusterInfo.put(ClusterSpec.Id.from("cluster1"),
new ClusterInfo("flavor1", 37, 2, 4, 50,
ClusterSpec.Type.content, hostnames));
Map<ClusterSpec.Id, ClusterUtilization> clusterUtils = new HashMap<>();
clusterUtils.put(ClusterSpec.Id.from("cluster1"), new ClusterUtilization(0.3, 0.6, 0.4, 0.3));
DeploymentMetrics metrics = new DeploymentMetrics(1, 2, 3, 4, 5,
Optional.of(Instant.ofEpochMilli(123123)), Map.of());
lockedApplication = lockedApplication.with(instance.name(),
lockedInstance -> lockedInstance.withClusterInfo(deployment.zone(), clusterInfo)
.withClusterUtilization(deployment.zone(), clusterUtils)
.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
controllerTester.controller().applications().store(lockedApplication);
}
});
}
}
private ServiceRegistryMock serviceRegistry() {
return (ServiceRegistryMock) tester.container().components().getComponent(ServiceRegistryMock.class.getName());
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator())).run();
}
private RotationStatus rotationStatus(Instance instance) {
return controllerTester.controller().applications().rotationRepository().getRotation(instance)
.map(rotation -> {
var rotationStatus = controllerTester.controller().serviceRegistry().globalRoutingService().getHealthStatus(rotation.name());
var statusMap = new LinkedHashMap<ZoneId, RotationState>();
rotationStatus.forEach((zone, status) -> statusMap.put(zone, RotationState.in));
return RotationStatus.from(Map.of(rotation.id(), statusMap));
})
.orElse(RotationStatus.EMPTY);
}
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));
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 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 OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private Map<String, List<String>> headers = new HashMap<>();
private String recursive;
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(StandardCharsets.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 oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { this.recursive = recursive; 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:
(recursive == null ? "" : "?recursive=" + recursive),
data, method);
request.getHeaders().addAll(headers);
request.getHeaders().put("Content-Type", contentType);
if (identity != null) {
addIdentityToRequest(request, identity);
}
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 HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("dummy");
private static final ZoneId TEST_ZONE = ZoneId.from(Environment.test, RegionName.from("us-east-1"));
private static final ZoneId STAGING_ZONE = ZoneId.from(Environment.staging, RegionName.from("us-east-3"));
private ContainerControllerTester controllerTester;
private ContainerTester tester;
@Before
public void before() {
controllerTester = new ContainerControllerTester(container, responseFiles);
tester = controllerTester.containerTester();
}
@Test
public void testApplicationApi() {
tester.computeVersionStatus();
tester.controller().jobController().setRunner(__ -> { });
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),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/user", GET).userIdentity(USER_ID),
new File("user.json"));
tester.assertResponse(request("/application/v4/user", PUT).userIdentity(USER_ID),
"{\"message\":\"Created user 'by-myuser'\"}");
tester.assertResponse(request("/application/v4/user", GET).userIdentity(USER_ID),
new File("user-which-exists.json"));
tester.assertResponse(request("/application/v4/tenant/by-myuser", DELETE).userIdentity(USER_ID),
"{\"tenant\":\"by-myuser\",\"type\":\"USER\",\"applications\":[]}");
tester.assertResponse(request("/application/v4/tenant/", GET).userIdentity(USER_ID),
new File("tenant-list.json"));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT)
.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)
.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),
new File("application-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"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
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)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(entity::data)))
.userIdentity(USER_ID),
new File("deploy-result.json"));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
long screwdriverProjectId = 123;
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value()));
controllerTester.jobCompletion(JobType.component)
.application(id)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackageInstance1)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/instance1/", POST)
.data(createApplicationDeployData(Optional.empty(), false))
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in test.us-east-1\"}");
controllerTester.jobCompletion(JobType.systemTest)
.application(id)
.projectId(screwdriverProjectId)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-east-3/instance/instance1/", POST)
.data(createApplicationDeployData(Optional.empty(), false))
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-east-3/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in staging.us-east-3\"}");
controllerTester.jobCompletion(JobType.stagingTest)
.application(id)
.projectId(screwdriverProjectId)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(createApplicationDeployData(Optional.empty(), false))
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsCentral1)
.application(id)
.projectId(screwdriverProjectId)
.unsuccessful()
.submit();
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(BuildJob.defaultSourceRevision,
BuildJob.defaultBuildNumber - 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),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1.instance1 with version 1.0.41-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(BuildJob.defaultSourceRevision,
BuildJob.defaultBuildNumber)),
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")
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application-reference-2.json"));
ApplicationId app2 = ApplicationId.from("tenant2", "application2", "default");
long screwdriverProjectId2 = 456;
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(app2.application().value()));
controllerTester.controller().applications().deploymentTrigger().triggerChange(TenantAndApplicationId.from(app2), Change.of(Version.fromString("7.0")));
controllerTester.jobCompletion(JobType.component)
.application(app2)
.projectId(screwdriverProjectId2)
.uploadArtifact(applicationPackage)
.submit();
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/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", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
"{\"message\":\"Deleted application tenant2.application2\"}");
controllerTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
tester.computeVersionStatus();
setDeploymentMaintainedInfo(controllerTester);
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("application.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(controllerTester, 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("application1-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/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.42-commit1' to 'no change' for application 'tenant1.application1'\"}");
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 application 'tenant1.application1' 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\"}");
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 application 'tenant1.application1'\"}");
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\"}");
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 application 'tenant1.application1'\"}");
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 application 'tenant1.application1'\"}");
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", 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)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
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?hostname=host1", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"error-code\":\"INTERNAL_SERVER_ERROR\",\"message\":\"No node with the hostname host1 is known.\"}", 500);
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),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-west-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.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1", POST)
.userIdentity(USER_ID)
.data(createApplicationDeployData(applicationPackage, false)),
new File("deployment-job-accepted.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage)),
"{\"message\":\"Application package version: 1.0.43-d00d, source revision of repository 'repo', branch 'master' with commit 'd00d', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
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();
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService)),
"{\"message\":\"Application package version: 1.0.44-d00d, source revision of repository 'repo', branch 'master' with commit 'd00d', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
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)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService);
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.45-d00d, source revision of repository 'repo', branch 'master' with commit 'd00d', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationId app1 = ApplicationId.from("tenant1", "application1", "instance1");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/jobreport", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(asJson(DeploymentJobs.JobReport.ofComponent(app1,
1234,
123,
Optional.empty(),
BuildJob.defaultSourceRevision))),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"" + app1 + " is set up to be deployed from internally," +
" and no longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.\"}",
400);
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/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 1 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Unregistered 'tenant1.application1.instance1' from internal deployment pipeline.\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/jobreport", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(asJson(DeploymentJobs.JobReport.ofComponent(app1,
1234,
123,
Optional.empty(),
BuildJob.defaultSourceRevision))),
"{\"message\":\"ok\"}");
byte[] data = new byte[0];
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.data(data)
.userIdentity(new UserId("new_user")),
new File("create-user-response.json"));
tester.assertResponse(request("/application/v4/user", GET)
.userIdentity(new UserId("other_user")),
"{\"user\":\"other_user\",\"tenants\":[],\"tenantExists\":false}");
tester.assertResponse(request("/application/v4/", Request.Method.OPTIONS)
.userIdentity(USER_ID),
"");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("tenant-without-applications.json"));
}
private void addIssues(ContainerControllerTester tester, TenantAndApplicationId id) {
tester.controller().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() {
tester.computeVersionStatus();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
ApplicationId id = createTenantAndApplication();
long projectId = 1;
MultiPartStreamer deployData = createApplicationDeployData(Optional.of(applicationPackage), false);
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 100);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsWest1)
.application(id)
.projectId(projectId)
.submit();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
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-east-3/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-east-3\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-east-3/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-east-3\"}",
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"));
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"));
}
@Test
@Test
public void testDeployDirectly() {
tester.computeVersionStatus();
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),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId("application1"));
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);
tester.upgradeSystem(tester.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 testSortsDeploymentsAndJobs() {
tester.computeVersionStatus();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-east-3")
.build();
ApplicationId id = createTenantAndApplication();
long projectId = 1;
MultiPartStreamer deployData = createApplicationDeployData(Optional.empty(), false);
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 100);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-east-3/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsEast3)
.application(id)
.projectId(projectId)
.submit();
applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
startAndTestChange(controllerTester, id, projectId, applicationPackage, deployData, 101);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsWest1)
.application(id)
.projectId(projectId)
.submit();
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-east-3/deploy", POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
controllerTester.jobCompletion(JobType.productionUsEast3)
.application(id)
.projectId(projectId)
.submit();
setDeploymentMaintainedInfo(controllerTester);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("application-without-change-multiple-deployments.json"));
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = (MockMeteringClient) controllerTester.containerTester().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)),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246)),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492))));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application1-metering.json"));
}
@Test
public void testErrorResponses() throws Exception {
tester.computeVersionStatus();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT)
.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/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),
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),
"{\"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)
.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),
"{\"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/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz tenant name cannot have prefix 'by-'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/hosted-vespa", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT),
"{\"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),
new File("application-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
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", 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", 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"), "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),
"{\"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),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT)
.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),
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),
"{\"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)
.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),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT),
"{\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),
new File("application-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),
new File("application-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete application; more than one instance present: [tenant1.application1, tenant1.application1.instance1]\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT),
"{\"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),
"{\"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 deployment_fails_on_illegal_domain_in_deployment_spec() {
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();
long screwdriverProjectId = 123;
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"), true);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
}
@Test
public void deployment_succeeds_when_correct_domain_is_used() {
ApplicationPackage 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();
long screwdriverProjectId = 123;
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
new File("deploy-result.json"));
}
@Test
public void deployment_fails_for_personal_tenants_when_athenzdomain_specified_and_user_not_admin() {
tester.computeVersionStatus();
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
byte[] data = new byte[0];
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.data(data)
.userIdentity(userId),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.dev)
.region("us-west-1")
.build();
String expectedResult="{\"error-code\":\"BAD_REQUEST\",\"message\":\"User user.new-user is not allowed to launch services in Athenz domain domain1. Please reach out to the domain admin.\"}";
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(userId),
expectedResult,
400);
}
@Test
public void deployment_succeeds_for_personal_tenants_when_user_is_tenant_admin() {
tester.computeVersionStatus();
UserId tenantAdmin = new UserId("new_user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
byte[] data = new byte[0];
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.data(data)
.userIdentity(tenantAdmin),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.dev)
.region("us-west-1")
.build();
MultiPartStreamer entity = createApplicationDeployData(applicationPackage, true);
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(tenantAdmin),
new File("deploy-result.json"));
}
@Test
public void deployment_fails_when_athenz_service_cannot_be_launched() {
ApplicationPackage 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();
long screwdriverProjectId = 123;
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), false);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
String expectedResult="{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}";
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
expectedResult,
400);
}
@Test
public void redeployment_succeeds_when_not_specifying_versions_or_application_package() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.computeVersionStatus();
ApplicationPackage 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();
long screwdriverProjectId = 123;
ScrewdriverId screwdriverId = new ScrewdriverId(Long.toString(screwdriverProjectId));
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
configureAthenzIdentity(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"), true);
Application application = controllerTester.createApplication(ATHENZ_TENANT_DOMAIN.getName(), "tenant1", "application1", "default");
controllerTester.authorize(ATHENZ_TENANT_DOMAIN, screwdriverId, ApplicationAction.deploy, application.id());
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(screwdriverProjectId)
.uploadArtifact(applicationPackage)
.submit();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(applicationPackage, false))
.screwdriverIdentity(screwdriverId),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/default/", POST)
.data(createApplicationDeployData(Optional.empty(), true))
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
}
@Test
public void testJobStatusReporting() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.computeVersionStatus();
long projectId = 1;
Application app = controllerTester.createApplication();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-central-1")
.build();
Version vespaVersion = new Version("6.1");
BuildJob job = new BuildJob(report -> notifyCompletion(report, controllerTester), controllerTester.containerTester().serviceRegistry().artifactRepositoryMock())
.application(app)
.projectId(projectId);
job.type(JobType.component).uploadArtifact(applicationPackage).submit();
controllerTester.deploy(app.id().defaultInstance(), applicationPackage, TEST_ZONE);
job.type(JobType.systemTest).submit();
Request request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(asJson(job.type(JobType.systemTest).report()))
.userIdentity(HOSTED_VESPA_OPERATOR)
.get();
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of system-test for tenant1.application1, but that has not been triggered; last was " +
controllerTester.controller().applications().requireInstance(app.id().defaultInstance()).deploymentJobs().jobStatus().get(JobType.systemTest).lastTriggered().get().at() + "\"}", 400);
request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(asJson(job.type(JobType.productionUsEast3).report()))
.userIdentity(HOSTED_VESPA_OPERATOR)
.get();
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of production-us-east-3 for tenant1.application1, but that has not been triggered; last was never\"}",
400);
JobStatus recordedStatus =
tester.controller().applications().getInstance(app.id().defaultInstance()).get().deploymentJobs().jobStatus().get(JobType.component);
assertNotNull("Status was recorded", recordedStatus);
assertTrue(recordedStatus.isSuccess());
assertEquals(vespaVersion, recordedStatus.lastCompleted().get().platform());
recordedStatus =
tester.controller().applications().getInstance(app.id().defaultInstance()).get().deploymentJobs().jobStatus().get(JobType.productionApNortheast2);
assertNull("Status of never-triggered jobs is empty", recordedStatus);
assertTrue("All jobs have been run", tester.controller().applications().deploymentTrigger().jobsToRun().isEmpty());
}
@Test
public void testJobStatusReportingOutOfCapacity() {
controllerTester.containerTester().computeVersionStatus();
long projectId = 1;
Application app = controllerTester.createApplication();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-central-1")
.build();
BuildJob job = new BuildJob(report -> notifyCompletion(report, controllerTester), controllerTester.containerTester().serviceRegistry().artifactRepositoryMock())
.application(app)
.projectId(projectId);
job.type(JobType.component).uploadArtifact(applicationPackage).submit();
controllerTester.deploy(app.id().defaultInstance(), applicationPackage, TEST_ZONE);
job.type(JobType.systemTest).submit();
controllerTester.deploy(app.id().defaultInstance(), applicationPackage, STAGING_ZONE);
job.type(JobType.stagingTest).error(DeploymentJobs.JobError.outOfCapacity).submit();
JobStatus jobStatus = tester.controller().applications().getInstance(app.id().defaultInstance()).get()
.deploymentJobs()
.jobStatus()
.get(JobType.stagingTest);
assertFalse(jobStatus.isSuccess());
assertEquals(DeploymentJobs.JobError.outOfCapacity, jobStatus.jobError().get());
}
@Test
public void applicationWithRoutingPolicy() {
Application app = controllerTester.createApplication();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
controllerTester.deployCompletely(app, applicationPackage, 1, false);
RoutingPolicy policy = new RoutingPolicy(app.id().defaultInstance(),
ClusterSpec.Id.from("default"),
ZoneId.from(Environment.prod, RegionName.from("us-west-1")),
HostName.from("lb-0-canonical-name"),
Optional.of("dns-zone-1"), Set.of(EndpointId.of("c0")));
tester.controller().curator().writeRoutingPolicies(app.id().defaultInstance(), Set.of(policy));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
new File("application-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private void notifyCompletion(DeploymentJobs.JobReport report, ContainerControllerTester tester) {
assertResponse(request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.userIdentity(HOSTED_VESPA_OPERATOR)
.data(asJson(report))
.get(),
200, "{\"message\":\"ok\"}");
tester.controller().applications().deploymentTrigger().triggerReadyJobs();
}
private static byte[] asJson(DeploymentJobs.JobReport report) {
Slime slime = new Slime();
Cursor cursor = slime.setObject();
cursor.setLong("projectId", report.projectId());
cursor.setString("jobName", report.jobType().jobName());
cursor.setLong("buildNumber", report.buildNumber());
report.jobError().ifPresent(jobError -> cursor.setString("jobError", jobError.name()));
report.version().flatMap(ApplicationVersion::source).ifPresent(sr -> {
Cursor sourceRevision = cursor.setObject("sourceRevision");
sourceRevision.setString("repository", sr.repository());
sourceRevision.setString("branch", sr.branch());
sourceRevision.setString("commit", sr.commit());
});
cursor.setString("tenant", report.applicationId().tenant().value());
cursor.setString("application", report.applicationId().application().value());
cursor.setString("instance", report.applicationId().instance().value());
try {
return SlimeUtils.toJsonBytes(slime);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
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;
}
private MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repo\",\"branch\":\"master\",\"commit\":\"d00d\",\"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) {
AthenzClientFactoryMock mock = (AthenzClientFactoryMock) container.components()
.getComponent(AthenzClientFactoryMock.class.getName());
AthenzDbMock.Domain domainMock = mock.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 configureAthenzIdentity(com.yahoo.vespa.athenz.api.AthenzService service, boolean allowLaunch) {
AthenzClientFactoryMock mock = (AthenzClientFactoryMock) container.components()
.getComponent(AthenzClientFactoryMock.class.getName());
AthenzDbMock.Domain domainMock = mock.getSetup().domains.computeIfAbsent(service.getDomain(), AthenzDbMock.Domain::new);
domainMock.services.put(service.getName(), new AthenzDbMock.Service(allowLaunch));
}
/**
* 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,
com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId applicationId) {
AthenzClientFactoryMock mock = (AthenzClientFactoryMock) container.components()
.getComponent(AthenzClientFactoryMock.class.getName());
AthenzIdentity screwdriverIdentity = HostedAthenzIdentities.from(screwdriverId);
AthenzDbMock.Application athenzApplication = mock.getSetup().domains.get(domain).applications.get(applicationId);
athenzApplication.addRoleMember(ApplicationAction.deploy, screwdriverIdentity);
}
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),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT),
new File("application-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN,
new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
private void startAndTestChange(ContainerControllerTester controllerTester, ApplicationId application,
long projectId, ApplicationPackage applicationPackage,
MultiPartStreamer deployData, long buildNumber) {
ContainerTester tester = controllerTester.containerTester();
controllerTester.containerTester().serviceRegistry().artifactRepositoryMock()
.put(application, applicationPackage,"1.0." + buildNumber + "-commit1");
controllerTester.jobCompletion(JobType.component)
.application(application)
.projectId(projectId)
.buildNumber(buildNumber)
.submit();
String testPath = String.format("/application/v4/tenant/%s/application/%s/instance/%s/environment/test/region/us-east-1",
application.tenant().value(), application.application().value(), application.instance().value());
tester.assertResponse(request(testPath, POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request(testPath, DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated " + application + " in test.us-east-1\"}");
controllerTester.jobCompletion(JobType.systemTest)
.application(application)
.projectId(projectId)
.submit();
String stagingPath = String.format("/application/v4/tenant/%s/application/%s/instance/%s/environment/staging/region/us-east-3",
application.tenant().value(), application.application().value(), application.instance().value());
tester.assertResponse(request(stagingPath, POST)
.data(deployData)
.screwdriverIdentity(SCREWDRIVER_ID),
new File("deploy-result.json"));
tester.assertResponse(request(stagingPath, DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated " + application + " in staging.us-east-3\"}");
controllerTester.jobCompletion(JobType.stagingTest)
.application(application)
.projectId(projectId)
.submit();
}
/**
* 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(ContainerControllerTester controllerTester) {
for (Application application : controllerTester.controller().applications().asList()) {
controllerTester.controller().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()) {
Map<ClusterSpec.Id, ClusterInfo> clusterInfo = new HashMap<>();
List<String> hostnames = new ArrayList<>();
hostnames.add("host1");
hostnames.add("host2");
clusterInfo.put(ClusterSpec.Id.from("cluster1"),
new ClusterInfo("flavor1", 37, 2, 4, 50,
ClusterSpec.Type.content, hostnames));
Map<ClusterSpec.Id, ClusterUtilization> clusterUtils = new HashMap<>();
clusterUtils.put(ClusterSpec.Id.from("cluster1"), new ClusterUtilization(0.3, 0.6, 0.4, 0.3));
DeploymentMetrics metrics = new DeploymentMetrics(1, 2, 3, 4, 5,
Optional.of(Instant.ofEpochMilli(123123)), Map.of());
lockedApplication = lockedApplication.with(instance.name(),
lockedInstance -> lockedInstance.withClusterInfo(deployment.zone(), clusterInfo)
.withClusterUtilization(deployment.zone(), clusterUtils)
.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
controllerTester.controller().applications().store(lockedApplication);
}
});
}
}
private ServiceRegistryMock serviceRegistry() {
return (ServiceRegistryMock) tester.container().components().getComponent(ServiceRegistryMock.class.getName());
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator())).run();
}
private RotationStatus rotationStatus(Instance instance) {
return controllerTester.controller().applications().rotationRepository().getRotation(instance)
.map(rotation -> {
var rotationStatus = controllerTester.controller().serviceRegistry().globalRoutingService().getHealthStatus(rotation.name());
var statusMap = new LinkedHashMap<ZoneId, RotationState>();
rotationStatus.forEach((zone, status) -> statusMap.put(zone, RotationState.in));
return RotationStatus.from(Map.of(rotation.id(), statusMap));
})
.orElse(RotationStatus.EMPTY);
}
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));
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 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 OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private Map<String, List<String>> headers = new HashMap<>();
private String recursive;
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(StandardCharsets.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 oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { this.recursive = recursive; 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:
(recursive == null ? "" : "?recursive=" + recursive),
data, method);
request.getHeaders().addAll(headers);
request.getHeaders().put("Content-Type", contentType);
if (identity != null) {
addIdentityToRequest(request, identity);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} |
Path parameter should be renamed. | private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/user")) return authenticatedUser(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}/cost")) return tenantCost(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/cost/{month}")) return tenantCost(path.get("tenant"), path.get("month"), 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"), "default", 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 application(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}/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}/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}/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}/cost/{month}")) return tenantCost(path.get("tenant"), path.get("month"), request); | private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/user")) return authenticatedUser(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}/cost")) return tenantCost(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/cost/{month}")) return tenantCost(path.get("tenant"), path.get("month"), 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"), "default", 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 application(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}/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}/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}/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/user")) return createUser(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}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), 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"), "default", 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/{ignored}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), path.get("instance"), 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}/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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), "default");
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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), path.get("instance"));
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}/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, "user", "tenant");
}
private HttpResponse authenticatedUser(HttpRequest request) {
Principal user = requireUserPrincipal(request);
if (user == null)
throw new NotAuthorizedException("You must be authenticated.");
String userName = user instanceof AthenzPrincipal ? ((AthenzPrincipal) user).getIdentity().getName() : user.getName();
TenantName tenantName = TenantName.from(UserTenant.normalizeUser(userName));
List<Tenant> tenants = controller.tenants().asList(new Credentials(user));
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setString("user", userName);
Cursor tenantsArray = response.setArray("tenants");
for (Tenant tenant : tenants)
tenantInTenantsListToSlime(tenant, request.getUri(), tenantsArray.addObject());
response.setBool("tenantExists", tenants.stream().anyMatch(tenant -> tenant.name().equals(tenantName)));
return new SlimeJsonResponse(slime);
}
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 tenantCost(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenantCost(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenantCost(Tenant tenant, HttpRequest request) {
var slime = new Slime();
var objectCursor = slime.setObject();
var monthsCursor = objectCursor.setArray("months");
return new SlimeJsonResponse(slime);
}
private HttpResponse tenantCost(String tenantName, String dateString, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenantCost(tenant, tenantCostParseDate(dateString), request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private LocalDate tenantCostParseDate(String dateString) {
var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try {
return LocalDate.parse(dateString, formatter).withDayOfMonth(1);
} catch (DateTimeParseException e) {
throw new IllegalArgumentException("Could not parse date parameter: " + Exceptions.toMessageString(e));
}
}
private HttpResponse tenantCost(Tenant tenant, LocalDate month, HttpRequest request) {
var slime = new Slime();
slime.setObject();
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Slime slime = new Slime();
Cursor array = slime.setArray();
for (Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true))
for (InstanceName instance : application.instances().keySet())
toSlime(application.id().instance(instance), array.addObject(), request);
}
return new SlimeJsonResponse(slime);
}
private HttpResponse application(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
getApplication(tenantName, applicationName, instanceName), 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 Application getApplication(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
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()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.canonicalFlavor());
nodeObject.setDouble("vcpu", node.vcpu());
nodeObject.setDouble("memoryGb", node.memoryGb());
nodeObject.setDouble("diskGb", node.diskGb());
nodeObject.setDouble("bandwidthGbps", node.bandwidthGbps());
nodeObject.setBool("fastDisk", node.fastDisk());
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
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";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
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) {
String triggered = controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName())
.stream().map(JobType::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 void toSlime(Cursor object, Instance instance, Application application, HttpRequest request) {
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());
instance.deploymentJobs().statusOf(JobType.component)
.flatMap(JobStatus::lastSuccess)
.map(run -> run.application().source())
.ifPresent(source -> sourceRevisionToSlime(source, object.setObject("source")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if ( ! application.change().isEmpty()) {
toSlime(object.setObject("deploying"), application.change());
}
if ( ! application.outstandingChange().isEmpty()) {
toSlime(object.setObject("outstandingChange"), application.outstandingChange());
}
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedJobs(instance.deploymentJobs().jobStatus().values());
object.setBool("deployedInternally", application.internal());
Cursor deploymentsArray = object.setArray("deploymentJobs");
for (JobStatus job : jobStatus) {
Cursor jobObject = deploymentsArray.addObject();
jobObject.setString("type", job.type().jobName());
jobObject.setBool("success", job.isSuccess());
job.lastTriggered().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastTriggered")));
job.lastCompleted().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastCompleted")));
job.firstFailing().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("firstFailing")));
job.lastSuccess().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastSuccess")));
}
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().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);
});
object.setString("compileVersion", compileVersion(application.id()).toFullString());
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor globalRotationsArray = object.setArray("globalRotations");
instance.endpointsIn(controller.system())
.scope(Endpoint.Scope.global)
.legacy(false)
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
Set<RoutingPolicy> routingPolicies = controller.applications().routingPolicies().get(instance.id());
for (RoutingPolicy policy : routingPolicies) {
policy.rotationEndpointsIn(controller.system()).asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
}
List<Deployment> deployments = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedDeployments(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 (!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().getPath().contains("/instance/") ? "" : "/instance/" + instance.id().instance().value()),
request.getUri()).toString());
}
}
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(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 endpointArray = response.setArray("endpoints");
for (var policy : controller.applications().routingPolicies().get(deploymentId)) {
Cursor endpointObject = endpointArray.addObject();
Endpoint endpoint = policy.endpointIn(controller.system());
endpointObject.setString("cluster", policy.cluster().value());
endpointObject.setBool("tls", endpoint.tls());
endpointObject.setString("url", endpoint.url().toString());
}
Cursor serviceUrlArray = response.setArray("serviceUrls");
controller.applications().getDeploymentEndpoints(deploymentId)
.forEach(endpoint -> serviceUrlArray.addString(endpoint.toString()));
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()));
controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId())).projectId()
.ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
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));
DeploymentCost appCost = deployment.calculateCost();
Cursor costObject = response.setObject("cost");
toSlime(appCost, costObject);
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.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if ( ! revision.isPresent()) 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();
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
}
}
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);
return controller.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 -> ! controller.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);
}
Inspector requestData = toSlime(request.getData()).get();
String reason = mandatory("reason", requestData).asString();
String agent = requireUserPrincipal(request).getName();
long timestamp = controller.clock().instant().getEpochSecond();
EndpointStatus.Status status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
EndpointStatus endpointStatus = new EndpointStatus(status, reason, agent, timestamp);
controller.applications().setGlobalRotationStatus(new DeploymentId(instance.id(), deployment.zone()),
endpointStatus);
return new MessageResponse(String.format("Successfully set %s in %s.%s %s service",
instance.id().toShortString(),
deployment.zone().environment().value(),
deployment.zone().region().value(),
inService ? "in" : "out of"));
}
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");
Map<RoutingEndpoint, EndpointStatus> status = controller.applications().globalRotationStatus(deploymentId);
for (RoutingEndpoint endpoint : status.keySet()) {
EndpointStatus currentStatus = status.get(endpoint);
array.addString(endpoint.upstreamName());
Cursor statusObject = array.addObject();
statusObject.setString("status", currentStatus.getStatus().name());
statusObject.setString("reason", currentStatus.getReason() == null ? "" : currentStatus.getReason());
statusObject.setString("agent", currentStatus.getAgent() == null ? "" : currentStatus.getAgent());
statusObject.setLong("timestamp", currentStatus.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();
MeteringInfo meteringInfo = controller.serviceRegistry().meteringService().getResourceSnapshots(tenant, application);
ResourceAllocation currentSnapshot = meteringInfo.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringInfo.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringInfo.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 = meteringInfo.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 tenant, String application, String instance, HttpRequest request) {
Application app = controller.applications().requireApplication(TenantAndApplicationId.from(tenant, application));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! app.change().isEmpty()) {
app.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
app.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", app.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) {
Map<?,?> result = controller.getServiceApiResponse(tenantName, applicationName, instanceName, environment, region, serviceName, restPath);
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(result, serviceName, restPath);
return response;
}
private HttpResponse createUser(HttpRequest request) {
String user = Optional.of(requireUserPrincipal(request))
.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.map(AthenzIdentity::getName)
.map(UserTenant::normalizeUser)
.orElseThrow(() -> new ForbiddenException("Not authenticated or not a user."));
UserTenant tenant = UserTenant.create(user);
try {
controller.tenants().createUser(tenant);
return new MessageResponse("Created user '" + user + "'");
} catch (AlreadyExistsException e) {
return new MessageResponse("User '" + user + "' already exists");
}
}
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);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest()));
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());
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(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 " + change + " for " + 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);
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = Change.of(application.get().require(InstanceName.from(instanceName)).deploymentJobs().statusOf(JobType.component).get().lastSuccess().get().application());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered " + change + " for " + 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) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = application.get().change();
if (change.isEmpty()) {
response.append("No deployment in progress for " + application + " at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '" + change + "' to '" +
controller.applications().requireApplication(id).change() + "' for " + application);
});
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) {
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(),
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);
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<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,
application.get().internal(),
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,
application.get().internal(),
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
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.isPresent())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
if (tenant.get().type() == Tenant.Type.user)
controller.tenants().deleteUser((UserTenant) tenant.get());
else
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);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(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);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty())
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) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
DeploymentId deploymentId = new DeploymentId(instance.id(), ZoneId.from(environment, region));
controller.applications().deactivate(deploymentId.applicationId(), deploymentId.zoneId());
return new MessageResponse("Deactivated " + deploymentId);
}
private HttpResponse notifyJobCompletion(String tenant, String application, HttpRequest request) {
try {
DeploymentJobs.JobReport report = toJobReport(tenant, application, toSlime(request.getData()).get());
if ( report.jobType() == JobType.component
&& controller.applications().requireApplication(TenantAndApplicationId.from(report.applicationId())).internal())
throw new IllegalArgumentException(report.applicationId() + " is set up to be deployed from internally, and no " +
"longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.");
controller.applications().deploymentTrigger().notifyOfCompletion(report);
return new MessageResponse("ok");
} catch (IllegalStateException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
}
private HttpResponse testConfig(ApplicationId id, JobType type) {
Set<ZoneId> zones = controller.jobController().testedZoneAndProductionZones(id, type);
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
controller.applications().clusterEndpoints(id, zones),
controller.applications().contentClustersByZone(id, zones)));
}
private static DeploymentJobs.JobReport toJobReport(String tenantName, String applicationName, Inspector report) {
Optional<DeploymentJobs.JobError> jobError = Optional.empty();
if (report.field("jobError").valid()) {
jobError = Optional.of(DeploymentJobs.JobError.valueOf(report.field("jobError").asString()));
}
ApplicationId id = ApplicationId.from(tenantName, applicationName, report.field("instance").asString());
JobType type = JobType.fromJobName(report.field("jobName").asString());
long buildNumber = report.field("buildNumber").asLong();
if (type == JobType.component)
return DeploymentJobs.JobReport.ofComponent(id,
report.field("projectId").asLong(),
buildNumber,
jobError,
toSourceRevision(report.field("sourceRevision")));
else
return DeploymentJobs.JobReport.ofJob(id, type, buildNumber, jobError);
}
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<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 user: 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 (Application application : applications)
for (Instance instance : application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, application, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
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 user: 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(JobStatus.JobRun jobRun, Cursor object) {
object.setLong("id", jobRun.id());
object.setString("version", jobRun.platform().toFullString());
if (!jobRun.application().isUnknown())
toSlime(jobRun.application(), object.setObject("revision"));
object.setString("reason", jobRun.reason());
object.setLong("at", jobRun.at().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));
}
public static void toSlime(DeploymentCost deploymentCost, Cursor object) {
object.setLong("tco", (long)deploymentCost.getTco());
object.setLong("waste", (long)deploymentCost.getWaste());
object.setDouble("utilization", deploymentCost.getUtilization());
Cursor clustersObject = object.setObject("cluster");
for (Map.Entry<String, ClusterCost> clusterEntry : deploymentCost.getCluster().entrySet())
toSlime(clusterEntry.getValue(), clustersObject.setObject(clusterEntry.getKey()));
}
private static void toSlime(ClusterCost clusterCost, Cursor object) {
object.setLong("count", clusterCost.getClusterInfo().getHostnames().size());
object.setString("resource", getResourceName(clusterCost.getResultUtilization()));
object.setDouble("utilization", clusterCost.getResultUtilization().getMaxUtilization());
object.setLong("tco", (int)clusterCost.getTco());
object.setLong("waste", (int)clusterCost.getWaste());
object.setString("flavor", clusterCost.getClusterInfo().getFlavor());
object.setDouble("flavorCost", clusterCost.getClusterInfo().getFlavorCost());
object.setDouble("flavorCpu", clusterCost.getClusterInfo().getFlavorCPU());
object.setDouble("flavorMem", clusterCost.getClusterInfo().getFlavorMem());
object.setDouble("flavorDisk", clusterCost.getClusterInfo().getFlavorDisk());
object.setString("type", clusterCost.getClusterInfo().getClusterType().name());
Cursor utilObject = object.setObject("util");
utilObject.setDouble("cpu", clusterCost.getResultUtilization().getCpu());
utilObject.setDouble("mem", clusterCost.getResultUtilization().getMemory());
utilObject.setDouble("disk", clusterCost.getResultUtilization().getDisk());
utilObject.setDouble("diskBusy", clusterCost.getResultUtilization().getDiskBusy());
Cursor usageObject = object.setObject("usage");
usageObject.setDouble("cpu", clusterCost.getSystemUtilization().getCpu());
usageObject.setDouble("mem", clusterCost.getSystemUtilization().getMemory());
usageObject.setDouble("disk", clusterCost.getSystemUtilization().getDisk());
usageObject.setDouble("diskBusy", clusterCost.getSystemUtilization().getDiskBusy());
Cursor hostnamesArray = object.setArray("hostnames");
for (String hostname : clusterCost.getClusterInfo().getHostnames())
hostnamesArray.addString(hostname);
}
private static String getResourceName(ClusterUtilization utilization) {
String name = "cpu";
double max = utilization.getMaxUtilization();
if (utilization.getMemory() == max) {
name = "mem";
} else if (utilization.getDisk() == max) {
name = "disk";
} else if (utilization.getDiskBusy() == max) {
name = "diskbusy";
}
return name;
}
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 String tenantType(Tenant tenant) {
switch (tenant.type()) {
case user: return "USER";
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, String instance, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
SourceRevision sourceRevision = toSourceRevision(submitOptions);
String authorEmail = submitOptions.field("authorEmail").asString();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
if (DeploymentSpec.empty.equals(applicationPackage.deploymentSpec()))
throw new IllegalArgumentException("Missing required file 'deployment.xml'");
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
instance,
sourceRevision,
authorEmail,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
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";
}
} | 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/user")) return createUser(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}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), 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"), "default", 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/{ignored}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), path.get("instance"), 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}/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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), "default");
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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"), path.get("instance"));
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}/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, "user", "tenant");
}
private HttpResponse authenticatedUser(HttpRequest request) {
Principal user = requireUserPrincipal(request);
if (user == null)
throw new NotAuthorizedException("You must be authenticated.");
String userName = user instanceof AthenzPrincipal ? ((AthenzPrincipal) user).getIdentity().getName() : user.getName();
TenantName tenantName = TenantName.from(UserTenant.normalizeUser(userName));
List<Tenant> tenants = controller.tenants().asList(new Credentials(user));
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setString("user", userName);
Cursor tenantsArray = response.setArray("tenants");
for (Tenant tenant : tenants)
tenantInTenantsListToSlime(tenant, request.getUri(), tenantsArray.addObject());
response.setBool("tenantExists", tenants.stream().anyMatch(tenant -> tenant.name().equals(tenantName)));
return new SlimeJsonResponse(slime);
}
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 tenantCost(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenantCost(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenantCost(Tenant tenant, HttpRequest request) {
var slime = new Slime();
var objectCursor = slime.setObject();
var monthsCursor = objectCursor.setArray("months");
return new SlimeJsonResponse(slime);
}
private HttpResponse tenantCost(String tenantName, String dateString, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenantCost(tenant, tenantCostParseDate(dateString), request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private LocalDate tenantCostParseDate(String dateString) {
var monthPattern = Pattern.compile("^(?<year>[0-9]{4})-(?<month>[0-9]{2})$");
var matcher = monthPattern.matcher(dateString);
if (matcher.matches()) {
var year = Integer.parseInt(matcher.group("year"));
var month = Integer.parseInt(matcher.group("month"));
return LocalDate.of(year, month, 1);
} else {
throw new IllegalArgumentException("Could not parse year-month '" + dateString + "'");
}
}
private HttpResponse tenantCost(Tenant tenant, LocalDate month, HttpRequest request) {
var slime = new Slime();
slime.setObject();
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Slime slime = new Slime();
Cursor array = slime.setArray();
for (Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true))
for (InstanceName instance : application.instances().keySet())
toSlime(application.id().instance(instance), array.addObject(), request);
}
return new SlimeJsonResponse(slime);
}
private HttpResponse application(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
getApplication(tenantName, applicationName, instanceName), 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 Application getApplication(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
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()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.canonicalFlavor());
nodeObject.setDouble("vcpu", node.vcpu());
nodeObject.setDouble("memoryGb", node.memoryGb());
nodeObject.setDouble("diskGb", node.diskGb());
nodeObject.setDouble("bandwidthGbps", node.bandwidthGbps());
nodeObject.setBool("fastDisk", node.fastDisk());
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
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";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
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) {
String triggered = controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName())
.stream().map(JobType::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 void toSlime(Cursor object, Instance instance, Application application, HttpRequest request) {
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());
instance.deploymentJobs().statusOf(JobType.component)
.flatMap(JobStatus::lastSuccess)
.map(run -> run.application().source())
.ifPresent(source -> sourceRevisionToSlime(source, object.setObject("source")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if ( ! application.change().isEmpty()) {
toSlime(object.setObject("deploying"), application.change());
}
if ( ! application.outstandingChange().isEmpty()) {
toSlime(object.setObject("outstandingChange"), application.outstandingChange());
}
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedJobs(instance.deploymentJobs().jobStatus().values());
object.setBool("deployedInternally", application.internal());
Cursor deploymentsArray = object.setArray("deploymentJobs");
for (JobStatus job : jobStatus) {
Cursor jobObject = deploymentsArray.addObject();
jobObject.setString("type", job.type().jobName());
jobObject.setBool("success", job.isSuccess());
job.lastTriggered().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastTriggered")));
job.lastCompleted().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastCompleted")));
job.firstFailing().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("firstFailing")));
job.lastSuccess().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastSuccess")));
}
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().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);
});
object.setString("compileVersion", compileVersion(application.id()).toFullString());
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor globalRotationsArray = object.setArray("globalRotations");
instance.endpointsIn(controller.system())
.scope(Endpoint.Scope.global)
.legacy(false)
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
Set<RoutingPolicy> routingPolicies = controller.applications().routingPolicies().get(instance.id());
for (RoutingPolicy policy : routingPolicies) {
policy.rotationEndpointsIn(controller.system()).asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
}
List<Deployment> deployments = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedDeployments(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 (!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().getPath().contains("/instance/") ? "" : "/instance/" + instance.id().instance().value()),
request.getUri()).toString());
}
}
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(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 endpointArray = response.setArray("endpoints");
for (var policy : controller.applications().routingPolicies().get(deploymentId)) {
Cursor endpointObject = endpointArray.addObject();
Endpoint endpoint = policy.endpointIn(controller.system());
endpointObject.setString("cluster", policy.cluster().value());
endpointObject.setBool("tls", endpoint.tls());
endpointObject.setString("url", endpoint.url().toString());
}
Cursor serviceUrlArray = response.setArray("serviceUrls");
controller.applications().getDeploymentEndpoints(deploymentId)
.forEach(endpoint -> serviceUrlArray.addString(endpoint.toString()));
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()));
controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId())).projectId()
.ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
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));
DeploymentCost appCost = deployment.calculateCost();
Cursor costObject = response.setObject("cost");
toSlime(appCost, costObject);
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.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if ( ! revision.isPresent()) 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();
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
}
}
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);
return controller.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 -> ! controller.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);
}
Inspector requestData = toSlime(request.getData()).get();
String reason = mandatory("reason", requestData).asString();
String agent = requireUserPrincipal(request).getName();
long timestamp = controller.clock().instant().getEpochSecond();
EndpointStatus.Status status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
EndpointStatus endpointStatus = new EndpointStatus(status, reason, agent, timestamp);
controller.applications().setGlobalRotationStatus(new DeploymentId(instance.id(), deployment.zone()),
endpointStatus);
return new MessageResponse(String.format("Successfully set %s in %s.%s %s service",
instance.id().toShortString(),
deployment.zone().environment().value(),
deployment.zone().region().value(),
inService ? "in" : "out of"));
}
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");
Map<RoutingEndpoint, EndpointStatus> status = controller.applications().globalRotationStatus(deploymentId);
for (RoutingEndpoint endpoint : status.keySet()) {
EndpointStatus currentStatus = status.get(endpoint);
array.addString(endpoint.upstreamName());
Cursor statusObject = array.addObject();
statusObject.setString("status", currentStatus.getStatus().name());
statusObject.setString("reason", currentStatus.getReason() == null ? "" : currentStatus.getReason());
statusObject.setString("agent", currentStatus.getAgent() == null ? "" : currentStatus.getAgent());
statusObject.setLong("timestamp", currentStatus.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();
MeteringInfo meteringInfo = controller.serviceRegistry().meteringService().getResourceSnapshots(tenant, application);
ResourceAllocation currentSnapshot = meteringInfo.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringInfo.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringInfo.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 = meteringInfo.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 tenant, String application, String instance, HttpRequest request) {
Application app = controller.applications().requireApplication(TenantAndApplicationId.from(tenant, application));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! app.change().isEmpty()) {
app.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
app.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", app.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) {
Map<?,?> result = controller.getServiceApiResponse(tenantName, applicationName, instanceName, environment, region, serviceName, restPath);
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(result, serviceName, restPath);
return response;
}
private HttpResponse createUser(HttpRequest request) {
String user = Optional.of(requireUserPrincipal(request))
.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.map(AthenzIdentity::getName)
.map(UserTenant::normalizeUser)
.orElseThrow(() -> new ForbiddenException("Not authenticated or not a user."));
UserTenant tenant = UserTenant.create(user);
try {
controller.tenants().createUser(tenant);
return new MessageResponse("Created user '" + user + "'");
} catch (AlreadyExistsException e) {
return new MessageResponse("User '" + user + "' already exists");
}
}
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);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest()));
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());
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(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 " + change + " for " + 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);
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = Change.of(application.get().require(InstanceName.from(instanceName)).deploymentJobs().statusOf(JobType.component).get().lastSuccess().get().application());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered " + change + " for " + 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) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = application.get().change();
if (change.isEmpty()) {
response.append("No deployment in progress for " + application + " at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '" + change + "' to '" +
controller.applications().requireApplication(id).change() + "' for " + application);
});
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) {
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(),
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);
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<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,
application.get().internal(),
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,
application.get().internal(),
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
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.isPresent())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
if (tenant.get().type() == Tenant.Type.user)
controller.tenants().deleteUser((UserTenant) tenant.get());
else
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);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(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);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty())
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) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
DeploymentId deploymentId = new DeploymentId(instance.id(), ZoneId.from(environment, region));
controller.applications().deactivate(deploymentId.applicationId(), deploymentId.zoneId());
return new MessageResponse("Deactivated " + deploymentId);
}
private HttpResponse notifyJobCompletion(String tenant, String application, HttpRequest request) {
try {
DeploymentJobs.JobReport report = toJobReport(tenant, application, toSlime(request.getData()).get());
if ( report.jobType() == JobType.component
&& controller.applications().requireApplication(TenantAndApplicationId.from(report.applicationId())).internal())
throw new IllegalArgumentException(report.applicationId() + " is set up to be deployed from internally, and no " +
"longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.");
controller.applications().deploymentTrigger().notifyOfCompletion(report);
return new MessageResponse("ok");
} catch (IllegalStateException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
}
private HttpResponse testConfig(ApplicationId id, JobType type) {
Set<ZoneId> zones = controller.jobController().testedZoneAndProductionZones(id, type);
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
controller.applications().clusterEndpoints(id, zones),
controller.applications().contentClustersByZone(id, zones)));
}
private static DeploymentJobs.JobReport toJobReport(String tenantName, String applicationName, Inspector report) {
Optional<DeploymentJobs.JobError> jobError = Optional.empty();
if (report.field("jobError").valid()) {
jobError = Optional.of(DeploymentJobs.JobError.valueOf(report.field("jobError").asString()));
}
ApplicationId id = ApplicationId.from(tenantName, applicationName, report.field("instance").asString());
JobType type = JobType.fromJobName(report.field("jobName").asString());
long buildNumber = report.field("buildNumber").asLong();
if (type == JobType.component)
return DeploymentJobs.JobReport.ofComponent(id,
report.field("projectId").asLong(),
buildNumber,
jobError,
toSourceRevision(report.field("sourceRevision")));
else
return DeploymentJobs.JobReport.ofJob(id, type, buildNumber, jobError);
}
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<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 user: 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 (Application application : applications)
for (Instance instance : application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, application, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
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 user: 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(JobStatus.JobRun jobRun, Cursor object) {
object.setLong("id", jobRun.id());
object.setString("version", jobRun.platform().toFullString());
if (!jobRun.application().isUnknown())
toSlime(jobRun.application(), object.setObject("revision"));
object.setString("reason", jobRun.reason());
object.setLong("at", jobRun.at().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));
}
public static void toSlime(DeploymentCost deploymentCost, Cursor object) {
object.setLong("tco", (long)deploymentCost.getTco());
object.setLong("waste", (long)deploymentCost.getWaste());
object.setDouble("utilization", deploymentCost.getUtilization());
Cursor clustersObject = object.setObject("cluster");
for (Map.Entry<String, ClusterCost> clusterEntry : deploymentCost.getCluster().entrySet())
toSlime(clusterEntry.getValue(), clustersObject.setObject(clusterEntry.getKey()));
}
private static void toSlime(ClusterCost clusterCost, Cursor object) {
object.setLong("count", clusterCost.getClusterInfo().getHostnames().size());
object.setString("resource", getResourceName(clusterCost.getResultUtilization()));
object.setDouble("utilization", clusterCost.getResultUtilization().getMaxUtilization());
object.setLong("tco", (int)clusterCost.getTco());
object.setLong("waste", (int)clusterCost.getWaste());
object.setString("flavor", clusterCost.getClusterInfo().getFlavor());
object.setDouble("flavorCost", clusterCost.getClusterInfo().getFlavorCost());
object.setDouble("flavorCpu", clusterCost.getClusterInfo().getFlavorCPU());
object.setDouble("flavorMem", clusterCost.getClusterInfo().getFlavorMem());
object.setDouble("flavorDisk", clusterCost.getClusterInfo().getFlavorDisk());
object.setString("type", clusterCost.getClusterInfo().getClusterType().name());
Cursor utilObject = object.setObject("util");
utilObject.setDouble("cpu", clusterCost.getResultUtilization().getCpu());
utilObject.setDouble("mem", clusterCost.getResultUtilization().getMemory());
utilObject.setDouble("disk", clusterCost.getResultUtilization().getDisk());
utilObject.setDouble("diskBusy", clusterCost.getResultUtilization().getDiskBusy());
Cursor usageObject = object.setObject("usage");
usageObject.setDouble("cpu", clusterCost.getSystemUtilization().getCpu());
usageObject.setDouble("mem", clusterCost.getSystemUtilization().getMemory());
usageObject.setDouble("disk", clusterCost.getSystemUtilization().getDisk());
usageObject.setDouble("diskBusy", clusterCost.getSystemUtilization().getDiskBusy());
Cursor hostnamesArray = object.setArray("hostnames");
for (String hostname : clusterCost.getClusterInfo().getHostnames())
hostnamesArray.addString(hostname);
}
private static String getResourceName(ClusterUtilization utilization) {
String name = "cpu";
double max = utilization.getMaxUtilization();
if (utilization.getMemory() == max) {
name = "mem";
} else if (utilization.getDisk() == max) {
name = "disk";
} else if (utilization.getDiskBusy() == max) {
name = "diskbusy";
}
return name;
}
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 String tenantType(Tenant tenant) {
switch (tenant.type()) {
case user: return "USER";
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, String instance, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
SourceRevision sourceRevision = toSourceRevision(submitOptions);
String authorEmail = submitOptions.field("authorEmail").asString();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
if (DeploymentSpec.empty.equals(applicationPackage.deploymentSpec()))
throw new IllegalArgumentException("Missing required file 'deployment.xml'");
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
instance,
sourceRevision,
authorEmail,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
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";
}
} |
```suggestion // POST in a different pem developer key ``` | public void testUserManagement() {
ContainerTester tester = new ContainerTester(container, responseFiles);
assertEquals(SystemName.Public, tester.controller().system());
Set<Role> operator = Set.of(Role.hostedOperator());
ApplicationId id = ApplicationId.from("my-tenant", "my-app", "default");
tester.assertResponse(request("/application/v4/"),
accessDenied, 403);
tester.assertResponse(request("/application/v4/tenant")
.roles(operator),
"[]");
tester.assertResponse(request("/api/application/v4/tenant")
.roles(operator),
"[]");
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.data("{\"token\":\"hello\"}"),
accessDenied, 403);
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.roles(operator)
.user("administrator@tenant")
.data("{\"token\":\"hello\"}"),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/user/", PUT)
.roles(operator),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"Not authenticated or not a user.\"}", 403);
tester.assertResponse(request("/user/v1/"),
accessDenied, 403);
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
.roles(Set.of(Role.administrator(id.tenant())))
.data("{\"user\":\"evil@evil\",\"roleName\":\"hostedOperator\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'hostedOperator'.\"}", 400);
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
.roles(Set.of(Role.administrator(id.tenant())))
.data("{\"user\":\"developer@tenant\",\"roleName\":\"developer\"}"),
"{\"message\":\"user 'developer@tenant' is now a member of role 'developer' of 'my-tenant'\"}");
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"user\":\"developer@tenant\",\"roleName\":\"administrator\"}"),
accessDenied, 403);
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app", POST)
.roles(Set.of(Role.administrator(TenantName.from("my-tenant"))))
.data("{\"user\":\"headless@app\",\"roleName\":\"headless\"}"),
"{\"error-code\":\"INTERNAL_SERVER_ERROR\",\"message\":\"NullPointerException\"}", 500);
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app", POST)
.user("developer@tenant")
.roles(Set.of(Role.developer(id.tenant()))),
new File("application-created.json"));
tester.assertResponse(request("/application/v4/tenant/other-tenant/application/my-app", POST)
.roles(Set.of(Role.administrator(id.tenant()))),
accessDenied, 403);
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app", POST)
.roles(Set.of(Role.hostedOperator()))
.data("{\"user\":\"developer@app\",\"roleName\":\"developer\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'developer'.\"}", 400);
tester.assertResponse(request("/user/v1/tenant/my-tenant")
.roles(Set.of(Role.reader(id.tenant()))),
new File("tenant-roles.json"));
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app")
.roles(Set.of(Role.administrator(id.tenant()))),
new File("application-roles.json"));
tester.assertResponse(request("/api/user/v1/tenant/my-tenant/application/my-app")
.roles(Set.of(Role.administrator(id.tenant()))),
new File("application-roles.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app/key", POST)
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
new File("first-deploy-key.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
.user("joe@dev")
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
new File("first-developer-key.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
.user("operator@tenant")
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Key "+ quotedPemPublicKey + " is already owned by joe@dev\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
.user("developer@tenant")
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + otherPemPublicKey + "\"}"),
new File("both-developer-keys.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/")
.roles(Set.of(Role.reader(id.tenant()))),
new File("tenant-with-keys.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", DELETE)
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
new File("second-developer-key.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app", DELETE)
.roles(Set.of(Role.developer(id.tenant()))),
"{\"message\":\"Deleted application my-tenant.my-app\"}");
tester.assertResponse(request("/user/v1/tenant/my-tenant", DELETE)
.roles(Set.of(Role.administrator(id.tenant())))
.data("{\"user\":\"developer@tenant\",\"roleName\":\"developer\"}"),
"{\"message\":\"user 'developer@tenant' is no longer a member of role 'developer' of 'my-tenant'\"}");
tester.assertResponse(request("/user/v1/tenant/my-tenant", DELETE)
.roles(operator)
.data("{\"user\":\"administrator@tenant\",\"roleName\":\"administrator\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Can't remove the last administrator of a tenant.\"}", 400);
tester.assertResponse(request("/application/v4/tenant/my-tenant", DELETE)
.roles(Set.of(Role.tenantOwner(id.tenant()))),
new File("tenant-without-applications.json"));
} | public void testUserManagement() {
ContainerTester tester = new ContainerTester(container, responseFiles);
assertEquals(SystemName.Public, tester.controller().system());
Set<Role> operator = Set.of(Role.hostedOperator());
ApplicationId id = ApplicationId.from("my-tenant", "my-app", "default");
tester.assertResponse(request("/application/v4/"),
accessDenied, 403);
tester.assertResponse(request("/application/v4/tenant")
.roles(operator),
"[]");
tester.assertResponse(request("/api/application/v4/tenant")
.roles(operator),
"[]");
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.data("{\"token\":\"hello\"}"),
accessDenied, 403);
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.roles(operator)
.user("administrator@tenant")
.data("{\"token\":\"hello\"}"),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/user/", PUT)
.roles(operator),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"Not authenticated or not a user.\"}", 403);
tester.assertResponse(request("/user/v1/"),
accessDenied, 403);
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
.roles(Set.of(Role.administrator(id.tenant())))
.data("{\"user\":\"evil@evil\",\"roleName\":\"hostedOperator\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'hostedOperator'.\"}", 400);
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
.roles(Set.of(Role.administrator(id.tenant())))
.data("{\"user\":\"developer@tenant\",\"roleName\":\"developer\"}"),
"{\"message\":\"user 'developer@tenant' is now a member of role 'developer' of 'my-tenant'\"}");
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"user\":\"developer@tenant\",\"roleName\":\"administrator\"}"),
accessDenied, 403);
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app", POST)
.roles(Set.of(Role.administrator(TenantName.from("my-tenant"))))
.data("{\"user\":\"headless@app\",\"roleName\":\"headless\"}"),
"{\"error-code\":\"INTERNAL_SERVER_ERROR\",\"message\":\"NullPointerException\"}", 500);
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app", POST)
.user("developer@tenant")
.roles(Set.of(Role.developer(id.tenant()))),
new File("application-created.json"));
tester.assertResponse(request("/application/v4/tenant/other-tenant/application/my-app", POST)
.roles(Set.of(Role.administrator(id.tenant()))),
accessDenied, 403);
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app", POST)
.roles(Set.of(Role.hostedOperator()))
.data("{\"user\":\"developer@app\",\"roleName\":\"developer\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'developer'.\"}", 400);
tester.assertResponse(request("/user/v1/tenant/my-tenant")
.roles(Set.of(Role.reader(id.tenant()))),
new File("tenant-roles.json"));
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app")
.roles(Set.of(Role.administrator(id.tenant()))),
new File("application-roles.json"));
tester.assertResponse(request("/api/user/v1/tenant/my-tenant/application/my-app")
.roles(Set.of(Role.administrator(id.tenant()))),
new File("application-roles.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app/key", POST)
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
new File("first-deploy-key.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
.user("joe@dev")
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
new File("first-developer-key.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
.user("operator@tenant")
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Key "+ quotedPemPublicKey + " is already owned by joe@dev\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
.user("developer@tenant")
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + otherPemPublicKey + "\"}"),
new File("both-developer-keys.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/")
.roles(Set.of(Role.reader(id.tenant()))),
new File("tenant-with-keys.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", DELETE)
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
new File("second-developer-key.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app", DELETE)
.roles(Set.of(Role.developer(id.tenant()))),
"{\"message\":\"Deleted application my-tenant.my-app\"}");
tester.assertResponse(request("/user/v1/tenant/my-tenant", DELETE)
.roles(Set.of(Role.administrator(id.tenant())))
.data("{\"user\":\"developer@tenant\",\"roleName\":\"developer\"}"),
"{\"message\":\"user 'developer@tenant' is no longer a member of role 'developer' of 'my-tenant'\"}");
tester.assertResponse(request("/user/v1/tenant/my-tenant", DELETE)
.roles(operator)
.data("{\"user\":\"administrator@tenant\",\"roleName\":\"administrator\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Can't remove the last administrator of a tenant.\"}", 400);
tester.assertResponse(request("/application/v4/tenant/my-tenant", DELETE)
.roles(Set.of(Role.tenantOwner(id.tenant()))),
new File("tenant-without-applications.json"));
} | class UserApiTest extends ControllerContainerCloudTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String otherPemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFELzPyinTfQ/sZnTmRp5E4Ve/sbE\n" +
"pDhJeqczkyFcT2PysJ5sZwm7rKPEeXDOhzTPCyRvbUqc2SGdWbKUGGa/Yw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final String otherQuotedPemPublicKey = otherPemPublicKey.replaceAll("\\n", "\\\\n");
@Test
} | class UserApiTest extends ControllerContainerCloudTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String otherPemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFELzPyinTfQ/sZnTmRp5E4Ve/sbE\n" +
"pDhJeqczkyFcT2PysJ5sZwm7rKPEeXDOhzTPCyRvbUqc2SGdWbKUGGa/Yw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final String otherQuotedPemPublicKey = otherPemPublicKey.replaceAll("\\n", "\\\\n");
@Test
} | |
Any reason to not use `Files.createTempFile`? | private void writeBytes(byte[] content, boolean atomic) {
if (atomic) {
String tmpPath = path.toPath().toString() + ".FileSyncTmp";
new UnixPath(path.toPath().getFileSystem().getPath(tmpPath))
.writeBytes(content)
.atomicMove(path.toPath());
} else {
path.writeBytes(content);
}
} | String tmpPath = path.toPath().toString() + ".FileSyncTmp"; | private void writeBytes(byte[] content, boolean atomic) {
if (atomic) {
String tmpPath = path.toPath().toString() + ".FileSyncTmp";
new UnixPath(path.toPath().getFileSystem().getPath(tmpPath))
.writeBytes(content)
.atomicMove(path.toPath());
} else {
path.writeBytes(content);
}
} | class FileSync {
private static final Logger logger = Logger.getLogger(FileSync.class.getName());
private final UnixPath path;
private final FileContentCache contentCache;
public FileSync(Path path) {
this.path = new UnixPath(path);
this.contentCache = new FileContentCache(this.path);
}
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData) {
return convergeTo(taskContext, partialFileData, false);
}
/**
* CPU, I/O, and memory usage is optimized for repeated calls with the same arguments.
*
* @param atomicWrite Whether to write updates to a temporary file in the same directory, and atomically move it
* to path. Ensures the file cannot be read while in the middle of writing it.
* @return true if the system was modified: content was written, or owner was set, etc.
* system is only modified if necessary (different).
*/
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData, boolean atomicWrite) {
FileAttributesCache currentAttributes = new FileAttributesCache(path);
boolean modifiedSystem = maybeUpdateContent(taskContext, partialFileData.getContent(), currentAttributes, atomicWrite);
AttributeSync attributeSync = new AttributeSync(path.toPath()).with(partialFileData);
modifiedSystem |= attributeSync.converge(taskContext, currentAttributes);
return modifiedSystem;
}
private boolean maybeUpdateContent(TaskContext taskContext,
Optional<byte[]> content,
FileAttributesCache currentAttributes,
boolean atomicWrite) {
if (!content.isPresent()) {
return false;
}
if (!currentAttributes.exists()) {
taskContext.recordSystemModification(logger, "Creating file " + path);
path.createParents();
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
if (Arrays.equals(content.get(), contentCache.get(currentAttributes.get().lastModifiedTime()))) {
return false;
} else {
taskContext.recordSystemModification(logger, "Patching file " + path);
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
}
} | class FileSync {
private static final Logger logger = Logger.getLogger(FileSync.class.getName());
private final UnixPath path;
private final FileContentCache contentCache;
public FileSync(Path path) {
this.path = new UnixPath(path);
this.contentCache = new FileContentCache(this.path);
}
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData) {
return convergeTo(taskContext, partialFileData, false);
}
/**
* CPU, I/O, and memory usage is optimized for repeated calls with the same arguments.
*
* @param atomicWrite Whether to write updates to a temporary file in the same directory, and atomically move it
* to path. Ensures the file cannot be read while in the middle of writing it.
* @return true if the system was modified: content was written, or owner was set, etc.
* system is only modified if necessary (different).
*/
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData, boolean atomicWrite) {
FileAttributesCache currentAttributes = new FileAttributesCache(path);
boolean modifiedSystem = maybeUpdateContent(taskContext, partialFileData.getContent(), currentAttributes, atomicWrite);
AttributeSync attributeSync = new AttributeSync(path.toPath()).with(partialFileData);
modifiedSystem |= attributeSync.converge(taskContext, currentAttributes);
return modifiedSystem;
}
private boolean maybeUpdateContent(TaskContext taskContext,
Optional<byte[]> content,
FileAttributesCache currentAttributes,
boolean atomicWrite) {
if (!content.isPresent()) {
return false;
}
if (!currentAttributes.exists()) {
taskContext.recordSystemModification(logger, "Creating file " + path);
path.createParents();
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
if (Arrays.equals(content.get(), contentCache.get(currentAttributes.get().lastModifiedTime()))) {
return false;
} else {
taskContext.recordSystemModification(logger, "Patching file " + path);
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
}
} |
I specifically did not want to use it, in case there is an exception (or restart of host-admin) after createTempFile and before the move: It would leave stray files in the directory. | private void writeBytes(byte[] content, boolean atomic) {
if (atomic) {
String tmpPath = path.toPath().toString() + ".FileSyncTmp";
new UnixPath(path.toPath().getFileSystem().getPath(tmpPath))
.writeBytes(content)
.atomicMove(path.toPath());
} else {
path.writeBytes(content);
}
} | String tmpPath = path.toPath().toString() + ".FileSyncTmp"; | private void writeBytes(byte[] content, boolean atomic) {
if (atomic) {
String tmpPath = path.toPath().toString() + ".FileSyncTmp";
new UnixPath(path.toPath().getFileSystem().getPath(tmpPath))
.writeBytes(content)
.atomicMove(path.toPath());
} else {
path.writeBytes(content);
}
} | class FileSync {
private static final Logger logger = Logger.getLogger(FileSync.class.getName());
private final UnixPath path;
private final FileContentCache contentCache;
public FileSync(Path path) {
this.path = new UnixPath(path);
this.contentCache = new FileContentCache(this.path);
}
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData) {
return convergeTo(taskContext, partialFileData, false);
}
/**
* CPU, I/O, and memory usage is optimized for repeated calls with the same arguments.
*
* @param atomicWrite Whether to write updates to a temporary file in the same directory, and atomically move it
* to path. Ensures the file cannot be read while in the middle of writing it.
* @return true if the system was modified: content was written, or owner was set, etc.
* system is only modified if necessary (different).
*/
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData, boolean atomicWrite) {
FileAttributesCache currentAttributes = new FileAttributesCache(path);
boolean modifiedSystem = maybeUpdateContent(taskContext, partialFileData.getContent(), currentAttributes, atomicWrite);
AttributeSync attributeSync = new AttributeSync(path.toPath()).with(partialFileData);
modifiedSystem |= attributeSync.converge(taskContext, currentAttributes);
return modifiedSystem;
}
private boolean maybeUpdateContent(TaskContext taskContext,
Optional<byte[]> content,
FileAttributesCache currentAttributes,
boolean atomicWrite) {
if (!content.isPresent()) {
return false;
}
if (!currentAttributes.exists()) {
taskContext.recordSystemModification(logger, "Creating file " + path);
path.createParents();
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
if (Arrays.equals(content.get(), contentCache.get(currentAttributes.get().lastModifiedTime()))) {
return false;
} else {
taskContext.recordSystemModification(logger, "Patching file " + path);
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
}
} | class FileSync {
private static final Logger logger = Logger.getLogger(FileSync.class.getName());
private final UnixPath path;
private final FileContentCache contentCache;
public FileSync(Path path) {
this.path = new UnixPath(path);
this.contentCache = new FileContentCache(this.path);
}
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData) {
return convergeTo(taskContext, partialFileData, false);
}
/**
* CPU, I/O, and memory usage is optimized for repeated calls with the same arguments.
*
* @param atomicWrite Whether to write updates to a temporary file in the same directory, and atomically move it
* to path. Ensures the file cannot be read while in the middle of writing it.
* @return true if the system was modified: content was written, or owner was set, etc.
* system is only modified if necessary (different).
*/
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData, boolean atomicWrite) {
FileAttributesCache currentAttributes = new FileAttributesCache(path);
boolean modifiedSystem = maybeUpdateContent(taskContext, partialFileData.getContent(), currentAttributes, atomicWrite);
AttributeSync attributeSync = new AttributeSync(path.toPath()).with(partialFileData);
modifiedSystem |= attributeSync.converge(taskContext, currentAttributes);
return modifiedSystem;
}
private boolean maybeUpdateContent(TaskContext taskContext,
Optional<byte[]> content,
FileAttributesCache currentAttributes,
boolean atomicWrite) {
if (!content.isPresent()) {
return false;
}
if (!currentAttributes.exists()) {
taskContext.recordSystemModification(logger, "Creating file " + path);
path.createParents();
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
if (Arrays.equals(content.get(), contentCache.get(currentAttributes.get().lastModifiedTime()))) {
return false;
} else {
taskContext.recordSystemModification(logger, "Patching file " + path);
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
}
} |
More importantly, the temp file may be written on a different file system, moving across file systems is never atomic. | private void writeBytes(byte[] content, boolean atomic) {
if (atomic) {
String tmpPath = path.toPath().toString() + ".FileSyncTmp";
new UnixPath(path.toPath().getFileSystem().getPath(tmpPath))
.writeBytes(content)
.atomicMove(path.toPath());
} else {
path.writeBytes(content);
}
} | String tmpPath = path.toPath().toString() + ".FileSyncTmp"; | private void writeBytes(byte[] content, boolean atomic) {
if (atomic) {
String tmpPath = path.toPath().toString() + ".FileSyncTmp";
new UnixPath(path.toPath().getFileSystem().getPath(tmpPath))
.writeBytes(content)
.atomicMove(path.toPath());
} else {
path.writeBytes(content);
}
} | class FileSync {
private static final Logger logger = Logger.getLogger(FileSync.class.getName());
private final UnixPath path;
private final FileContentCache contentCache;
public FileSync(Path path) {
this.path = new UnixPath(path);
this.contentCache = new FileContentCache(this.path);
}
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData) {
return convergeTo(taskContext, partialFileData, false);
}
/**
* CPU, I/O, and memory usage is optimized for repeated calls with the same arguments.
*
* @param atomicWrite Whether to write updates to a temporary file in the same directory, and atomically move it
* to path. Ensures the file cannot be read while in the middle of writing it.
* @return true if the system was modified: content was written, or owner was set, etc.
* system is only modified if necessary (different).
*/
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData, boolean atomicWrite) {
FileAttributesCache currentAttributes = new FileAttributesCache(path);
boolean modifiedSystem = maybeUpdateContent(taskContext, partialFileData.getContent(), currentAttributes, atomicWrite);
AttributeSync attributeSync = new AttributeSync(path.toPath()).with(partialFileData);
modifiedSystem |= attributeSync.converge(taskContext, currentAttributes);
return modifiedSystem;
}
private boolean maybeUpdateContent(TaskContext taskContext,
Optional<byte[]> content,
FileAttributesCache currentAttributes,
boolean atomicWrite) {
if (!content.isPresent()) {
return false;
}
if (!currentAttributes.exists()) {
taskContext.recordSystemModification(logger, "Creating file " + path);
path.createParents();
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
if (Arrays.equals(content.get(), contentCache.get(currentAttributes.get().lastModifiedTime()))) {
return false;
} else {
taskContext.recordSystemModification(logger, "Patching file " + path);
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
}
} | class FileSync {
private static final Logger logger = Logger.getLogger(FileSync.class.getName());
private final UnixPath path;
private final FileContentCache contentCache;
public FileSync(Path path) {
this.path = new UnixPath(path);
this.contentCache = new FileContentCache(this.path);
}
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData) {
return convergeTo(taskContext, partialFileData, false);
}
/**
* CPU, I/O, and memory usage is optimized for repeated calls with the same arguments.
*
* @param atomicWrite Whether to write updates to a temporary file in the same directory, and atomically move it
* to path. Ensures the file cannot be read while in the middle of writing it.
* @return true if the system was modified: content was written, or owner was set, etc.
* system is only modified if necessary (different).
*/
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData, boolean atomicWrite) {
FileAttributesCache currentAttributes = new FileAttributesCache(path);
boolean modifiedSystem = maybeUpdateContent(taskContext, partialFileData.getContent(), currentAttributes, atomicWrite);
AttributeSync attributeSync = new AttributeSync(path.toPath()).with(partialFileData);
modifiedSystem |= attributeSync.converge(taskContext, currentAttributes);
return modifiedSystem;
}
private boolean maybeUpdateContent(TaskContext taskContext,
Optional<byte[]> content,
FileAttributesCache currentAttributes,
boolean atomicWrite) {
if (!content.isPresent()) {
return false;
}
if (!currentAttributes.exists()) {
taskContext.recordSystemModification(logger, "Creating file " + path);
path.createParents();
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
if (Arrays.equals(content.get(), contentCache.get(currentAttributes.get().lastModifiedTime()))) {
return false;
} else {
taskContext.recordSystemModification(logger, "Patching file " + path);
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
}
} |
It is possible to specify the directory. | private void writeBytes(byte[] content, boolean atomic) {
if (atomic) {
String tmpPath = path.toPath().toString() + ".FileSyncTmp";
new UnixPath(path.toPath().getFileSystem().getPath(tmpPath))
.writeBytes(content)
.atomicMove(path.toPath());
} else {
path.writeBytes(content);
}
} | String tmpPath = path.toPath().toString() + ".FileSyncTmp"; | private void writeBytes(byte[] content, boolean atomic) {
if (atomic) {
String tmpPath = path.toPath().toString() + ".FileSyncTmp";
new UnixPath(path.toPath().getFileSystem().getPath(tmpPath))
.writeBytes(content)
.atomicMove(path.toPath());
} else {
path.writeBytes(content);
}
} | class FileSync {
private static final Logger logger = Logger.getLogger(FileSync.class.getName());
private final UnixPath path;
private final FileContentCache contentCache;
public FileSync(Path path) {
this.path = new UnixPath(path);
this.contentCache = new FileContentCache(this.path);
}
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData) {
return convergeTo(taskContext, partialFileData, false);
}
/**
* CPU, I/O, and memory usage is optimized for repeated calls with the same arguments.
*
* @param atomicWrite Whether to write updates to a temporary file in the same directory, and atomically move it
* to path. Ensures the file cannot be read while in the middle of writing it.
* @return true if the system was modified: content was written, or owner was set, etc.
* system is only modified if necessary (different).
*/
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData, boolean atomicWrite) {
FileAttributesCache currentAttributes = new FileAttributesCache(path);
boolean modifiedSystem = maybeUpdateContent(taskContext, partialFileData.getContent(), currentAttributes, atomicWrite);
AttributeSync attributeSync = new AttributeSync(path.toPath()).with(partialFileData);
modifiedSystem |= attributeSync.converge(taskContext, currentAttributes);
return modifiedSystem;
}
private boolean maybeUpdateContent(TaskContext taskContext,
Optional<byte[]> content,
FileAttributesCache currentAttributes,
boolean atomicWrite) {
if (!content.isPresent()) {
return false;
}
if (!currentAttributes.exists()) {
taskContext.recordSystemModification(logger, "Creating file " + path);
path.createParents();
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
if (Arrays.equals(content.get(), contentCache.get(currentAttributes.get().lastModifiedTime()))) {
return false;
} else {
taskContext.recordSystemModification(logger, "Patching file " + path);
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
}
} | class FileSync {
private static final Logger logger = Logger.getLogger(FileSync.class.getName());
private final UnixPath path;
private final FileContentCache contentCache;
public FileSync(Path path) {
this.path = new UnixPath(path);
this.contentCache = new FileContentCache(this.path);
}
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData) {
return convergeTo(taskContext, partialFileData, false);
}
/**
* CPU, I/O, and memory usage is optimized for repeated calls with the same arguments.
*
* @param atomicWrite Whether to write updates to a temporary file in the same directory, and atomically move it
* to path. Ensures the file cannot be read while in the middle of writing it.
* @return true if the system was modified: content was written, or owner was set, etc.
* system is only modified if necessary (different).
*/
public boolean convergeTo(TaskContext taskContext, PartialFileData partialFileData, boolean atomicWrite) {
FileAttributesCache currentAttributes = new FileAttributesCache(path);
boolean modifiedSystem = maybeUpdateContent(taskContext, partialFileData.getContent(), currentAttributes, atomicWrite);
AttributeSync attributeSync = new AttributeSync(path.toPath()).with(partialFileData);
modifiedSystem |= attributeSync.converge(taskContext, currentAttributes);
return modifiedSystem;
}
private boolean maybeUpdateContent(TaskContext taskContext,
Optional<byte[]> content,
FileAttributesCache currentAttributes,
boolean atomicWrite) {
if (!content.isPresent()) {
return false;
}
if (!currentAttributes.exists()) {
taskContext.recordSystemModification(logger, "Creating file " + path);
path.createParents();
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
if (Arrays.equals(content.get(), contentCache.get(currentAttributes.get().lastModifiedTime()))) {
return false;
} else {
taskContext.recordSystemModification(logger, "Patching file " + path);
writeBytes(content.get(), atomicWrite);
contentCache.updateWith(content.get(), currentAttributes.forceGet().lastModifiedTime());
return true;
}
}
} |
Nit: Indentation. | private Optional<ApplicationVersion> latestVersionFromSlimeWithFallback(Inspector latestVersionObject, List<Instance> instances) {
if (latestVersionObject.valid())
return Optional.of(applicationVersionFromSlime(latestVersionObject));
return instances.stream()
.flatMap(instance -> instance.deploymentJobs().statusOf(JobType.component).stream())
.flatMap(status -> status.lastSuccess().stream())
.map(JobStatus.JobRun::application)
.findFirst();
} | .findFirst(); | private Optional<ApplicationVersion> latestVersionFromSlimeWithFallback(Inspector latestVersionObject, List<Instance> instances) {
if (latestVersionObject.valid())
return Optional.of(applicationVersionFromSlime(latestVersionObject));
return instances.stream()
.flatMap(instance -> instance.deploymentJobs().statusOf(JobType.component).stream())
.flatMap(status -> status.lastSuccess().stream())
.map(JobStatus.JobRun::application)
.findFirst();
} | class ApplicationSerializer {
private static final String idField = "id";
private static final String createdAtField = "createdAt";
private static final String deploymentSpecField = "deploymentSpecField";
private static final String validationOverridesField = "validationOverrides";
private static final String instancesField = "instances";
private static final String deployingField = "deployingField";
private static final String projectIdField = "projectId";
private static final String latestVersionField = "latestVersion";
private static final String builtInternallyField = "builtInternally";
private static final String pinnedField = "pinned";
private static final String outstandingChangeField = "outstandingChangeField";
private static final String deploymentIssueField = "deploymentIssueId";
private static final String ownershipIssueIdField = "ownershipIssueId";
private static final String ownerField = "confirmedOwner";
private static final String majorVersionField = "majorVersion";
private static final String writeQualityField = "writeQuality";
private static final String queryQualityField = "queryQuality";
private static final String pemDeployKeysField = "pemDeployKeys";
private static final String assignedRotationClusterField = "clusterId";
private static final String assignedRotationRotationField = "rotationId";
private static final String instanceNameField = "instanceName";
private static final String deploymentsField = "deployments";
private static final String deploymentJobsField = "deploymentJobs";
private static final String assignedRotationsField = "assignedRotations";
private static final String assignedRotationEndpointField = "endpointId";
private static final String zoneField = "zone";
private static final String environmentField = "environment";
private static final String regionField = "region";
private static final String deployTimeField = "deployTime";
private static final String applicationBuildNumberField = "applicationBuildNumber";
private static final String applicationPackageRevisionField = "applicationPackageRevision";
private static final String sourceRevisionField = "sourceRevision";
private static final String repositoryField = "repositoryField";
private static final String branchField = "branchField";
private static final String commitField = "commitField";
private static final String authorEmailField = "authorEmailField";
private static final String compileVersionField = "compileVersion";
private static final String buildTimeField = "buildTime";
private static final String lastQueriedField = "lastQueried";
private static final String lastWrittenField = "lastWritten";
private static final String lastQueriesPerSecondField = "lastQueriesPerSecond";
private static final String lastWritesPerSecondField = "lastWritesPerSecond";
private static final String jobStatusField = "jobStatus";
private static final String jobTypeField = "jobType";
private static final String errorField = "jobError";
private static final String lastTriggeredField = "lastTriggered";
private static final String lastCompletedField = "lastCompleted";
private static final String firstFailingField = "firstFailing";
private static final String lastSuccessField = "lastSuccess";
private static final String pausedUntilField = "pausedUntil";
private static final String jobRunIdField = "id";
private static final String versionField = "version";
private static final String revisionField = "revision";
private static final String sourceVersionField = "sourceVersion";
private static final String sourceApplicationField = "sourceRevision";
private static final String reasonField = "reason";
private static final String atField = "at";
private static final String clusterInfoField = "clusterInfo";
private static final String clusterInfoFlavorField = "flavor";
private static final String clusterInfoCostField = "cost";
private static final String clusterInfoCpuField = "flavorCpu";
private static final String clusterInfoMemField = "flavorMem";
private static final String clusterInfoDiskField = "flavorDisk";
private static final String clusterInfoTypeField = "clusterType";
private static final String clusterInfoHostnamesField = "hostnames";
private static final String deploymentMetricsField = "metrics";
private static final String deploymentMetricsQPSField = "queriesPerSecond";
private static final String deploymentMetricsWPSField = "writesPerSecond";
private static final String deploymentMetricsDocsField = "documentCount";
private static final String deploymentMetricsQueryLatencyField = "queryLatencyMillis";
private static final String deploymentMetricsWriteLatencyField = "writeLatencyMillis";
private static final String deploymentMetricsUpdateTime = "lastUpdated";
private static final String deploymentMetricsWarningsField = "warnings";
private static final String rotationStatusField = "rotationStatus2";
private static final String rotationIdField = "rotationId";
private static final String rotationStateField = "state";
private static final String statusField = "status";
public Slime toSlime(Application application) {
Slime slime = new Slime();
Cursor root = slime.setObject();
root.setString(idField, application.id().serialized());
root.setLong(createdAtField, application.createdAt().toEpochMilli());
root.setString(deploymentSpecField, application.deploymentSpec().xmlForm());
root.setString(validationOverridesField, application.validationOverrides().xmlForm());
application.projectId().ifPresent(projectId -> root.setLong(projectIdField, projectId));
application.deploymentIssueId().ifPresent(jiraIssueId -> root.setString(deploymentIssueField, jiraIssueId.value()));
application.ownershipIssueId().ifPresent(issueId -> root.setString(ownershipIssueIdField, issueId.value()));
root.setBool(builtInternallyField, application.internal());
toSlime(application.change(), root, deployingField);
toSlime(application.outstandingChange(), root, outstandingChangeField);
application.owner().ifPresent(owner -> root.setString(ownerField, owner.username()));
application.majorVersion().ifPresent(majorVersion -> root.setLong(majorVersionField, majorVersion));
root.setDouble(queryQualityField, application.metrics().queryServiceQuality());
root.setDouble(writeQualityField, application.metrics().writeServiceQuality());
deployKeysToSlime(application.deployKeys(), root.setArray(pemDeployKeysField));
application.latestVersion().ifPresent(version -> toSlime(version, root.setObject(latestVersionField)));
instancesToSlime(application, root.setArray(instancesField));
return slime;
}
private void instancesToSlime(Application application, Cursor array) {
for (Instance instance : application.instances().values()) {
Cursor instanceObject = array.addObject();
instanceObject.setString(instanceNameField, instance.name().value());
deploymentsToSlime(instance.deployments().values(), instanceObject.setArray(deploymentsField));
toSlime(instance.deploymentJobs(), instanceObject.setObject(deploymentJobsField));
assignedRotationsToSlime(instance.rotations(), instanceObject, assignedRotationsField);
toSlime(instance.rotationStatus(), instanceObject.setArray(rotationStatusField));
}
}
private void deployKeysToSlime(Set<PublicKey> deployKeys, Cursor array) {
deployKeys.forEach(key -> array.addString(KeyUtils.toPem(key)));
}
private void deploymentsToSlime(Collection<Deployment> deployments, Cursor array) {
for (Deployment deployment : deployments)
deploymentToSlime(deployment, array.addObject());
}
private void deploymentToSlime(Deployment deployment, Cursor object) {
zoneIdToSlime(deployment.zone(), object.setObject(zoneField));
object.setString(versionField, deployment.version().toString());
object.setLong(deployTimeField, deployment.at().toEpochMilli());
toSlime(deployment.applicationVersion(), object.setObject(applicationPackageRevisionField));
clusterInfoToSlime(deployment.clusterInfo(), object);
deploymentMetricsToSlime(deployment.metrics(), object);
deployment.activity().lastQueried().ifPresent(instant -> object.setLong(lastQueriedField, instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> object.setLong(lastWrittenField, instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> object.setDouble(lastQueriesPerSecondField, value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> object.setDouble(lastWritesPerSecondField, value));
}
private void deploymentMetricsToSlime(DeploymentMetrics metrics, Cursor object) {
Cursor root = object.setObject(deploymentMetricsField);
root.setDouble(deploymentMetricsQPSField, metrics.queriesPerSecond());
root.setDouble(deploymentMetricsWPSField, metrics.writesPerSecond());
root.setDouble(deploymentMetricsDocsField, metrics.documentCount());
root.setDouble(deploymentMetricsQueryLatencyField, metrics.queryLatencyMillis());
root.setDouble(deploymentMetricsWriteLatencyField, metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> root.setLong(deploymentMetricsUpdateTime, instant.toEpochMilli()));
if (!metrics.warnings().isEmpty()) {
Cursor warningsObject = root.setObject(deploymentMetricsWarningsField);
metrics.warnings().forEach((warning, count) -> warningsObject.setLong(warning.name(), count));
}
}
private void clusterInfoToSlime(Map<ClusterSpec.Id, ClusterInfo> clusters, Cursor object) {
Cursor root = object.setObject(clusterInfoField);
for (Map.Entry<ClusterSpec.Id, ClusterInfo> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterInfo info, Cursor object) {
object.setString(clusterInfoFlavorField, info.getFlavor());
object.setLong(clusterInfoCostField, info.getFlavorCost());
object.setDouble(clusterInfoCpuField, info.getFlavorCPU());
object.setDouble(clusterInfoMemField, info.getFlavorMem());
object.setDouble(clusterInfoDiskField, info.getFlavorDisk());
object.setString(clusterInfoTypeField, info.getClusterType().name());
Cursor array = object.setArray(clusterInfoHostnamesField);
for (String host : info.getHostnames()) {
array.addString(host);
}
}
private void zoneIdToSlime(ZoneId zone, Cursor object) {
object.setString(environmentField, zone.environment().value());
object.setString(regionField, zone.region().value());
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if (applicationVersion.buildNumber().isPresent() && applicationVersion.source().isPresent()) {
object.setLong(applicationBuildNumberField, applicationVersion.buildNumber().getAsLong());
toSlime(applicationVersion.source().get(), object.setObject(sourceRevisionField));
applicationVersion.authorEmail().ifPresent(email -> object.setString(authorEmailField, email));
applicationVersion.compileVersion().ifPresent(version -> object.setString(compileVersionField, version.toString()));
applicationVersion.buildTime().ifPresent(time -> object.setLong(buildTimeField, time.toEpochMilli()));
}
}
private void toSlime(SourceRevision sourceRevision, Cursor object) {
object.setString(repositoryField, sourceRevision.repository());
object.setString(branchField, sourceRevision.branch());
object.setString(commitField, sourceRevision.commit());
}
private void toSlime(DeploymentJobs deploymentJobs, Cursor cursor) {
jobStatusToSlime(deploymentJobs.jobStatus().values(), cursor.setArray(jobStatusField));
}
private void jobStatusToSlime(Collection<JobStatus> jobStatuses, Cursor jobStatusArray) {
for (JobStatus jobStatus : jobStatuses)
toSlime(jobStatus, jobStatusArray.addObject());
}
private void toSlime(JobStatus jobStatus, Cursor object) {
object.setString(jobTypeField, jobStatus.type().jobName());
if (jobStatus.jobError().isPresent())
object.setString(errorField, jobStatus.jobError().get().name());
jobStatus.lastTriggered().ifPresent(run -> jobRunToSlime(run, object, lastTriggeredField));
jobStatus.lastCompleted().ifPresent(run -> jobRunToSlime(run, object, lastCompletedField));
jobStatus.lastSuccess().ifPresent(run -> jobRunToSlime(run, object, lastSuccessField));
jobStatus.firstFailing().ifPresent(run -> jobRunToSlime(run, object, firstFailingField));
jobStatus.pausedUntil().ifPresent(until -> object.setLong(pausedUntilField, until));
}
private void jobRunToSlime(JobStatus.JobRun jobRun, Cursor parent, String jobRunObjectName) {
Cursor object = parent.setObject(jobRunObjectName);
object.setLong(jobRunIdField, jobRun.id());
object.setString(versionField, jobRun.platform().toString());
toSlime(jobRun.application(), object.setObject(revisionField));
jobRun.sourcePlatform().ifPresent(version -> object.setString(sourceVersionField, version.toString()));
jobRun.sourceApplication().ifPresent(version -> toSlime(version, object.setObject(sourceApplicationField)));
object.setString(reasonField, jobRun.reason());
object.setLong(atField, jobRun.at().toEpochMilli());
}
private void toSlime(Change deploying, Cursor parentObject, String fieldName) {
if (deploying.isEmpty()) return;
Cursor object = parentObject.setObject(fieldName);
if (deploying.platform().isPresent())
object.setString(versionField, deploying.platform().get().toString());
if (deploying.application().isPresent())
toSlime(deploying.application().get(), object);
if (deploying.isPinned())
object.setBool(pinnedField, true);
}
private void toSlime(RotationStatus status, Cursor array) {
status.asMap().forEach((rotationId, zoneStatus) -> {
Cursor rotationObject = array.addObject();
rotationObject.setString(rotationIdField, rotationId.asString());
Cursor statusArray = rotationObject.setArray(statusField);
zoneStatus.forEach((zone, state) -> {
Cursor statusObject = statusArray.addObject();
zoneIdToSlime(zone, statusObject);
statusObject.setString(rotationStateField, state.name());
});
});
}
private void assignedRotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) {
var rotationsArray = parent.setArray(fieldName);
for (var rotation : rotations) {
var object = rotationsArray.addObject();
object.setString(assignedRotationEndpointField, rotation.endpointId().id());
object.setString(assignedRotationRotationField, rotation.rotationId().asString());
object.setString(assignedRotationClusterField, rotation.clusterId().value());
}
}
public Application fromSlime(Slime slime) {
Inspector root = slime.get();
TenantAndApplicationId id = TenantAndApplicationId.fromSerialized(root.field(idField).asString());
Instant createdAt = Instant.ofEpochMilli(root.field(createdAtField).asLong());
DeploymentSpec deploymentSpec = DeploymentSpec.fromXml(root.field(deploymentSpecField).asString(), false);
ValidationOverrides validationOverrides = ValidationOverrides.fromXml(root.field(validationOverridesField).asString());
Change deploying = changeFromSlime(root.field(deployingField));
Change outstandingChange = changeFromSlime(root.field(outstandingChangeField));
Optional<IssueId> deploymentIssueId = Serializers.optionalString(root.field(deploymentIssueField)).map(IssueId::from);
Optional<IssueId> ownershipIssueId = Serializers.optionalString(root.field(ownershipIssueIdField)).map(IssueId::from);
Optional<User> owner = Serializers.optionalString(root.field(ownerField)).map(User::from);
OptionalInt majorVersion = Serializers.optionalInteger(root.field(majorVersionField));
ApplicationMetrics metrics = new ApplicationMetrics(root.field(queryQualityField).asDouble(),
root.field(writeQualityField).asDouble());
Set<PublicKey> deployKeys = deployKeysFromSlime(root.field(pemDeployKeysField));
List<Instance> instances = instancesFromSlime(id, deploymentSpec, root.field(instancesField));
OptionalLong projectId = Serializers.optionalLong(root.field(projectIdField));
Optional<ApplicationVersion> latestVersion = latestVersionFromSlimeWithFallback(root.field(latestVersionField), instances);
boolean builtInternally = root.field(builtInternallyField).asBool();
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
deployKeys, projectId, builtInternally, latestVersion, instances);
}
private List<Instance> instancesFromSlime(TenantAndApplicationId id, DeploymentSpec deploymentSpec, Inspector field) {
List<Instance> instances = new ArrayList<>();
field.traverse((ArrayTraverser) (name, object) -> {
InstanceName instanceName = InstanceName.from(object.field(instanceNameField).asString());
List<Deployment> deployments = deploymentsFromSlime(object.field(deploymentsField));
DeploymentJobs deploymentJobs = deploymentJobsFromSlime(object.field(deploymentJobsField));
List<AssignedRotation> assignedRotations = assignedRotationsFromSlime(deploymentSpec, object);
RotationStatus rotationStatus = rotationStatusFromSlime(object);
instances.add(new Instance(id.instance(instanceName),
deployments,
deploymentJobs,
assignedRotations,
rotationStatus));
});
return instances;
}
private Set<PublicKey> deployKeysFromSlime(Inspector array) {
Set<PublicKey> keys = new LinkedHashSet<>();
array.traverse((ArrayTraverser) (__, key) -> keys.add(KeyUtils.fromPemEncodedPublicKey(key.asString())));
return keys;
}
private List<Deployment> deploymentsFromSlime(Inspector array) {
List<Deployment> deployments = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> deployments.add(deploymentFromSlime(item)));
return deployments;
}
private Deployment deploymentFromSlime(Inspector deploymentObject) {
return new Deployment(zoneIdFromSlime(deploymentObject.field(zoneField)),
applicationVersionFromSlime(deploymentObject.field(applicationPackageRevisionField)),
Version.fromString(deploymentObject.field(versionField).asString()),
Instant.ofEpochMilli(deploymentObject.field(deployTimeField).asLong()),
clusterInfoMapFromSlime(deploymentObject.field(clusterInfoField)),
deploymentMetricsFromSlime(deploymentObject.field(deploymentMetricsField)),
DeploymentActivity.create(Serializers.optionalInstant(deploymentObject.field(lastQueriedField)),
Serializers.optionalInstant(deploymentObject.field(lastWrittenField)),
Serializers.optionalDouble(deploymentObject.field(lastQueriesPerSecondField)),
Serializers.optionalDouble(deploymentObject.field(lastWritesPerSecondField))));
}
private DeploymentMetrics deploymentMetricsFromSlime(Inspector object) {
Optional<Instant> instant = object.field(deploymentMetricsUpdateTime).valid() ?
Optional.of(Instant.ofEpochMilli(object.field(deploymentMetricsUpdateTime).asLong())) :
Optional.empty();
return new DeploymentMetrics(object.field(deploymentMetricsQPSField).asDouble(),
object.field(deploymentMetricsWPSField).asDouble(),
object.field(deploymentMetricsDocsField).asDouble(),
object.field(deploymentMetricsQueryLatencyField).asDouble(),
object.field(deploymentMetricsWriteLatencyField).asDouble(),
instant,
deploymentWarningsFrom(object.field(deploymentMetricsWarningsField)));
}
private Map<DeploymentMetrics.Warning, Integer> deploymentWarningsFrom(Inspector object) {
Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>();
object.traverse((ObjectTraverser) (name, value) -> warnings.put(DeploymentMetrics.Warning.valueOf(name),
(int) value.asLong()));
return Collections.unmodifiableMap(warnings);
}
private RotationStatus rotationStatusFromSlime(Inspector parentObject) {
var object = parentObject.field(rotationStatusField);
var statusMap = new LinkedHashMap<RotationId, Map<ZoneId, RotationState>>();
object.traverse((ArrayTraverser) (idx, statusObject) -> statusMap.put(new RotationId(statusObject.field(rotationIdField).asString()),
singleRotationStatusFromSlime(statusObject.field(statusField))));
return RotationStatus.from(statusMap);
}
private Map<ZoneId, RotationState> singleRotationStatusFromSlime(Inspector object) {
if (!object.valid()) {
return Collections.emptyMap();
}
Map<ZoneId, RotationState> rotationStatus = new LinkedHashMap<>();
object.traverse((ArrayTraverser) (idx, statusObject) -> {
var zone = zoneIdFromSlime(statusObject);
var status = RotationState.valueOf(statusObject.field(rotationStateField).asString());
rotationStatus.put(zone, status);
});
return Collections.unmodifiableMap(rotationStatus);
}
private Map<ClusterSpec.Id, ClusterInfo> clusterInfoMapFromSlime (Inspector object) {
Map<ClusterSpec.Id, ClusterInfo> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterInfoFromSlime(value)));
return map;
}
private ClusterInfo clusterInfoFromSlime(Inspector inspector) {
String flavor = inspector.field(clusterInfoFlavorField).asString();
int cost = (int)inspector.field(clusterInfoCostField).asLong();
String type = inspector.field(clusterInfoTypeField).asString();
double flavorCpu = inspector.field(clusterInfoCpuField).asDouble();
double flavorMem = inspector.field(clusterInfoMemField).asDouble();
double flavorDisk = inspector.field(clusterInfoDiskField).asDouble();
List<String> hostnames = new ArrayList<>();
inspector.field(clusterInfoHostnamesField).traverse((ArrayTraverser)(int index, Inspector value) -> hostnames.add(value.asString()));
return new ClusterInfo(flavor, cost, flavorCpu, flavorMem, flavorDisk, ClusterSpec.Type.from(type), hostnames);
}
private ZoneId zoneIdFromSlime(Inspector object) {
return ZoneId.from(object.field(environmentField).asString(), object.field(regionField).asString());
}
private ApplicationVersion applicationVersionFromSlime(Inspector object) {
if ( ! object.valid()) return ApplicationVersion.unknown;
OptionalLong applicationBuildNumber = Serializers.optionalLong(object.field(applicationBuildNumberField));
Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField));
if (sourceRevision.isEmpty() || applicationBuildNumber.isEmpty()) {
return ApplicationVersion.unknown;
}
Optional<String> authorEmail = Serializers.optionalString(object.field(authorEmailField));
Optional<Version> compileVersion = Serializers.optionalString(object.field(compileVersionField)).map(Version::fromString);
Optional<Instant> buildTime = Serializers.optionalInstant(object.field(buildTimeField));
if (authorEmail.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong());
if (compileVersion.isEmpty() || buildTime.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get());
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get(),
compileVersion.get(), buildTime.get());
}
private Optional<SourceRevision> sourceRevisionFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new SourceRevision(object.field(repositoryField).asString(),
object.field(branchField).asString(),
object.field(commitField).asString()));
}
private DeploymentJobs deploymentJobsFromSlime(Inspector object) {
List<JobStatus> jobStatusList = jobStatusListFromSlime(object.field(jobStatusField));
return new DeploymentJobs(jobStatusList);
}
private Change changeFromSlime(Inspector object) {
if ( ! object.valid()) return Change.empty();
Inspector versionFieldValue = object.field(versionField);
Change change = Change.empty();
if (versionFieldValue.valid())
change = Change.of(Version.fromString(versionFieldValue.asString()));
if (object.field(applicationBuildNumberField).valid())
change = change.with(applicationVersionFromSlime(object));
if (object.field(pinnedField).asBool())
change = change.withPin();
return change;
}
private List<JobStatus> jobStatusListFromSlime(Inspector array) {
List<JobStatus> jobStatusList = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> jobStatusFromSlime(item).ifPresent(jobStatusList::add));
return jobStatusList;
}
private Optional<JobStatus> jobStatusFromSlime(Inspector object) {
Optional<JobType> jobType =
JobType.fromOptionalJobName(object.field(jobTypeField).asString());
if (jobType.isEmpty()) return Optional.empty();
Optional<JobError> jobError = Optional.empty();
if (object.field(errorField).valid())
jobError = Optional.of(JobError.valueOf(object.field(errorField).asString()));
return Optional.of(new JobStatus(jobType.get(),
jobError,
jobRunFromSlime(object.field(lastTriggeredField)),
jobRunFromSlime(object.field(lastCompletedField)),
jobRunFromSlime(object.field(firstFailingField)),
jobRunFromSlime(object.field(lastSuccessField)),
Serializers.optionalLong(object.field(pausedUntilField))));
}
private Optional<JobStatus.JobRun> jobRunFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new JobStatus.JobRun(object.field(jobRunIdField).asLong(),
new Version(object.field(versionField).asString()),
applicationVersionFromSlime(object.field(revisionField)),
Serializers.optionalString(object.field(sourceVersionField)).map(Version::fromString),
Optional.of(object.field(sourceApplicationField)).filter(Inspector::valid).map(this::applicationVersionFromSlime),
object.field(reasonField).asString(),
Instant.ofEpochMilli(object.field(atField).asLong())));
}
private List<AssignedRotation> assignedRotationsFromSlime(DeploymentSpec deploymentSpec, Inspector root) {
var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>();
root.field(assignedRotationsField).traverse((ArrayTraverser) (idx, inspector) -> {
var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString());
var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString());
var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString());
var regions = deploymentSpec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
} | class ApplicationSerializer {
private static final String idField = "id";
private static final String createdAtField = "createdAt";
private static final String deploymentSpecField = "deploymentSpecField";
private static final String validationOverridesField = "validationOverrides";
private static final String instancesField = "instances";
private static final String deployingField = "deployingField";
private static final String projectIdField = "projectId";
private static final String latestVersionField = "latestVersion";
private static final String builtInternallyField = "builtInternally";
private static final String pinnedField = "pinned";
private static final String outstandingChangeField = "outstandingChangeField";
private static final String deploymentIssueField = "deploymentIssueId";
private static final String ownershipIssueIdField = "ownershipIssueId";
private static final String ownerField = "confirmedOwner";
private static final String majorVersionField = "majorVersion";
private static final String writeQualityField = "writeQuality";
private static final String queryQualityField = "queryQuality";
private static final String pemDeployKeysField = "pemDeployKeys";
private static final String assignedRotationClusterField = "clusterId";
private static final String assignedRotationRotationField = "rotationId";
private static final String instanceNameField = "instanceName";
private static final String deploymentsField = "deployments";
private static final String deploymentJobsField = "deploymentJobs";
private static final String assignedRotationsField = "assignedRotations";
private static final String assignedRotationEndpointField = "endpointId";
private static final String zoneField = "zone";
private static final String environmentField = "environment";
private static final String regionField = "region";
private static final String deployTimeField = "deployTime";
private static final String applicationBuildNumberField = "applicationBuildNumber";
private static final String applicationPackageRevisionField = "applicationPackageRevision";
private static final String sourceRevisionField = "sourceRevision";
private static final String repositoryField = "repositoryField";
private static final String branchField = "branchField";
private static final String commitField = "commitField";
private static final String authorEmailField = "authorEmailField";
private static final String compileVersionField = "compileVersion";
private static final String buildTimeField = "buildTime";
private static final String lastQueriedField = "lastQueried";
private static final String lastWrittenField = "lastWritten";
private static final String lastQueriesPerSecondField = "lastQueriesPerSecond";
private static final String lastWritesPerSecondField = "lastWritesPerSecond";
private static final String jobStatusField = "jobStatus";
private static final String jobTypeField = "jobType";
private static final String errorField = "jobError";
private static final String lastTriggeredField = "lastTriggered";
private static final String lastCompletedField = "lastCompleted";
private static final String firstFailingField = "firstFailing";
private static final String lastSuccessField = "lastSuccess";
private static final String pausedUntilField = "pausedUntil";
private static final String jobRunIdField = "id";
private static final String versionField = "version";
private static final String revisionField = "revision";
private static final String sourceVersionField = "sourceVersion";
private static final String sourceApplicationField = "sourceRevision";
private static final String reasonField = "reason";
private static final String atField = "at";
private static final String clusterInfoField = "clusterInfo";
private static final String clusterInfoFlavorField = "flavor";
private static final String clusterInfoCostField = "cost";
private static final String clusterInfoCpuField = "flavorCpu";
private static final String clusterInfoMemField = "flavorMem";
private static final String clusterInfoDiskField = "flavorDisk";
private static final String clusterInfoTypeField = "clusterType";
private static final String clusterInfoHostnamesField = "hostnames";
private static final String deploymentMetricsField = "metrics";
private static final String deploymentMetricsQPSField = "queriesPerSecond";
private static final String deploymentMetricsWPSField = "writesPerSecond";
private static final String deploymentMetricsDocsField = "documentCount";
private static final String deploymentMetricsQueryLatencyField = "queryLatencyMillis";
private static final String deploymentMetricsWriteLatencyField = "writeLatencyMillis";
private static final String deploymentMetricsUpdateTime = "lastUpdated";
private static final String deploymentMetricsWarningsField = "warnings";
private static final String rotationStatusField = "rotationStatus2";
private static final String rotationIdField = "rotationId";
private static final String rotationStateField = "state";
private static final String statusField = "status";
public Slime toSlime(Application application) {
Slime slime = new Slime();
Cursor root = slime.setObject();
root.setString(idField, application.id().serialized());
root.setLong(createdAtField, application.createdAt().toEpochMilli());
root.setString(deploymentSpecField, application.deploymentSpec().xmlForm());
root.setString(validationOverridesField, application.validationOverrides().xmlForm());
application.projectId().ifPresent(projectId -> root.setLong(projectIdField, projectId));
application.deploymentIssueId().ifPresent(jiraIssueId -> root.setString(deploymentIssueField, jiraIssueId.value()));
application.ownershipIssueId().ifPresent(issueId -> root.setString(ownershipIssueIdField, issueId.value()));
root.setBool(builtInternallyField, application.internal());
toSlime(application.change(), root, deployingField);
toSlime(application.outstandingChange(), root, outstandingChangeField);
application.owner().ifPresent(owner -> root.setString(ownerField, owner.username()));
application.majorVersion().ifPresent(majorVersion -> root.setLong(majorVersionField, majorVersion));
root.setDouble(queryQualityField, application.metrics().queryServiceQuality());
root.setDouble(writeQualityField, application.metrics().writeServiceQuality());
deployKeysToSlime(application.deployKeys(), root.setArray(pemDeployKeysField));
application.latestVersion().ifPresent(version -> toSlime(version, root.setObject(latestVersionField)));
instancesToSlime(application, root.setArray(instancesField));
return slime;
}
private void instancesToSlime(Application application, Cursor array) {
for (Instance instance : application.instances().values()) {
Cursor instanceObject = array.addObject();
instanceObject.setString(instanceNameField, instance.name().value());
deploymentsToSlime(instance.deployments().values(), instanceObject.setArray(deploymentsField));
toSlime(instance.deploymentJobs(), instanceObject.setObject(deploymentJobsField));
assignedRotationsToSlime(instance.rotations(), instanceObject, assignedRotationsField);
toSlime(instance.rotationStatus(), instanceObject.setArray(rotationStatusField));
}
}
private void deployKeysToSlime(Set<PublicKey> deployKeys, Cursor array) {
deployKeys.forEach(key -> array.addString(KeyUtils.toPem(key)));
}
private void deploymentsToSlime(Collection<Deployment> deployments, Cursor array) {
for (Deployment deployment : deployments)
deploymentToSlime(deployment, array.addObject());
}
private void deploymentToSlime(Deployment deployment, Cursor object) {
zoneIdToSlime(deployment.zone(), object.setObject(zoneField));
object.setString(versionField, deployment.version().toString());
object.setLong(deployTimeField, deployment.at().toEpochMilli());
toSlime(deployment.applicationVersion(), object.setObject(applicationPackageRevisionField));
clusterInfoToSlime(deployment.clusterInfo(), object);
deploymentMetricsToSlime(deployment.metrics(), object);
deployment.activity().lastQueried().ifPresent(instant -> object.setLong(lastQueriedField, instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> object.setLong(lastWrittenField, instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> object.setDouble(lastQueriesPerSecondField, value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> object.setDouble(lastWritesPerSecondField, value));
}
private void deploymentMetricsToSlime(DeploymentMetrics metrics, Cursor object) {
Cursor root = object.setObject(deploymentMetricsField);
root.setDouble(deploymentMetricsQPSField, metrics.queriesPerSecond());
root.setDouble(deploymentMetricsWPSField, metrics.writesPerSecond());
root.setDouble(deploymentMetricsDocsField, metrics.documentCount());
root.setDouble(deploymentMetricsQueryLatencyField, metrics.queryLatencyMillis());
root.setDouble(deploymentMetricsWriteLatencyField, metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> root.setLong(deploymentMetricsUpdateTime, instant.toEpochMilli()));
if (!metrics.warnings().isEmpty()) {
Cursor warningsObject = root.setObject(deploymentMetricsWarningsField);
metrics.warnings().forEach((warning, count) -> warningsObject.setLong(warning.name(), count));
}
}
private void clusterInfoToSlime(Map<ClusterSpec.Id, ClusterInfo> clusters, Cursor object) {
Cursor root = object.setObject(clusterInfoField);
for (Map.Entry<ClusterSpec.Id, ClusterInfo> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterInfo info, Cursor object) {
object.setString(clusterInfoFlavorField, info.getFlavor());
object.setLong(clusterInfoCostField, info.getFlavorCost());
object.setDouble(clusterInfoCpuField, info.getFlavorCPU());
object.setDouble(clusterInfoMemField, info.getFlavorMem());
object.setDouble(clusterInfoDiskField, info.getFlavorDisk());
object.setString(clusterInfoTypeField, info.getClusterType().name());
Cursor array = object.setArray(clusterInfoHostnamesField);
for (String host : info.getHostnames()) {
array.addString(host);
}
}
private void zoneIdToSlime(ZoneId zone, Cursor object) {
object.setString(environmentField, zone.environment().value());
object.setString(regionField, zone.region().value());
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if (applicationVersion.buildNumber().isPresent() && applicationVersion.source().isPresent()) {
object.setLong(applicationBuildNumberField, applicationVersion.buildNumber().getAsLong());
toSlime(applicationVersion.source().get(), object.setObject(sourceRevisionField));
applicationVersion.authorEmail().ifPresent(email -> object.setString(authorEmailField, email));
applicationVersion.compileVersion().ifPresent(version -> object.setString(compileVersionField, version.toString()));
applicationVersion.buildTime().ifPresent(time -> object.setLong(buildTimeField, time.toEpochMilli()));
}
}
private void toSlime(SourceRevision sourceRevision, Cursor object) {
object.setString(repositoryField, sourceRevision.repository());
object.setString(branchField, sourceRevision.branch());
object.setString(commitField, sourceRevision.commit());
}
private void toSlime(DeploymentJobs deploymentJobs, Cursor cursor) {
jobStatusToSlime(deploymentJobs.jobStatus().values(), cursor.setArray(jobStatusField));
}
private void jobStatusToSlime(Collection<JobStatus> jobStatuses, Cursor jobStatusArray) {
for (JobStatus jobStatus : jobStatuses)
toSlime(jobStatus, jobStatusArray.addObject());
}
private void toSlime(JobStatus jobStatus, Cursor object) {
object.setString(jobTypeField, jobStatus.type().jobName());
if (jobStatus.jobError().isPresent())
object.setString(errorField, jobStatus.jobError().get().name());
jobStatus.lastTriggered().ifPresent(run -> jobRunToSlime(run, object, lastTriggeredField));
jobStatus.lastCompleted().ifPresent(run -> jobRunToSlime(run, object, lastCompletedField));
jobStatus.lastSuccess().ifPresent(run -> jobRunToSlime(run, object, lastSuccessField));
jobStatus.firstFailing().ifPresent(run -> jobRunToSlime(run, object, firstFailingField));
jobStatus.pausedUntil().ifPresent(until -> object.setLong(pausedUntilField, until));
}
private void jobRunToSlime(JobStatus.JobRun jobRun, Cursor parent, String jobRunObjectName) {
Cursor object = parent.setObject(jobRunObjectName);
object.setLong(jobRunIdField, jobRun.id());
object.setString(versionField, jobRun.platform().toString());
toSlime(jobRun.application(), object.setObject(revisionField));
jobRun.sourcePlatform().ifPresent(version -> object.setString(sourceVersionField, version.toString()));
jobRun.sourceApplication().ifPresent(version -> toSlime(version, object.setObject(sourceApplicationField)));
object.setString(reasonField, jobRun.reason());
object.setLong(atField, jobRun.at().toEpochMilli());
}
private void toSlime(Change deploying, Cursor parentObject, String fieldName) {
if (deploying.isEmpty()) return;
Cursor object = parentObject.setObject(fieldName);
if (deploying.platform().isPresent())
object.setString(versionField, deploying.platform().get().toString());
if (deploying.application().isPresent())
toSlime(deploying.application().get(), object);
if (deploying.isPinned())
object.setBool(pinnedField, true);
}
private void toSlime(RotationStatus status, Cursor array) {
status.asMap().forEach((rotationId, zoneStatus) -> {
Cursor rotationObject = array.addObject();
rotationObject.setString(rotationIdField, rotationId.asString());
Cursor statusArray = rotationObject.setArray(statusField);
zoneStatus.forEach((zone, state) -> {
Cursor statusObject = statusArray.addObject();
zoneIdToSlime(zone, statusObject);
statusObject.setString(rotationStateField, state.name());
});
});
}
private void assignedRotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) {
var rotationsArray = parent.setArray(fieldName);
for (var rotation : rotations) {
var object = rotationsArray.addObject();
object.setString(assignedRotationEndpointField, rotation.endpointId().id());
object.setString(assignedRotationRotationField, rotation.rotationId().asString());
object.setString(assignedRotationClusterField, rotation.clusterId().value());
}
}
public Application fromSlime(Slime slime) {
Inspector root = slime.get();
TenantAndApplicationId id = TenantAndApplicationId.fromSerialized(root.field(idField).asString());
Instant createdAt = Instant.ofEpochMilli(root.field(createdAtField).asLong());
DeploymentSpec deploymentSpec = DeploymentSpec.fromXml(root.field(deploymentSpecField).asString(), false);
ValidationOverrides validationOverrides = ValidationOverrides.fromXml(root.field(validationOverridesField).asString());
Change deploying = changeFromSlime(root.field(deployingField));
Change outstandingChange = changeFromSlime(root.field(outstandingChangeField));
Optional<IssueId> deploymentIssueId = Serializers.optionalString(root.field(deploymentIssueField)).map(IssueId::from);
Optional<IssueId> ownershipIssueId = Serializers.optionalString(root.field(ownershipIssueIdField)).map(IssueId::from);
Optional<User> owner = Serializers.optionalString(root.field(ownerField)).map(User::from);
OptionalInt majorVersion = Serializers.optionalInteger(root.field(majorVersionField));
ApplicationMetrics metrics = new ApplicationMetrics(root.field(queryQualityField).asDouble(),
root.field(writeQualityField).asDouble());
Set<PublicKey> deployKeys = deployKeysFromSlime(root.field(pemDeployKeysField));
List<Instance> instances = instancesFromSlime(id, deploymentSpec, root.field(instancesField));
OptionalLong projectId = Serializers.optionalLong(root.field(projectIdField));
Optional<ApplicationVersion> latestVersion = latestVersionFromSlimeWithFallback(root.field(latestVersionField), instances);
boolean builtInternally = root.field(builtInternallyField).asBool();
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
deployKeys, projectId, builtInternally, latestVersion, instances);
}
private List<Instance> instancesFromSlime(TenantAndApplicationId id, DeploymentSpec deploymentSpec, Inspector field) {
List<Instance> instances = new ArrayList<>();
field.traverse((ArrayTraverser) (name, object) -> {
InstanceName instanceName = InstanceName.from(object.field(instanceNameField).asString());
List<Deployment> deployments = deploymentsFromSlime(object.field(deploymentsField));
DeploymentJobs deploymentJobs = deploymentJobsFromSlime(object.field(deploymentJobsField));
List<AssignedRotation> assignedRotations = assignedRotationsFromSlime(deploymentSpec, object);
RotationStatus rotationStatus = rotationStatusFromSlime(object);
instances.add(new Instance(id.instance(instanceName),
deployments,
deploymentJobs,
assignedRotations,
rotationStatus));
});
return instances;
}
private Set<PublicKey> deployKeysFromSlime(Inspector array) {
Set<PublicKey> keys = new LinkedHashSet<>();
array.traverse((ArrayTraverser) (__, key) -> keys.add(KeyUtils.fromPemEncodedPublicKey(key.asString())));
return keys;
}
private List<Deployment> deploymentsFromSlime(Inspector array) {
List<Deployment> deployments = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> deployments.add(deploymentFromSlime(item)));
return deployments;
}
private Deployment deploymentFromSlime(Inspector deploymentObject) {
return new Deployment(zoneIdFromSlime(deploymentObject.field(zoneField)),
applicationVersionFromSlime(deploymentObject.field(applicationPackageRevisionField)),
Version.fromString(deploymentObject.field(versionField).asString()),
Instant.ofEpochMilli(deploymentObject.field(deployTimeField).asLong()),
clusterInfoMapFromSlime(deploymentObject.field(clusterInfoField)),
deploymentMetricsFromSlime(deploymentObject.field(deploymentMetricsField)),
DeploymentActivity.create(Serializers.optionalInstant(deploymentObject.field(lastQueriedField)),
Serializers.optionalInstant(deploymentObject.field(lastWrittenField)),
Serializers.optionalDouble(deploymentObject.field(lastQueriesPerSecondField)),
Serializers.optionalDouble(deploymentObject.field(lastWritesPerSecondField))));
}
private DeploymentMetrics deploymentMetricsFromSlime(Inspector object) {
Optional<Instant> instant = object.field(deploymentMetricsUpdateTime).valid() ?
Optional.of(Instant.ofEpochMilli(object.field(deploymentMetricsUpdateTime).asLong())) :
Optional.empty();
return new DeploymentMetrics(object.field(deploymentMetricsQPSField).asDouble(),
object.field(deploymentMetricsWPSField).asDouble(),
object.field(deploymentMetricsDocsField).asDouble(),
object.field(deploymentMetricsQueryLatencyField).asDouble(),
object.field(deploymentMetricsWriteLatencyField).asDouble(),
instant,
deploymentWarningsFrom(object.field(deploymentMetricsWarningsField)));
}
private Map<DeploymentMetrics.Warning, Integer> deploymentWarningsFrom(Inspector object) {
Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>();
object.traverse((ObjectTraverser) (name, value) -> warnings.put(DeploymentMetrics.Warning.valueOf(name),
(int) value.asLong()));
return Collections.unmodifiableMap(warnings);
}
private RotationStatus rotationStatusFromSlime(Inspector parentObject) {
var object = parentObject.field(rotationStatusField);
var statusMap = new LinkedHashMap<RotationId, Map<ZoneId, RotationState>>();
object.traverse((ArrayTraverser) (idx, statusObject) -> statusMap.put(new RotationId(statusObject.field(rotationIdField).asString()),
singleRotationStatusFromSlime(statusObject.field(statusField))));
return RotationStatus.from(statusMap);
}
private Map<ZoneId, RotationState> singleRotationStatusFromSlime(Inspector object) {
if (!object.valid()) {
return Collections.emptyMap();
}
Map<ZoneId, RotationState> rotationStatus = new LinkedHashMap<>();
object.traverse((ArrayTraverser) (idx, statusObject) -> {
var zone = zoneIdFromSlime(statusObject);
var status = RotationState.valueOf(statusObject.field(rotationStateField).asString());
rotationStatus.put(zone, status);
});
return Collections.unmodifiableMap(rotationStatus);
}
private Map<ClusterSpec.Id, ClusterInfo> clusterInfoMapFromSlime (Inspector object) {
Map<ClusterSpec.Id, ClusterInfo> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterInfoFromSlime(value)));
return map;
}
private ClusterInfo clusterInfoFromSlime(Inspector inspector) {
String flavor = inspector.field(clusterInfoFlavorField).asString();
int cost = (int)inspector.field(clusterInfoCostField).asLong();
String type = inspector.field(clusterInfoTypeField).asString();
double flavorCpu = inspector.field(clusterInfoCpuField).asDouble();
double flavorMem = inspector.field(clusterInfoMemField).asDouble();
double flavorDisk = inspector.field(clusterInfoDiskField).asDouble();
List<String> hostnames = new ArrayList<>();
inspector.field(clusterInfoHostnamesField).traverse((ArrayTraverser)(int index, Inspector value) -> hostnames.add(value.asString()));
return new ClusterInfo(flavor, cost, flavorCpu, flavorMem, flavorDisk, ClusterSpec.Type.from(type), hostnames);
}
private ZoneId zoneIdFromSlime(Inspector object) {
return ZoneId.from(object.field(environmentField).asString(), object.field(regionField).asString());
}
private ApplicationVersion applicationVersionFromSlime(Inspector object) {
if ( ! object.valid()) return ApplicationVersion.unknown;
OptionalLong applicationBuildNumber = Serializers.optionalLong(object.field(applicationBuildNumberField));
Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField));
if (sourceRevision.isEmpty() || applicationBuildNumber.isEmpty()) {
return ApplicationVersion.unknown;
}
Optional<String> authorEmail = Serializers.optionalString(object.field(authorEmailField));
Optional<Version> compileVersion = Serializers.optionalString(object.field(compileVersionField)).map(Version::fromString);
Optional<Instant> buildTime = Serializers.optionalInstant(object.field(buildTimeField));
if (authorEmail.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong());
if (compileVersion.isEmpty() || buildTime.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get());
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get(),
compileVersion.get(), buildTime.get());
}
private Optional<SourceRevision> sourceRevisionFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new SourceRevision(object.field(repositoryField).asString(),
object.field(branchField).asString(),
object.field(commitField).asString()));
}
private DeploymentJobs deploymentJobsFromSlime(Inspector object) {
List<JobStatus> jobStatusList = jobStatusListFromSlime(object.field(jobStatusField));
return new DeploymentJobs(jobStatusList);
}
private Change changeFromSlime(Inspector object) {
if ( ! object.valid()) return Change.empty();
Inspector versionFieldValue = object.field(versionField);
Change change = Change.empty();
if (versionFieldValue.valid())
change = Change.of(Version.fromString(versionFieldValue.asString()));
if (object.field(applicationBuildNumberField).valid())
change = change.with(applicationVersionFromSlime(object));
if (object.field(pinnedField).asBool())
change = change.withPin();
return change;
}
private List<JobStatus> jobStatusListFromSlime(Inspector array) {
List<JobStatus> jobStatusList = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> jobStatusFromSlime(item).ifPresent(jobStatusList::add));
return jobStatusList;
}
private Optional<JobStatus> jobStatusFromSlime(Inspector object) {
Optional<JobType> jobType =
JobType.fromOptionalJobName(object.field(jobTypeField).asString());
if (jobType.isEmpty()) return Optional.empty();
Optional<JobError> jobError = Optional.empty();
if (object.field(errorField).valid())
jobError = Optional.of(JobError.valueOf(object.field(errorField).asString()));
return Optional.of(new JobStatus(jobType.get(),
jobError,
jobRunFromSlime(object.field(lastTriggeredField)),
jobRunFromSlime(object.field(lastCompletedField)),
jobRunFromSlime(object.field(firstFailingField)),
jobRunFromSlime(object.field(lastSuccessField)),
Serializers.optionalLong(object.field(pausedUntilField))));
}
private Optional<JobStatus.JobRun> jobRunFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new JobStatus.JobRun(object.field(jobRunIdField).asLong(),
new Version(object.field(versionField).asString()),
applicationVersionFromSlime(object.field(revisionField)),
Serializers.optionalString(object.field(sourceVersionField)).map(Version::fromString),
Optional.of(object.field(sourceApplicationField)).filter(Inspector::valid).map(this::applicationVersionFromSlime),
object.field(reasonField).asString(),
Instant.ofEpochMilli(object.field(atField).asLong())));
}
private List<AssignedRotation> assignedRotationsFromSlime(DeploymentSpec deploymentSpec, Inspector root) {
var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>();
root.field(assignedRotationsField).traverse((ArrayTraverser) (idx, inspector) -> {
var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString());
var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString());
var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString());
var regions = deploymentSpec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
} |
Typo. | private static Optional<ApplicationVersion> requireNotUnknown(Optional<ApplicationVersion> latestVersion) {
Objects.requireNonNull(latestVersion, "latestVersion cannot be null");
latestVersion.ifPresent(version -> {
if (version.isUnknown())
throw new IllegalArgumentException("latstVersion cannot be unknown");
});
return latestVersion;
} | throw new IllegalArgumentException("latstVersion cannot be unknown"); | private static Optional<ApplicationVersion> requireNotUnknown(Optional<ApplicationVersion> latestVersion) {
Objects.requireNonNull(latestVersion, "latestVersion cannot be null");
latestVersion.ifPresent(version -> {
if (version.isUnknown())
throw new IllegalArgumentException("latstVersion cannot be unknown");
});
return latestVersion;
} | class Application {
private final TenantAndApplicationId id;
private final Instant createdAt;
private final DeploymentSpec deploymentSpec;
private final ValidationOverrides validationOverrides;
private final Optional<ApplicationVersion> latestVersion;
private final OptionalLong projectId;
private final boolean internal;
private final Change change;
private final Change outstandingChange;
private final Optional<IssueId> deploymentIssueId;
private final Optional<IssueId> ownershipIssueId;
private final Optional<User> owner;
private final OptionalInt majorVersion;
private final ApplicationMetrics metrics;
private final Set<PublicKey> deployKeys;
private final Map<InstanceName, Instance> instances;
/** Creates an empty application. */
public Application(TenantAndApplicationId id, Instant now) {
this(id, now, DeploymentSpec.empty, ValidationOverrides.empty, Change.empty(), Change.empty(),
Optional.empty(), Optional.empty(), Optional.empty(), OptionalInt.empty(),
new ApplicationMetrics(0, 0), Set.of(), OptionalLong.empty(), false, Optional.empty(), List.of());
}
public Application(TenantAndApplicationId id, Instant createdAt, DeploymentSpec deploymentSpec, ValidationOverrides validationOverrides,
Change change, Change outstandingChange, Optional<IssueId> deploymentIssueId, Optional<IssueId> ownershipIssueId, Optional<User> owner,
OptionalInt majorVersion, ApplicationMetrics metrics, Set<PublicKey> deployKeys, OptionalLong projectId,
boolean internal, Optional<ApplicationVersion> latestVersion, Collection<Instance> instances) {
this.id = Objects.requireNonNull(id, "id cannot be null");
this.createdAt = Objects.requireNonNull(createdAt, "instant of creation cannot be null");
this.deploymentSpec = Objects.requireNonNull(deploymentSpec, "deploymentSpec cannot be null");
this.validationOverrides = Objects.requireNonNull(validationOverrides, "validationOverrides cannot be null");
this.change = Objects.requireNonNull(change, "change cannot be null");
this.outstandingChange = Objects.requireNonNull(outstandingChange, "outstandingChange cannot be null");
this.deploymentIssueId = Objects.requireNonNull(deploymentIssueId, "deploymentIssueId cannot be null");
this.ownershipIssueId = Objects.requireNonNull(ownershipIssueId, "ownershipIssueId cannot be null");
this.owner = Objects.requireNonNull(owner, "owner cannot be null");
this.majorVersion = Objects.requireNonNull(majorVersion, "majorVersion cannot be null");
this.metrics = Objects.requireNonNull(metrics, "metrics cannot be null");
this.deployKeys = Objects.requireNonNull(deployKeys, "deployKeys cannot be null");
this.projectId = Objects.requireNonNull(projectId, "projectId cannot be null");
this.internal = internal;
this.latestVersion = requireNotUnknown(latestVersion);
this.instances = ImmutableSortedMap.copyOf(instances.stream().collect(Collectors.toMap(Instance::name, Function.identity())));
}
public TenantAndApplicationId id() { return id; }
public Instant createdAt() { return createdAt; }
/**
* Returns the last deployed deployment spec of this application,
* or the empty deployment spec if it has never been deployed
*/
public DeploymentSpec deploymentSpec() { return deploymentSpec; }
/** Returns the project id of this application, if it has any. */
public OptionalLong projectId() { return projectId; }
/** Returns the last submitted version of this application. */
public Optional<ApplicationVersion> latestVersion() { return latestVersion; }
/** Returns whether this application is run on the internal deployment pipeline. */
public boolean internal() { return internal; }
/**
* Returns the last deployed validation overrides of this application,
* or the empty validation overrides if it has never been deployed
* (or was deployed with an empty/missing validation overrides)
*/
public ValidationOverrides validationOverrides() { return validationOverrides; }
/** Returns the instances of this application */
public Map<InstanceName, Instance> instances() { return instances; }
/** Returns the instance with the given name, if it exists. */
public Optional<Instance> get(InstanceName instance) { return Optional.ofNullable(instances.get(instance)); }
/** Returns the instance with the given name, or throws. */
public Instance require(InstanceName instance) {
return get(instance).orElseThrow(() -> new IllegalArgumentException("Unknown instance '" + instance + "'"));
}
/**
* Returns base change for this application, i.e., the change that is deployed outside block windows.
* This is empty when no change is currently under deployment.
*/
public Change change() { return change; }
/**
* Returns whether this has an outstanding change (in the source repository), which
* has currently not started deploying (because a deployment is (or was) already in progress
*/
public Change outstandingChange() { return outstandingChange; }
/** Returns ID of any open deployment issue filed for this */
public Optional<IssueId> deploymentIssueId() {
return deploymentIssueId;
}
/** Returns ID of the last ownership issue filed for this */
public Optional<IssueId> ownershipIssueId() {
return ownershipIssueId;
}
public Optional<User> owner() {
return owner;
}
/**
* Overrides the system major version for this application. This override takes effect if the deployment
* spec does not specify a major version.
*/
public OptionalInt majorVersion() { return majorVersion; }
/** Returns metrics for this */
public ApplicationMetrics metrics() {
return metrics;
}
/** Returns activity for this */
public ApplicationActivity activity() {
return ApplicationActivity.from(instances.values().stream()
.flatMap(instance -> instance.deployments().values().stream())
.collect(Collectors.toUnmodifiableList()));
}
public Map<InstanceName, List<Deployment>> productionDeployments() {
return instances.values().stream()
.collect(Collectors.toUnmodifiableMap(Instance::name,
instance -> List.copyOf(instance.productionDeployments().values())));
}
/**
* Returns the oldest platform version this has deployed in a permanent zone (not test or staging).
*
* This is unfortunately quite similar to {@link ApplicationController
* but this checks only what the controller has deployed to the production zones, while that checks the node repository
* to see what's actually installed on each node. Thus, this is the right choice for, e.g., target Vespa versions for
* new deployments, while that is the right choice for version to compile against.
*/
public Optional<Version> oldestDeployedPlatform() {
return productionDeployments().values().stream().flatMap(List::stream)
.map(Deployment::version)
.min(Comparator.naturalOrder());
}
/**
* Returns the oldest application version this has deployed in a permanent zone (not test or staging).
*/
public Optional<ApplicationVersion> oldestDeployedApplication() {
return productionDeployments().values().stream().flatMap(List::stream)
.map(Deployment::applicationVersion)
.min(Comparator.naturalOrder());
}
/** Returns the set of deploy keys for this application. */
public Set<PublicKey> deployKeys() { return deployKeys; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (! (o instanceof Application)) return false;
Application that = (Application) o;
return id.equals(that.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public String toString() {
return "application '" + id + "'";
}
} | class Application {
private final TenantAndApplicationId id;
private final Instant createdAt;
private final DeploymentSpec deploymentSpec;
private final ValidationOverrides validationOverrides;
private final Optional<ApplicationVersion> latestVersion;
private final OptionalLong projectId;
private final boolean internal;
private final Change change;
private final Change outstandingChange;
private final Optional<IssueId> deploymentIssueId;
private final Optional<IssueId> ownershipIssueId;
private final Optional<User> owner;
private final OptionalInt majorVersion;
private final ApplicationMetrics metrics;
private final Set<PublicKey> deployKeys;
private final Map<InstanceName, Instance> instances;
/** Creates an empty application. */
public Application(TenantAndApplicationId id, Instant now) {
this(id, now, DeploymentSpec.empty, ValidationOverrides.empty, Change.empty(), Change.empty(),
Optional.empty(), Optional.empty(), Optional.empty(), OptionalInt.empty(),
new ApplicationMetrics(0, 0), Set.of(), OptionalLong.empty(), false, Optional.empty(), List.of());
}
public Application(TenantAndApplicationId id, Instant createdAt, DeploymentSpec deploymentSpec, ValidationOverrides validationOverrides,
Change change, Change outstandingChange, Optional<IssueId> deploymentIssueId, Optional<IssueId> ownershipIssueId, Optional<User> owner,
OptionalInt majorVersion, ApplicationMetrics metrics, Set<PublicKey> deployKeys, OptionalLong projectId,
boolean internal, Optional<ApplicationVersion> latestVersion, Collection<Instance> instances) {
this.id = Objects.requireNonNull(id, "id cannot be null");
this.createdAt = Objects.requireNonNull(createdAt, "instant of creation cannot be null");
this.deploymentSpec = Objects.requireNonNull(deploymentSpec, "deploymentSpec cannot be null");
this.validationOverrides = Objects.requireNonNull(validationOverrides, "validationOverrides cannot be null");
this.change = Objects.requireNonNull(change, "change cannot be null");
this.outstandingChange = Objects.requireNonNull(outstandingChange, "outstandingChange cannot be null");
this.deploymentIssueId = Objects.requireNonNull(deploymentIssueId, "deploymentIssueId cannot be null");
this.ownershipIssueId = Objects.requireNonNull(ownershipIssueId, "ownershipIssueId cannot be null");
this.owner = Objects.requireNonNull(owner, "owner cannot be null");
this.majorVersion = Objects.requireNonNull(majorVersion, "majorVersion cannot be null");
this.metrics = Objects.requireNonNull(metrics, "metrics cannot be null");
this.deployKeys = Objects.requireNonNull(deployKeys, "deployKeys cannot be null");
this.projectId = Objects.requireNonNull(projectId, "projectId cannot be null");
this.internal = internal;
this.latestVersion = requireNotUnknown(latestVersion);
this.instances = ImmutableSortedMap.copyOf(instances.stream().collect(Collectors.toMap(Instance::name, Function.identity())));
}
public TenantAndApplicationId id() { return id; }
public Instant createdAt() { return createdAt; }
/**
* Returns the last deployed deployment spec of this application,
* or the empty deployment spec if it has never been deployed
*/
public DeploymentSpec deploymentSpec() { return deploymentSpec; }
/** Returns the project id of this application, if it has any. */
public OptionalLong projectId() { return projectId; }
/** Returns the last submitted version of this application. */
public Optional<ApplicationVersion> latestVersion() { return latestVersion; }
/** Returns whether this application is run on the internal deployment pipeline. */
public boolean internal() { return internal; }
/**
* Returns the last deployed validation overrides of this application,
* or the empty validation overrides if it has never been deployed
* (or was deployed with an empty/missing validation overrides)
*/
public ValidationOverrides validationOverrides() { return validationOverrides; }
/** Returns the instances of this application */
public Map<InstanceName, Instance> instances() { return instances; }
/** Returns the instance with the given name, if it exists. */
public Optional<Instance> get(InstanceName instance) { return Optional.ofNullable(instances.get(instance)); }
/** Returns the instance with the given name, or throws. */
public Instance require(InstanceName instance) {
return get(instance).orElseThrow(() -> new IllegalArgumentException("Unknown instance '" + instance + "'"));
}
/**
* Returns base change for this application, i.e., the change that is deployed outside block windows.
* This is empty when no change is currently under deployment.
*/
public Change change() { return change; }
/**
* Returns whether this has an outstanding change (in the source repository), which
* has currently not started deploying (because a deployment is (or was) already in progress
*/
public Change outstandingChange() { return outstandingChange; }
/** Returns ID of any open deployment issue filed for this */
public Optional<IssueId> deploymentIssueId() {
return deploymentIssueId;
}
/** Returns ID of the last ownership issue filed for this */
public Optional<IssueId> ownershipIssueId() {
return ownershipIssueId;
}
public Optional<User> owner() {
return owner;
}
/**
* Overrides the system major version for this application. This override takes effect if the deployment
* spec does not specify a major version.
*/
public OptionalInt majorVersion() { return majorVersion; }
/** Returns metrics for this */
public ApplicationMetrics metrics() {
return metrics;
}
/** Returns activity for this */
public ApplicationActivity activity() {
return ApplicationActivity.from(instances.values().stream()
.flatMap(instance -> instance.deployments().values().stream())
.collect(Collectors.toUnmodifiableList()));
}
public Map<InstanceName, List<Deployment>> productionDeployments() {
return instances.values().stream()
.collect(Collectors.toUnmodifiableMap(Instance::name,
instance -> List.copyOf(instance.productionDeployments().values())));
}
/**
* Returns the oldest platform version this has deployed in a permanent zone (not test or staging).
*
* This is unfortunately quite similar to {@link ApplicationController
* but this checks only what the controller has deployed to the production zones, while that checks the node repository
* to see what's actually installed on each node. Thus, this is the right choice for, e.g., target Vespa versions for
* new deployments, while that is the right choice for version to compile against.
*/
public Optional<Version> oldestDeployedPlatform() {
return productionDeployments().values().stream().flatMap(List::stream)
.map(Deployment::version)
.min(Comparator.naturalOrder());
}
/**
* Returns the oldest application version this has deployed in a permanent zone (not test or staging).
*/
public Optional<ApplicationVersion> oldestDeployedApplication() {
return productionDeployments().values().stream().flatMap(List::stream)
.map(Deployment::applicationVersion)
.min(Comparator.naturalOrder());
}
/** Returns the set of deploy keys for this application. */
public Set<PublicKey> deployKeys() { return deployKeys; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (! (o instanceof Application)) return false;
Application that = (Application) o;
return id.equals(that.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public String toString() {
return "application '" + id + "'";
}
} |
Nit: Indentation. | private void reportDeploymentMetrics() {
List<Application> applications = ApplicationList.from(controller().applications().asList())
.withProductionDeployment().asList().stream()
.collect(Collectors.toUnmodifiableList());
List<Instance> instances = applications.stream()
.flatMap(application -> application.instances().values().stream())
.collect(Collectors.toUnmodifiableList());
metric.set(DEPLOYMENT_FAIL_METRIC, deploymentFailRatio(instances) * 100, metric.createContext(Map.of()));
averageDeploymentDurations(instances, clock.instant()).forEach((application, duration) -> {
metric.set(DEPLOYMENT_AVERAGE_DURATION, duration.getSeconds(), metric.createContext(dimensions(application)));
});
deploymentsFailingUpgrade(instances).forEach((application, failingJobs) -> {
metric.set(DEPLOYMENT_FAILING_UPGRADES, failingJobs, metric.createContext(dimensions(application)));
});
deploymentWarnings(instances).forEach((application, warnings) -> {
metric.set(DEPLOYMENT_WARNINGS, warnings, metric.createContext(dimensions(application)));
});
for (Application application : applications)
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()))));
} | .flatMap(ApplicationVersion::buildTime) | private void reportDeploymentMetrics() {
List<Application> applications = ApplicationList.from(controller().applications().asList())
.withProductionDeployment().asList().stream()
.collect(Collectors.toUnmodifiableList());
List<Instance> instances = applications.stream()
.flatMap(application -> application.instances().values().stream())
.collect(Collectors.toUnmodifiableList());
metric.set(DEPLOYMENT_FAIL_METRIC, deploymentFailRatio(instances) * 100, metric.createContext(Map.of()));
averageDeploymentDurations(instances, clock.instant()).forEach((application, duration) -> {
metric.set(DEPLOYMENT_AVERAGE_DURATION, duration.getSeconds(), metric.createContext(dimensions(application)));
});
deploymentsFailingUpgrade(instances).forEach((application, failingJobs) -> {
metric.set(DEPLOYMENT_FAILING_UPGRADES, failingJobs, metric.createContext(dimensions(application)));
});
deploymentWarnings(instances).forEach((application, warnings) -> {
metric.set(DEPLOYMENT_WARNINGS, warnings, metric.createContext(dimensions(application)));
});
for (Application application : applications)
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()))));
} | class MetricsReporter extends Maintainer {
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 NODES_FAILING_SYSTEM_UPGRADE = "deployment.nodesFailingSystemUpgrade";
public static final String REMAINING_ROTATIONS = "remaining_rotations";
public static final String NAME_SERVICE_REQUESTS_QUEUED = "dns.queuedRequests";
private static final Duration NODE_UPGRADE_TIMEOUT = Duration.ofHours(1);
private final Metric metric;
private final Clock clock;
public MetricsReporter(Controller controller, Metric metric, JobControl jobControl) {
super(controller, Duration.ofMinutes(1), jobControl);
this.metric = metric;
this.clock = controller.clock();
}
@Override
public void maintain() {
reportDeploymentMetrics();
reportRemainingRotations();
reportQueuedNameServiceRequests();
reportNodesFailingSystemUpgrade();
}
private void reportRemainingRotations() {
try (RotationLock lock = controller().applications().rotationRepository().lock()) {
int availableRotations = controller().applications().rotationRepository().availableRotations(lock).size();
metric.set(REMAINING_ROTATIONS, availableRotations, metric.createContext(Map.of()));
}
}
private void reportQueuedNameServiceRequests() {
metric.set(NAME_SERVICE_REQUESTS_QUEUED, controller().curator().readNameServiceQueue().requests().size(),
metric.createContext(Map.of()));
}
private void reportNodesFailingSystemUpgrade() {
metric.set(NODES_FAILING_SYSTEM_UPGRADE, nodesFailingSystemUpgrade(), metric.createContext(Map.of()));
}
private int nodesFailingSystemUpgrade() {
if (!controller().versionStatus().isUpgrading()) return 0;
var nodesFailingUpgrade = 0;
var acceptableInstant = clock.instant().minus(NODE_UPGRADE_TIMEOUT);
for (var vespaVersion : controller().versionStatus().versions()) {
if (vespaVersion.confidence() == VespaVersion.Confidence.broken) continue;
for (var nodeVersion : vespaVersion.nodeVersions().asMap().values()) {
if (!nodeVersion.changing()) continue;
if (nodeVersion.changedAt().isBefore(acceptableInstant)) nodesFailingUpgrade++;
}
}
return nodesFailingUpgrade;
}
private static double deploymentFailRatio(List<Instance> instances) {
return instances.stream()
.mapToInt(instance -> instance.deploymentJobs().hasFailures() ? 1 : 0)
.average().orElse(0);
}
private static Map<ApplicationId, Duration> averageDeploymentDurations(List<Instance> instances, Instant now) {
return instances.stream()
.collect(Collectors.toMap(Instance::id,
instance -> averageDeploymentDuration(instance, now)));
}
private static Map<ApplicationId, Integer> deploymentsFailingUpgrade(List<Instance> instances) {
return instances.stream()
.collect(Collectors.toMap(Instance::id, MetricsReporter::deploymentsFailingUpgrade));
}
private static int deploymentsFailingUpgrade(Instance instance) {
return JobList.from(instance).upgrading().failing().size();
}
private static Duration averageDeploymentDuration(Instance instance, Instant now) {
List<Duration> jobDurations = instance.deploymentJobs().jobStatus().values().stream()
.filter(status -> status.lastTriggered().isPresent())
.map(status -> {
Instant triggeredAt = status.lastTriggered().get().at();
Instant runningUntil = status.lastCompleted()
.map(JobStatus.JobRun::at)
.filter(at -> at.isAfter(triggeredAt))
.orElse(now);
return Duration.between(triggeredAt, runningUntil);
})
.collect(Collectors.toList());
return jobDurations.stream()
.reduce(Duration::plus)
.map(totalDuration -> totalDuration.dividedBy(jobDurations.size()))
.orElse(Duration.ZERO);
}
private static Map<ApplicationId, Integer> deploymentWarnings(List<Instance> instances) {
return instances.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());
}
} | class MetricsReporter extends Maintainer {
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 NODES_FAILING_SYSTEM_UPGRADE = "deployment.nodesFailingSystemUpgrade";
public static final String REMAINING_ROTATIONS = "remaining_rotations";
public static final String NAME_SERVICE_REQUESTS_QUEUED = "dns.queuedRequests";
private static final Duration NODE_UPGRADE_TIMEOUT = Duration.ofHours(1);
private final Metric metric;
private final Clock clock;
public MetricsReporter(Controller controller, Metric metric, JobControl jobControl) {
super(controller, Duration.ofMinutes(1), jobControl);
this.metric = metric;
this.clock = controller.clock();
}
@Override
public void maintain() {
reportDeploymentMetrics();
reportRemainingRotations();
reportQueuedNameServiceRequests();
reportNodesFailingSystemUpgrade();
}
private void reportRemainingRotations() {
try (RotationLock lock = controller().applications().rotationRepository().lock()) {
int availableRotations = controller().applications().rotationRepository().availableRotations(lock).size();
metric.set(REMAINING_ROTATIONS, availableRotations, metric.createContext(Map.of()));
}
}
private void reportQueuedNameServiceRequests() {
metric.set(NAME_SERVICE_REQUESTS_QUEUED, controller().curator().readNameServiceQueue().requests().size(),
metric.createContext(Map.of()));
}
private void reportNodesFailingSystemUpgrade() {
metric.set(NODES_FAILING_SYSTEM_UPGRADE, nodesFailingSystemUpgrade(), metric.createContext(Map.of()));
}
private int nodesFailingSystemUpgrade() {
if (!controller().versionStatus().isUpgrading()) return 0;
var nodesFailingUpgrade = 0;
var acceptableInstant = clock.instant().minus(NODE_UPGRADE_TIMEOUT);
for (var vespaVersion : controller().versionStatus().versions()) {
if (vespaVersion.confidence() == VespaVersion.Confidence.broken) continue;
for (var nodeVersion : vespaVersion.nodeVersions().asMap().values()) {
if (!nodeVersion.changing()) continue;
if (nodeVersion.changedAt().isBefore(acceptableInstant)) nodesFailingUpgrade++;
}
}
return nodesFailingUpgrade;
}
private static double deploymentFailRatio(List<Instance> instances) {
return instances.stream()
.mapToInt(instance -> instance.deploymentJobs().hasFailures() ? 1 : 0)
.average().orElse(0);
}
private static Map<ApplicationId, Duration> averageDeploymentDurations(List<Instance> instances, Instant now) {
return instances.stream()
.collect(Collectors.toMap(Instance::id,
instance -> averageDeploymentDuration(instance, now)));
}
private static Map<ApplicationId, Integer> deploymentsFailingUpgrade(List<Instance> instances) {
return instances.stream()
.collect(Collectors.toMap(Instance::id, MetricsReporter::deploymentsFailingUpgrade));
}
private static int deploymentsFailingUpgrade(Instance instance) {
return JobList.from(instance).upgrading().failing().size();
}
private static Duration averageDeploymentDuration(Instance instance, Instant now) {
List<Duration> jobDurations = instance.deploymentJobs().jobStatus().values().stream()
.filter(status -> status.lastTriggered().isPresent())
.map(status -> {
Instant triggeredAt = status.lastTriggered().get().at();
Instant runningUntil = status.lastCompleted()
.map(JobStatus.JobRun::at)
.filter(at -> at.isAfter(triggeredAt))
.orElse(now);
return Duration.between(triggeredAt, runningUntil);
})
.collect(Collectors.toList());
return jobDurations.stream()
.reduce(Duration::plus)
.map(totalDuration -> totalDuration.dividedBy(jobDurations.size()))
.orElse(Duration.ZERO);
}
private static Map<ApplicationId, Integer> deploymentWarnings(List<Instance> instances) {
return instances.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());
}
} |
Thanks. | private Optional<ApplicationVersion> latestVersionFromSlimeWithFallback(Inspector latestVersionObject, List<Instance> instances) {
if (latestVersionObject.valid())
return Optional.of(applicationVersionFromSlime(latestVersionObject));
return instances.stream()
.flatMap(instance -> instance.deploymentJobs().statusOf(JobType.component).stream())
.flatMap(status -> status.lastSuccess().stream())
.map(JobStatus.JobRun::application)
.findFirst();
} | .findFirst(); | private Optional<ApplicationVersion> latestVersionFromSlimeWithFallback(Inspector latestVersionObject, List<Instance> instances) {
if (latestVersionObject.valid())
return Optional.of(applicationVersionFromSlime(latestVersionObject));
return instances.stream()
.flatMap(instance -> instance.deploymentJobs().statusOf(JobType.component).stream())
.flatMap(status -> status.lastSuccess().stream())
.map(JobStatus.JobRun::application)
.findFirst();
} | class ApplicationSerializer {
private static final String idField = "id";
private static final String createdAtField = "createdAt";
private static final String deploymentSpecField = "deploymentSpecField";
private static final String validationOverridesField = "validationOverrides";
private static final String instancesField = "instances";
private static final String deployingField = "deployingField";
private static final String projectIdField = "projectId";
private static final String latestVersionField = "latestVersion";
private static final String builtInternallyField = "builtInternally";
private static final String pinnedField = "pinned";
private static final String outstandingChangeField = "outstandingChangeField";
private static final String deploymentIssueField = "deploymentIssueId";
private static final String ownershipIssueIdField = "ownershipIssueId";
private static final String ownerField = "confirmedOwner";
private static final String majorVersionField = "majorVersion";
private static final String writeQualityField = "writeQuality";
private static final String queryQualityField = "queryQuality";
private static final String pemDeployKeysField = "pemDeployKeys";
private static final String assignedRotationClusterField = "clusterId";
private static final String assignedRotationRotationField = "rotationId";
private static final String instanceNameField = "instanceName";
private static final String deploymentsField = "deployments";
private static final String deploymentJobsField = "deploymentJobs";
private static final String assignedRotationsField = "assignedRotations";
private static final String assignedRotationEndpointField = "endpointId";
private static final String zoneField = "zone";
private static final String environmentField = "environment";
private static final String regionField = "region";
private static final String deployTimeField = "deployTime";
private static final String applicationBuildNumberField = "applicationBuildNumber";
private static final String applicationPackageRevisionField = "applicationPackageRevision";
private static final String sourceRevisionField = "sourceRevision";
private static final String repositoryField = "repositoryField";
private static final String branchField = "branchField";
private static final String commitField = "commitField";
private static final String authorEmailField = "authorEmailField";
private static final String compileVersionField = "compileVersion";
private static final String buildTimeField = "buildTime";
private static final String lastQueriedField = "lastQueried";
private static final String lastWrittenField = "lastWritten";
private static final String lastQueriesPerSecondField = "lastQueriesPerSecond";
private static final String lastWritesPerSecondField = "lastWritesPerSecond";
private static final String jobStatusField = "jobStatus";
private static final String jobTypeField = "jobType";
private static final String errorField = "jobError";
private static final String lastTriggeredField = "lastTriggered";
private static final String lastCompletedField = "lastCompleted";
private static final String firstFailingField = "firstFailing";
private static final String lastSuccessField = "lastSuccess";
private static final String pausedUntilField = "pausedUntil";
private static final String jobRunIdField = "id";
private static final String versionField = "version";
private static final String revisionField = "revision";
private static final String sourceVersionField = "sourceVersion";
private static final String sourceApplicationField = "sourceRevision";
private static final String reasonField = "reason";
private static final String atField = "at";
private static final String clusterInfoField = "clusterInfo";
private static final String clusterInfoFlavorField = "flavor";
private static final String clusterInfoCostField = "cost";
private static final String clusterInfoCpuField = "flavorCpu";
private static final String clusterInfoMemField = "flavorMem";
private static final String clusterInfoDiskField = "flavorDisk";
private static final String clusterInfoTypeField = "clusterType";
private static final String clusterInfoHostnamesField = "hostnames";
private static final String deploymentMetricsField = "metrics";
private static final String deploymentMetricsQPSField = "queriesPerSecond";
private static final String deploymentMetricsWPSField = "writesPerSecond";
private static final String deploymentMetricsDocsField = "documentCount";
private static final String deploymentMetricsQueryLatencyField = "queryLatencyMillis";
private static final String deploymentMetricsWriteLatencyField = "writeLatencyMillis";
private static final String deploymentMetricsUpdateTime = "lastUpdated";
private static final String deploymentMetricsWarningsField = "warnings";
private static final String rotationStatusField = "rotationStatus2";
private static final String rotationIdField = "rotationId";
private static final String rotationStateField = "state";
private static final String statusField = "status";
public Slime toSlime(Application application) {
Slime slime = new Slime();
Cursor root = slime.setObject();
root.setString(idField, application.id().serialized());
root.setLong(createdAtField, application.createdAt().toEpochMilli());
root.setString(deploymentSpecField, application.deploymentSpec().xmlForm());
root.setString(validationOverridesField, application.validationOverrides().xmlForm());
application.projectId().ifPresent(projectId -> root.setLong(projectIdField, projectId));
application.deploymentIssueId().ifPresent(jiraIssueId -> root.setString(deploymentIssueField, jiraIssueId.value()));
application.ownershipIssueId().ifPresent(issueId -> root.setString(ownershipIssueIdField, issueId.value()));
root.setBool(builtInternallyField, application.internal());
toSlime(application.change(), root, deployingField);
toSlime(application.outstandingChange(), root, outstandingChangeField);
application.owner().ifPresent(owner -> root.setString(ownerField, owner.username()));
application.majorVersion().ifPresent(majorVersion -> root.setLong(majorVersionField, majorVersion));
root.setDouble(queryQualityField, application.metrics().queryServiceQuality());
root.setDouble(writeQualityField, application.metrics().writeServiceQuality());
deployKeysToSlime(application.deployKeys(), root.setArray(pemDeployKeysField));
application.latestVersion().ifPresent(version -> toSlime(version, root.setObject(latestVersionField)));
instancesToSlime(application, root.setArray(instancesField));
return slime;
}
private void instancesToSlime(Application application, Cursor array) {
for (Instance instance : application.instances().values()) {
Cursor instanceObject = array.addObject();
instanceObject.setString(instanceNameField, instance.name().value());
deploymentsToSlime(instance.deployments().values(), instanceObject.setArray(deploymentsField));
toSlime(instance.deploymentJobs(), instanceObject.setObject(deploymentJobsField));
assignedRotationsToSlime(instance.rotations(), instanceObject, assignedRotationsField);
toSlime(instance.rotationStatus(), instanceObject.setArray(rotationStatusField));
}
}
private void deployKeysToSlime(Set<PublicKey> deployKeys, Cursor array) {
deployKeys.forEach(key -> array.addString(KeyUtils.toPem(key)));
}
private void deploymentsToSlime(Collection<Deployment> deployments, Cursor array) {
for (Deployment deployment : deployments)
deploymentToSlime(deployment, array.addObject());
}
private void deploymentToSlime(Deployment deployment, Cursor object) {
zoneIdToSlime(deployment.zone(), object.setObject(zoneField));
object.setString(versionField, deployment.version().toString());
object.setLong(deployTimeField, deployment.at().toEpochMilli());
toSlime(deployment.applicationVersion(), object.setObject(applicationPackageRevisionField));
clusterInfoToSlime(deployment.clusterInfo(), object);
deploymentMetricsToSlime(deployment.metrics(), object);
deployment.activity().lastQueried().ifPresent(instant -> object.setLong(lastQueriedField, instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> object.setLong(lastWrittenField, instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> object.setDouble(lastQueriesPerSecondField, value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> object.setDouble(lastWritesPerSecondField, value));
}
private void deploymentMetricsToSlime(DeploymentMetrics metrics, Cursor object) {
Cursor root = object.setObject(deploymentMetricsField);
root.setDouble(deploymentMetricsQPSField, metrics.queriesPerSecond());
root.setDouble(deploymentMetricsWPSField, metrics.writesPerSecond());
root.setDouble(deploymentMetricsDocsField, metrics.documentCount());
root.setDouble(deploymentMetricsQueryLatencyField, metrics.queryLatencyMillis());
root.setDouble(deploymentMetricsWriteLatencyField, metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> root.setLong(deploymentMetricsUpdateTime, instant.toEpochMilli()));
if (!metrics.warnings().isEmpty()) {
Cursor warningsObject = root.setObject(deploymentMetricsWarningsField);
metrics.warnings().forEach((warning, count) -> warningsObject.setLong(warning.name(), count));
}
}
private void clusterInfoToSlime(Map<ClusterSpec.Id, ClusterInfo> clusters, Cursor object) {
Cursor root = object.setObject(clusterInfoField);
for (Map.Entry<ClusterSpec.Id, ClusterInfo> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterInfo info, Cursor object) {
object.setString(clusterInfoFlavorField, info.getFlavor());
object.setLong(clusterInfoCostField, info.getFlavorCost());
object.setDouble(clusterInfoCpuField, info.getFlavorCPU());
object.setDouble(clusterInfoMemField, info.getFlavorMem());
object.setDouble(clusterInfoDiskField, info.getFlavorDisk());
object.setString(clusterInfoTypeField, info.getClusterType().name());
Cursor array = object.setArray(clusterInfoHostnamesField);
for (String host : info.getHostnames()) {
array.addString(host);
}
}
private void zoneIdToSlime(ZoneId zone, Cursor object) {
object.setString(environmentField, zone.environment().value());
object.setString(regionField, zone.region().value());
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if (applicationVersion.buildNumber().isPresent() && applicationVersion.source().isPresent()) {
object.setLong(applicationBuildNumberField, applicationVersion.buildNumber().getAsLong());
toSlime(applicationVersion.source().get(), object.setObject(sourceRevisionField));
applicationVersion.authorEmail().ifPresent(email -> object.setString(authorEmailField, email));
applicationVersion.compileVersion().ifPresent(version -> object.setString(compileVersionField, version.toString()));
applicationVersion.buildTime().ifPresent(time -> object.setLong(buildTimeField, time.toEpochMilli()));
}
}
private void toSlime(SourceRevision sourceRevision, Cursor object) {
object.setString(repositoryField, sourceRevision.repository());
object.setString(branchField, sourceRevision.branch());
object.setString(commitField, sourceRevision.commit());
}
private void toSlime(DeploymentJobs deploymentJobs, Cursor cursor) {
jobStatusToSlime(deploymentJobs.jobStatus().values(), cursor.setArray(jobStatusField));
}
private void jobStatusToSlime(Collection<JobStatus> jobStatuses, Cursor jobStatusArray) {
for (JobStatus jobStatus : jobStatuses)
toSlime(jobStatus, jobStatusArray.addObject());
}
private void toSlime(JobStatus jobStatus, Cursor object) {
object.setString(jobTypeField, jobStatus.type().jobName());
if (jobStatus.jobError().isPresent())
object.setString(errorField, jobStatus.jobError().get().name());
jobStatus.lastTriggered().ifPresent(run -> jobRunToSlime(run, object, lastTriggeredField));
jobStatus.lastCompleted().ifPresent(run -> jobRunToSlime(run, object, lastCompletedField));
jobStatus.lastSuccess().ifPresent(run -> jobRunToSlime(run, object, lastSuccessField));
jobStatus.firstFailing().ifPresent(run -> jobRunToSlime(run, object, firstFailingField));
jobStatus.pausedUntil().ifPresent(until -> object.setLong(pausedUntilField, until));
}
private void jobRunToSlime(JobStatus.JobRun jobRun, Cursor parent, String jobRunObjectName) {
Cursor object = parent.setObject(jobRunObjectName);
object.setLong(jobRunIdField, jobRun.id());
object.setString(versionField, jobRun.platform().toString());
toSlime(jobRun.application(), object.setObject(revisionField));
jobRun.sourcePlatform().ifPresent(version -> object.setString(sourceVersionField, version.toString()));
jobRun.sourceApplication().ifPresent(version -> toSlime(version, object.setObject(sourceApplicationField)));
object.setString(reasonField, jobRun.reason());
object.setLong(atField, jobRun.at().toEpochMilli());
}
private void toSlime(Change deploying, Cursor parentObject, String fieldName) {
if (deploying.isEmpty()) return;
Cursor object = parentObject.setObject(fieldName);
if (deploying.platform().isPresent())
object.setString(versionField, deploying.platform().get().toString());
if (deploying.application().isPresent())
toSlime(deploying.application().get(), object);
if (deploying.isPinned())
object.setBool(pinnedField, true);
}
private void toSlime(RotationStatus status, Cursor array) {
status.asMap().forEach((rotationId, zoneStatus) -> {
Cursor rotationObject = array.addObject();
rotationObject.setString(rotationIdField, rotationId.asString());
Cursor statusArray = rotationObject.setArray(statusField);
zoneStatus.forEach((zone, state) -> {
Cursor statusObject = statusArray.addObject();
zoneIdToSlime(zone, statusObject);
statusObject.setString(rotationStateField, state.name());
});
});
}
private void assignedRotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) {
var rotationsArray = parent.setArray(fieldName);
for (var rotation : rotations) {
var object = rotationsArray.addObject();
object.setString(assignedRotationEndpointField, rotation.endpointId().id());
object.setString(assignedRotationRotationField, rotation.rotationId().asString());
object.setString(assignedRotationClusterField, rotation.clusterId().value());
}
}
public Application fromSlime(Slime slime) {
Inspector root = slime.get();
TenantAndApplicationId id = TenantAndApplicationId.fromSerialized(root.field(idField).asString());
Instant createdAt = Instant.ofEpochMilli(root.field(createdAtField).asLong());
DeploymentSpec deploymentSpec = DeploymentSpec.fromXml(root.field(deploymentSpecField).asString(), false);
ValidationOverrides validationOverrides = ValidationOverrides.fromXml(root.field(validationOverridesField).asString());
Change deploying = changeFromSlime(root.field(deployingField));
Change outstandingChange = changeFromSlime(root.field(outstandingChangeField));
Optional<IssueId> deploymentIssueId = Serializers.optionalString(root.field(deploymentIssueField)).map(IssueId::from);
Optional<IssueId> ownershipIssueId = Serializers.optionalString(root.field(ownershipIssueIdField)).map(IssueId::from);
Optional<User> owner = Serializers.optionalString(root.field(ownerField)).map(User::from);
OptionalInt majorVersion = Serializers.optionalInteger(root.field(majorVersionField));
ApplicationMetrics metrics = new ApplicationMetrics(root.field(queryQualityField).asDouble(),
root.field(writeQualityField).asDouble());
Set<PublicKey> deployKeys = deployKeysFromSlime(root.field(pemDeployKeysField));
List<Instance> instances = instancesFromSlime(id, deploymentSpec, root.field(instancesField));
OptionalLong projectId = Serializers.optionalLong(root.field(projectIdField));
Optional<ApplicationVersion> latestVersion = latestVersionFromSlimeWithFallback(root.field(latestVersionField), instances);
boolean builtInternally = root.field(builtInternallyField).asBool();
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
deployKeys, projectId, builtInternally, latestVersion, instances);
}
private List<Instance> instancesFromSlime(TenantAndApplicationId id, DeploymentSpec deploymentSpec, Inspector field) {
List<Instance> instances = new ArrayList<>();
field.traverse((ArrayTraverser) (name, object) -> {
InstanceName instanceName = InstanceName.from(object.field(instanceNameField).asString());
List<Deployment> deployments = deploymentsFromSlime(object.field(deploymentsField));
DeploymentJobs deploymentJobs = deploymentJobsFromSlime(object.field(deploymentJobsField));
List<AssignedRotation> assignedRotations = assignedRotationsFromSlime(deploymentSpec, object);
RotationStatus rotationStatus = rotationStatusFromSlime(object);
instances.add(new Instance(id.instance(instanceName),
deployments,
deploymentJobs,
assignedRotations,
rotationStatus));
});
return instances;
}
private Set<PublicKey> deployKeysFromSlime(Inspector array) {
Set<PublicKey> keys = new LinkedHashSet<>();
array.traverse((ArrayTraverser) (__, key) -> keys.add(KeyUtils.fromPemEncodedPublicKey(key.asString())));
return keys;
}
private List<Deployment> deploymentsFromSlime(Inspector array) {
List<Deployment> deployments = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> deployments.add(deploymentFromSlime(item)));
return deployments;
}
private Deployment deploymentFromSlime(Inspector deploymentObject) {
return new Deployment(zoneIdFromSlime(deploymentObject.field(zoneField)),
applicationVersionFromSlime(deploymentObject.field(applicationPackageRevisionField)),
Version.fromString(deploymentObject.field(versionField).asString()),
Instant.ofEpochMilli(deploymentObject.field(deployTimeField).asLong()),
clusterInfoMapFromSlime(deploymentObject.field(clusterInfoField)),
deploymentMetricsFromSlime(deploymentObject.field(deploymentMetricsField)),
DeploymentActivity.create(Serializers.optionalInstant(deploymentObject.field(lastQueriedField)),
Serializers.optionalInstant(deploymentObject.field(lastWrittenField)),
Serializers.optionalDouble(deploymentObject.field(lastQueriesPerSecondField)),
Serializers.optionalDouble(deploymentObject.field(lastWritesPerSecondField))));
}
private DeploymentMetrics deploymentMetricsFromSlime(Inspector object) {
Optional<Instant> instant = object.field(deploymentMetricsUpdateTime).valid() ?
Optional.of(Instant.ofEpochMilli(object.field(deploymentMetricsUpdateTime).asLong())) :
Optional.empty();
return new DeploymentMetrics(object.field(deploymentMetricsQPSField).asDouble(),
object.field(deploymentMetricsWPSField).asDouble(),
object.field(deploymentMetricsDocsField).asDouble(),
object.field(deploymentMetricsQueryLatencyField).asDouble(),
object.field(deploymentMetricsWriteLatencyField).asDouble(),
instant,
deploymentWarningsFrom(object.field(deploymentMetricsWarningsField)));
}
private Map<DeploymentMetrics.Warning, Integer> deploymentWarningsFrom(Inspector object) {
Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>();
object.traverse((ObjectTraverser) (name, value) -> warnings.put(DeploymentMetrics.Warning.valueOf(name),
(int) value.asLong()));
return Collections.unmodifiableMap(warnings);
}
private RotationStatus rotationStatusFromSlime(Inspector parentObject) {
var object = parentObject.field(rotationStatusField);
var statusMap = new LinkedHashMap<RotationId, Map<ZoneId, RotationState>>();
object.traverse((ArrayTraverser) (idx, statusObject) -> statusMap.put(new RotationId(statusObject.field(rotationIdField).asString()),
singleRotationStatusFromSlime(statusObject.field(statusField))));
return RotationStatus.from(statusMap);
}
private Map<ZoneId, RotationState> singleRotationStatusFromSlime(Inspector object) {
if (!object.valid()) {
return Collections.emptyMap();
}
Map<ZoneId, RotationState> rotationStatus = new LinkedHashMap<>();
object.traverse((ArrayTraverser) (idx, statusObject) -> {
var zone = zoneIdFromSlime(statusObject);
var status = RotationState.valueOf(statusObject.field(rotationStateField).asString());
rotationStatus.put(zone, status);
});
return Collections.unmodifiableMap(rotationStatus);
}
private Map<ClusterSpec.Id, ClusterInfo> clusterInfoMapFromSlime (Inspector object) {
Map<ClusterSpec.Id, ClusterInfo> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterInfoFromSlime(value)));
return map;
}
private ClusterInfo clusterInfoFromSlime(Inspector inspector) {
String flavor = inspector.field(clusterInfoFlavorField).asString();
int cost = (int)inspector.field(clusterInfoCostField).asLong();
String type = inspector.field(clusterInfoTypeField).asString();
double flavorCpu = inspector.field(clusterInfoCpuField).asDouble();
double flavorMem = inspector.field(clusterInfoMemField).asDouble();
double flavorDisk = inspector.field(clusterInfoDiskField).asDouble();
List<String> hostnames = new ArrayList<>();
inspector.field(clusterInfoHostnamesField).traverse((ArrayTraverser)(int index, Inspector value) -> hostnames.add(value.asString()));
return new ClusterInfo(flavor, cost, flavorCpu, flavorMem, flavorDisk, ClusterSpec.Type.from(type), hostnames);
}
private ZoneId zoneIdFromSlime(Inspector object) {
return ZoneId.from(object.field(environmentField).asString(), object.field(regionField).asString());
}
private ApplicationVersion applicationVersionFromSlime(Inspector object) {
if ( ! object.valid()) return ApplicationVersion.unknown;
OptionalLong applicationBuildNumber = Serializers.optionalLong(object.field(applicationBuildNumberField));
Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField));
if (sourceRevision.isEmpty() || applicationBuildNumber.isEmpty()) {
return ApplicationVersion.unknown;
}
Optional<String> authorEmail = Serializers.optionalString(object.field(authorEmailField));
Optional<Version> compileVersion = Serializers.optionalString(object.field(compileVersionField)).map(Version::fromString);
Optional<Instant> buildTime = Serializers.optionalInstant(object.field(buildTimeField));
if (authorEmail.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong());
if (compileVersion.isEmpty() || buildTime.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get());
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get(),
compileVersion.get(), buildTime.get());
}
private Optional<SourceRevision> sourceRevisionFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new SourceRevision(object.field(repositoryField).asString(),
object.field(branchField).asString(),
object.field(commitField).asString()));
}
private DeploymentJobs deploymentJobsFromSlime(Inspector object) {
List<JobStatus> jobStatusList = jobStatusListFromSlime(object.field(jobStatusField));
return new DeploymentJobs(jobStatusList);
}
private Change changeFromSlime(Inspector object) {
if ( ! object.valid()) return Change.empty();
Inspector versionFieldValue = object.field(versionField);
Change change = Change.empty();
if (versionFieldValue.valid())
change = Change.of(Version.fromString(versionFieldValue.asString()));
if (object.field(applicationBuildNumberField).valid())
change = change.with(applicationVersionFromSlime(object));
if (object.field(pinnedField).asBool())
change = change.withPin();
return change;
}
private List<JobStatus> jobStatusListFromSlime(Inspector array) {
List<JobStatus> jobStatusList = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> jobStatusFromSlime(item).ifPresent(jobStatusList::add));
return jobStatusList;
}
private Optional<JobStatus> jobStatusFromSlime(Inspector object) {
Optional<JobType> jobType =
JobType.fromOptionalJobName(object.field(jobTypeField).asString());
if (jobType.isEmpty()) return Optional.empty();
Optional<JobError> jobError = Optional.empty();
if (object.field(errorField).valid())
jobError = Optional.of(JobError.valueOf(object.field(errorField).asString()));
return Optional.of(new JobStatus(jobType.get(),
jobError,
jobRunFromSlime(object.field(lastTriggeredField)),
jobRunFromSlime(object.field(lastCompletedField)),
jobRunFromSlime(object.field(firstFailingField)),
jobRunFromSlime(object.field(lastSuccessField)),
Serializers.optionalLong(object.field(pausedUntilField))));
}
private Optional<JobStatus.JobRun> jobRunFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new JobStatus.JobRun(object.field(jobRunIdField).asLong(),
new Version(object.field(versionField).asString()),
applicationVersionFromSlime(object.field(revisionField)),
Serializers.optionalString(object.field(sourceVersionField)).map(Version::fromString),
Optional.of(object.field(sourceApplicationField)).filter(Inspector::valid).map(this::applicationVersionFromSlime),
object.field(reasonField).asString(),
Instant.ofEpochMilli(object.field(atField).asLong())));
}
private List<AssignedRotation> assignedRotationsFromSlime(DeploymentSpec deploymentSpec, Inspector root) {
var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>();
root.field(assignedRotationsField).traverse((ArrayTraverser) (idx, inspector) -> {
var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString());
var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString());
var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString());
var regions = deploymentSpec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
} | class ApplicationSerializer {
private static final String idField = "id";
private static final String createdAtField = "createdAt";
private static final String deploymentSpecField = "deploymentSpecField";
private static final String validationOverridesField = "validationOverrides";
private static final String instancesField = "instances";
private static final String deployingField = "deployingField";
private static final String projectIdField = "projectId";
private static final String latestVersionField = "latestVersion";
private static final String builtInternallyField = "builtInternally";
private static final String pinnedField = "pinned";
private static final String outstandingChangeField = "outstandingChangeField";
private static final String deploymentIssueField = "deploymentIssueId";
private static final String ownershipIssueIdField = "ownershipIssueId";
private static final String ownerField = "confirmedOwner";
private static final String majorVersionField = "majorVersion";
private static final String writeQualityField = "writeQuality";
private static final String queryQualityField = "queryQuality";
private static final String pemDeployKeysField = "pemDeployKeys";
private static final String assignedRotationClusterField = "clusterId";
private static final String assignedRotationRotationField = "rotationId";
private static final String instanceNameField = "instanceName";
private static final String deploymentsField = "deployments";
private static final String deploymentJobsField = "deploymentJobs";
private static final String assignedRotationsField = "assignedRotations";
private static final String assignedRotationEndpointField = "endpointId";
private static final String zoneField = "zone";
private static final String environmentField = "environment";
private static final String regionField = "region";
private static final String deployTimeField = "deployTime";
private static final String applicationBuildNumberField = "applicationBuildNumber";
private static final String applicationPackageRevisionField = "applicationPackageRevision";
private static final String sourceRevisionField = "sourceRevision";
private static final String repositoryField = "repositoryField";
private static final String branchField = "branchField";
private static final String commitField = "commitField";
private static final String authorEmailField = "authorEmailField";
private static final String compileVersionField = "compileVersion";
private static final String buildTimeField = "buildTime";
private static final String lastQueriedField = "lastQueried";
private static final String lastWrittenField = "lastWritten";
private static final String lastQueriesPerSecondField = "lastQueriesPerSecond";
private static final String lastWritesPerSecondField = "lastWritesPerSecond";
private static final String jobStatusField = "jobStatus";
private static final String jobTypeField = "jobType";
private static final String errorField = "jobError";
private static final String lastTriggeredField = "lastTriggered";
private static final String lastCompletedField = "lastCompleted";
private static final String firstFailingField = "firstFailing";
private static final String lastSuccessField = "lastSuccess";
private static final String pausedUntilField = "pausedUntil";
private static final String jobRunIdField = "id";
private static final String versionField = "version";
private static final String revisionField = "revision";
private static final String sourceVersionField = "sourceVersion";
private static final String sourceApplicationField = "sourceRevision";
private static final String reasonField = "reason";
private static final String atField = "at";
private static final String clusterInfoField = "clusterInfo";
private static final String clusterInfoFlavorField = "flavor";
private static final String clusterInfoCostField = "cost";
private static final String clusterInfoCpuField = "flavorCpu";
private static final String clusterInfoMemField = "flavorMem";
private static final String clusterInfoDiskField = "flavorDisk";
private static final String clusterInfoTypeField = "clusterType";
private static final String clusterInfoHostnamesField = "hostnames";
private static final String deploymentMetricsField = "metrics";
private static final String deploymentMetricsQPSField = "queriesPerSecond";
private static final String deploymentMetricsWPSField = "writesPerSecond";
private static final String deploymentMetricsDocsField = "documentCount";
private static final String deploymentMetricsQueryLatencyField = "queryLatencyMillis";
private static final String deploymentMetricsWriteLatencyField = "writeLatencyMillis";
private static final String deploymentMetricsUpdateTime = "lastUpdated";
private static final String deploymentMetricsWarningsField = "warnings";
private static final String rotationStatusField = "rotationStatus2";
private static final String rotationIdField = "rotationId";
private static final String rotationStateField = "state";
private static final String statusField = "status";
public Slime toSlime(Application application) {
Slime slime = new Slime();
Cursor root = slime.setObject();
root.setString(idField, application.id().serialized());
root.setLong(createdAtField, application.createdAt().toEpochMilli());
root.setString(deploymentSpecField, application.deploymentSpec().xmlForm());
root.setString(validationOverridesField, application.validationOverrides().xmlForm());
application.projectId().ifPresent(projectId -> root.setLong(projectIdField, projectId));
application.deploymentIssueId().ifPresent(jiraIssueId -> root.setString(deploymentIssueField, jiraIssueId.value()));
application.ownershipIssueId().ifPresent(issueId -> root.setString(ownershipIssueIdField, issueId.value()));
root.setBool(builtInternallyField, application.internal());
toSlime(application.change(), root, deployingField);
toSlime(application.outstandingChange(), root, outstandingChangeField);
application.owner().ifPresent(owner -> root.setString(ownerField, owner.username()));
application.majorVersion().ifPresent(majorVersion -> root.setLong(majorVersionField, majorVersion));
root.setDouble(queryQualityField, application.metrics().queryServiceQuality());
root.setDouble(writeQualityField, application.metrics().writeServiceQuality());
deployKeysToSlime(application.deployKeys(), root.setArray(pemDeployKeysField));
application.latestVersion().ifPresent(version -> toSlime(version, root.setObject(latestVersionField)));
instancesToSlime(application, root.setArray(instancesField));
return slime;
}
private void instancesToSlime(Application application, Cursor array) {
for (Instance instance : application.instances().values()) {
Cursor instanceObject = array.addObject();
instanceObject.setString(instanceNameField, instance.name().value());
deploymentsToSlime(instance.deployments().values(), instanceObject.setArray(deploymentsField));
toSlime(instance.deploymentJobs(), instanceObject.setObject(deploymentJobsField));
assignedRotationsToSlime(instance.rotations(), instanceObject, assignedRotationsField);
toSlime(instance.rotationStatus(), instanceObject.setArray(rotationStatusField));
}
}
private void deployKeysToSlime(Set<PublicKey> deployKeys, Cursor array) {
deployKeys.forEach(key -> array.addString(KeyUtils.toPem(key)));
}
private void deploymentsToSlime(Collection<Deployment> deployments, Cursor array) {
for (Deployment deployment : deployments)
deploymentToSlime(deployment, array.addObject());
}
private void deploymentToSlime(Deployment deployment, Cursor object) {
zoneIdToSlime(deployment.zone(), object.setObject(zoneField));
object.setString(versionField, deployment.version().toString());
object.setLong(deployTimeField, deployment.at().toEpochMilli());
toSlime(deployment.applicationVersion(), object.setObject(applicationPackageRevisionField));
clusterInfoToSlime(deployment.clusterInfo(), object);
deploymentMetricsToSlime(deployment.metrics(), object);
deployment.activity().lastQueried().ifPresent(instant -> object.setLong(lastQueriedField, instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> object.setLong(lastWrittenField, instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> object.setDouble(lastQueriesPerSecondField, value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> object.setDouble(lastWritesPerSecondField, value));
}
private void deploymentMetricsToSlime(DeploymentMetrics metrics, Cursor object) {
Cursor root = object.setObject(deploymentMetricsField);
root.setDouble(deploymentMetricsQPSField, metrics.queriesPerSecond());
root.setDouble(deploymentMetricsWPSField, metrics.writesPerSecond());
root.setDouble(deploymentMetricsDocsField, metrics.documentCount());
root.setDouble(deploymentMetricsQueryLatencyField, metrics.queryLatencyMillis());
root.setDouble(deploymentMetricsWriteLatencyField, metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> root.setLong(deploymentMetricsUpdateTime, instant.toEpochMilli()));
if (!metrics.warnings().isEmpty()) {
Cursor warningsObject = root.setObject(deploymentMetricsWarningsField);
metrics.warnings().forEach((warning, count) -> warningsObject.setLong(warning.name(), count));
}
}
private void clusterInfoToSlime(Map<ClusterSpec.Id, ClusterInfo> clusters, Cursor object) {
Cursor root = object.setObject(clusterInfoField);
for (Map.Entry<ClusterSpec.Id, ClusterInfo> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterInfo info, Cursor object) {
object.setString(clusterInfoFlavorField, info.getFlavor());
object.setLong(clusterInfoCostField, info.getFlavorCost());
object.setDouble(clusterInfoCpuField, info.getFlavorCPU());
object.setDouble(clusterInfoMemField, info.getFlavorMem());
object.setDouble(clusterInfoDiskField, info.getFlavorDisk());
object.setString(clusterInfoTypeField, info.getClusterType().name());
Cursor array = object.setArray(clusterInfoHostnamesField);
for (String host : info.getHostnames()) {
array.addString(host);
}
}
private void zoneIdToSlime(ZoneId zone, Cursor object) {
object.setString(environmentField, zone.environment().value());
object.setString(regionField, zone.region().value());
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if (applicationVersion.buildNumber().isPresent() && applicationVersion.source().isPresent()) {
object.setLong(applicationBuildNumberField, applicationVersion.buildNumber().getAsLong());
toSlime(applicationVersion.source().get(), object.setObject(sourceRevisionField));
applicationVersion.authorEmail().ifPresent(email -> object.setString(authorEmailField, email));
applicationVersion.compileVersion().ifPresent(version -> object.setString(compileVersionField, version.toString()));
applicationVersion.buildTime().ifPresent(time -> object.setLong(buildTimeField, time.toEpochMilli()));
}
}
private void toSlime(SourceRevision sourceRevision, Cursor object) {
object.setString(repositoryField, sourceRevision.repository());
object.setString(branchField, sourceRevision.branch());
object.setString(commitField, sourceRevision.commit());
}
private void toSlime(DeploymentJobs deploymentJobs, Cursor cursor) {
jobStatusToSlime(deploymentJobs.jobStatus().values(), cursor.setArray(jobStatusField));
}
private void jobStatusToSlime(Collection<JobStatus> jobStatuses, Cursor jobStatusArray) {
for (JobStatus jobStatus : jobStatuses)
toSlime(jobStatus, jobStatusArray.addObject());
}
private void toSlime(JobStatus jobStatus, Cursor object) {
object.setString(jobTypeField, jobStatus.type().jobName());
if (jobStatus.jobError().isPresent())
object.setString(errorField, jobStatus.jobError().get().name());
jobStatus.lastTriggered().ifPresent(run -> jobRunToSlime(run, object, lastTriggeredField));
jobStatus.lastCompleted().ifPresent(run -> jobRunToSlime(run, object, lastCompletedField));
jobStatus.lastSuccess().ifPresent(run -> jobRunToSlime(run, object, lastSuccessField));
jobStatus.firstFailing().ifPresent(run -> jobRunToSlime(run, object, firstFailingField));
jobStatus.pausedUntil().ifPresent(until -> object.setLong(pausedUntilField, until));
}
private void jobRunToSlime(JobStatus.JobRun jobRun, Cursor parent, String jobRunObjectName) {
Cursor object = parent.setObject(jobRunObjectName);
object.setLong(jobRunIdField, jobRun.id());
object.setString(versionField, jobRun.platform().toString());
toSlime(jobRun.application(), object.setObject(revisionField));
jobRun.sourcePlatform().ifPresent(version -> object.setString(sourceVersionField, version.toString()));
jobRun.sourceApplication().ifPresent(version -> toSlime(version, object.setObject(sourceApplicationField)));
object.setString(reasonField, jobRun.reason());
object.setLong(atField, jobRun.at().toEpochMilli());
}
private void toSlime(Change deploying, Cursor parentObject, String fieldName) {
if (deploying.isEmpty()) return;
Cursor object = parentObject.setObject(fieldName);
if (deploying.platform().isPresent())
object.setString(versionField, deploying.platform().get().toString());
if (deploying.application().isPresent())
toSlime(deploying.application().get(), object);
if (deploying.isPinned())
object.setBool(pinnedField, true);
}
private void toSlime(RotationStatus status, Cursor array) {
status.asMap().forEach((rotationId, zoneStatus) -> {
Cursor rotationObject = array.addObject();
rotationObject.setString(rotationIdField, rotationId.asString());
Cursor statusArray = rotationObject.setArray(statusField);
zoneStatus.forEach((zone, state) -> {
Cursor statusObject = statusArray.addObject();
zoneIdToSlime(zone, statusObject);
statusObject.setString(rotationStateField, state.name());
});
});
}
private void assignedRotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) {
var rotationsArray = parent.setArray(fieldName);
for (var rotation : rotations) {
var object = rotationsArray.addObject();
object.setString(assignedRotationEndpointField, rotation.endpointId().id());
object.setString(assignedRotationRotationField, rotation.rotationId().asString());
object.setString(assignedRotationClusterField, rotation.clusterId().value());
}
}
public Application fromSlime(Slime slime) {
Inspector root = slime.get();
TenantAndApplicationId id = TenantAndApplicationId.fromSerialized(root.field(idField).asString());
Instant createdAt = Instant.ofEpochMilli(root.field(createdAtField).asLong());
DeploymentSpec deploymentSpec = DeploymentSpec.fromXml(root.field(deploymentSpecField).asString(), false);
ValidationOverrides validationOverrides = ValidationOverrides.fromXml(root.field(validationOverridesField).asString());
Change deploying = changeFromSlime(root.field(deployingField));
Change outstandingChange = changeFromSlime(root.field(outstandingChangeField));
Optional<IssueId> deploymentIssueId = Serializers.optionalString(root.field(deploymentIssueField)).map(IssueId::from);
Optional<IssueId> ownershipIssueId = Serializers.optionalString(root.field(ownershipIssueIdField)).map(IssueId::from);
Optional<User> owner = Serializers.optionalString(root.field(ownerField)).map(User::from);
OptionalInt majorVersion = Serializers.optionalInteger(root.field(majorVersionField));
ApplicationMetrics metrics = new ApplicationMetrics(root.field(queryQualityField).asDouble(),
root.field(writeQualityField).asDouble());
Set<PublicKey> deployKeys = deployKeysFromSlime(root.field(pemDeployKeysField));
List<Instance> instances = instancesFromSlime(id, deploymentSpec, root.field(instancesField));
OptionalLong projectId = Serializers.optionalLong(root.field(projectIdField));
Optional<ApplicationVersion> latestVersion = latestVersionFromSlimeWithFallback(root.field(latestVersionField), instances);
boolean builtInternally = root.field(builtInternallyField).asBool();
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
deployKeys, projectId, builtInternally, latestVersion, instances);
}
private List<Instance> instancesFromSlime(TenantAndApplicationId id, DeploymentSpec deploymentSpec, Inspector field) {
List<Instance> instances = new ArrayList<>();
field.traverse((ArrayTraverser) (name, object) -> {
InstanceName instanceName = InstanceName.from(object.field(instanceNameField).asString());
List<Deployment> deployments = deploymentsFromSlime(object.field(deploymentsField));
DeploymentJobs deploymentJobs = deploymentJobsFromSlime(object.field(deploymentJobsField));
List<AssignedRotation> assignedRotations = assignedRotationsFromSlime(deploymentSpec, object);
RotationStatus rotationStatus = rotationStatusFromSlime(object);
instances.add(new Instance(id.instance(instanceName),
deployments,
deploymentJobs,
assignedRotations,
rotationStatus));
});
return instances;
}
private Set<PublicKey> deployKeysFromSlime(Inspector array) {
Set<PublicKey> keys = new LinkedHashSet<>();
array.traverse((ArrayTraverser) (__, key) -> keys.add(KeyUtils.fromPemEncodedPublicKey(key.asString())));
return keys;
}
private List<Deployment> deploymentsFromSlime(Inspector array) {
List<Deployment> deployments = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> deployments.add(deploymentFromSlime(item)));
return deployments;
}
private Deployment deploymentFromSlime(Inspector deploymentObject) {
return new Deployment(zoneIdFromSlime(deploymentObject.field(zoneField)),
applicationVersionFromSlime(deploymentObject.field(applicationPackageRevisionField)),
Version.fromString(deploymentObject.field(versionField).asString()),
Instant.ofEpochMilli(deploymentObject.field(deployTimeField).asLong()),
clusterInfoMapFromSlime(deploymentObject.field(clusterInfoField)),
deploymentMetricsFromSlime(deploymentObject.field(deploymentMetricsField)),
DeploymentActivity.create(Serializers.optionalInstant(deploymentObject.field(lastQueriedField)),
Serializers.optionalInstant(deploymentObject.field(lastWrittenField)),
Serializers.optionalDouble(deploymentObject.field(lastQueriesPerSecondField)),
Serializers.optionalDouble(deploymentObject.field(lastWritesPerSecondField))));
}
private DeploymentMetrics deploymentMetricsFromSlime(Inspector object) {
Optional<Instant> instant = object.field(deploymentMetricsUpdateTime).valid() ?
Optional.of(Instant.ofEpochMilli(object.field(deploymentMetricsUpdateTime).asLong())) :
Optional.empty();
return new DeploymentMetrics(object.field(deploymentMetricsQPSField).asDouble(),
object.field(deploymentMetricsWPSField).asDouble(),
object.field(deploymentMetricsDocsField).asDouble(),
object.field(deploymentMetricsQueryLatencyField).asDouble(),
object.field(deploymentMetricsWriteLatencyField).asDouble(),
instant,
deploymentWarningsFrom(object.field(deploymentMetricsWarningsField)));
}
private Map<DeploymentMetrics.Warning, Integer> deploymentWarningsFrom(Inspector object) {
Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>();
object.traverse((ObjectTraverser) (name, value) -> warnings.put(DeploymentMetrics.Warning.valueOf(name),
(int) value.asLong()));
return Collections.unmodifiableMap(warnings);
}
private RotationStatus rotationStatusFromSlime(Inspector parentObject) {
var object = parentObject.field(rotationStatusField);
var statusMap = new LinkedHashMap<RotationId, Map<ZoneId, RotationState>>();
object.traverse((ArrayTraverser) (idx, statusObject) -> statusMap.put(new RotationId(statusObject.field(rotationIdField).asString()),
singleRotationStatusFromSlime(statusObject.field(statusField))));
return RotationStatus.from(statusMap);
}
private Map<ZoneId, RotationState> singleRotationStatusFromSlime(Inspector object) {
if (!object.valid()) {
return Collections.emptyMap();
}
Map<ZoneId, RotationState> rotationStatus = new LinkedHashMap<>();
object.traverse((ArrayTraverser) (idx, statusObject) -> {
var zone = zoneIdFromSlime(statusObject);
var status = RotationState.valueOf(statusObject.field(rotationStateField).asString());
rotationStatus.put(zone, status);
});
return Collections.unmodifiableMap(rotationStatus);
}
private Map<ClusterSpec.Id, ClusterInfo> clusterInfoMapFromSlime (Inspector object) {
Map<ClusterSpec.Id, ClusterInfo> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterInfoFromSlime(value)));
return map;
}
private ClusterInfo clusterInfoFromSlime(Inspector inspector) {
String flavor = inspector.field(clusterInfoFlavorField).asString();
int cost = (int)inspector.field(clusterInfoCostField).asLong();
String type = inspector.field(clusterInfoTypeField).asString();
double flavorCpu = inspector.field(clusterInfoCpuField).asDouble();
double flavorMem = inspector.field(clusterInfoMemField).asDouble();
double flavorDisk = inspector.field(clusterInfoDiskField).asDouble();
List<String> hostnames = new ArrayList<>();
inspector.field(clusterInfoHostnamesField).traverse((ArrayTraverser)(int index, Inspector value) -> hostnames.add(value.asString()));
return new ClusterInfo(flavor, cost, flavorCpu, flavorMem, flavorDisk, ClusterSpec.Type.from(type), hostnames);
}
private ZoneId zoneIdFromSlime(Inspector object) {
return ZoneId.from(object.field(environmentField).asString(), object.field(regionField).asString());
}
private ApplicationVersion applicationVersionFromSlime(Inspector object) {
if ( ! object.valid()) return ApplicationVersion.unknown;
OptionalLong applicationBuildNumber = Serializers.optionalLong(object.field(applicationBuildNumberField));
Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField));
if (sourceRevision.isEmpty() || applicationBuildNumber.isEmpty()) {
return ApplicationVersion.unknown;
}
Optional<String> authorEmail = Serializers.optionalString(object.field(authorEmailField));
Optional<Version> compileVersion = Serializers.optionalString(object.field(compileVersionField)).map(Version::fromString);
Optional<Instant> buildTime = Serializers.optionalInstant(object.field(buildTimeField));
if (authorEmail.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong());
if (compileVersion.isEmpty() || buildTime.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get());
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get(),
compileVersion.get(), buildTime.get());
}
private Optional<SourceRevision> sourceRevisionFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new SourceRevision(object.field(repositoryField).asString(),
object.field(branchField).asString(),
object.field(commitField).asString()));
}
private DeploymentJobs deploymentJobsFromSlime(Inspector object) {
List<JobStatus> jobStatusList = jobStatusListFromSlime(object.field(jobStatusField));
return new DeploymentJobs(jobStatusList);
}
private Change changeFromSlime(Inspector object) {
if ( ! object.valid()) return Change.empty();
Inspector versionFieldValue = object.field(versionField);
Change change = Change.empty();
if (versionFieldValue.valid())
change = Change.of(Version.fromString(versionFieldValue.asString()));
if (object.field(applicationBuildNumberField).valid())
change = change.with(applicationVersionFromSlime(object));
if (object.field(pinnedField).asBool())
change = change.withPin();
return change;
}
private List<JobStatus> jobStatusListFromSlime(Inspector array) {
List<JobStatus> jobStatusList = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> jobStatusFromSlime(item).ifPresent(jobStatusList::add));
return jobStatusList;
}
private Optional<JobStatus> jobStatusFromSlime(Inspector object) {
Optional<JobType> jobType =
JobType.fromOptionalJobName(object.field(jobTypeField).asString());
if (jobType.isEmpty()) return Optional.empty();
Optional<JobError> jobError = Optional.empty();
if (object.field(errorField).valid())
jobError = Optional.of(JobError.valueOf(object.field(errorField).asString()));
return Optional.of(new JobStatus(jobType.get(),
jobError,
jobRunFromSlime(object.field(lastTriggeredField)),
jobRunFromSlime(object.field(lastCompletedField)),
jobRunFromSlime(object.field(firstFailingField)),
jobRunFromSlime(object.field(lastSuccessField)),
Serializers.optionalLong(object.field(pausedUntilField))));
}
private Optional<JobStatus.JobRun> jobRunFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new JobStatus.JobRun(object.field(jobRunIdField).asLong(),
new Version(object.field(versionField).asString()),
applicationVersionFromSlime(object.field(revisionField)),
Serializers.optionalString(object.field(sourceVersionField)).map(Version::fromString),
Optional.of(object.field(sourceApplicationField)).filter(Inspector::valid).map(this::applicationVersionFromSlime),
object.field(reasonField).asString(),
Instant.ofEpochMilli(object.field(atField).asLong())));
}
private List<AssignedRotation> assignedRotationsFromSlime(DeploymentSpec deploymentSpec, Inspector root) {
var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>();
root.field(assignedRotationsField).traverse((ArrayTraverser) (idx, inspector) -> {
var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString());
var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString());
var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString());
var regions = deploymentSpec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
} |
Thanks. | private void reportDeploymentMetrics() {
List<Application> applications = ApplicationList.from(controller().applications().asList())
.withProductionDeployment().asList().stream()
.collect(Collectors.toUnmodifiableList());
List<Instance> instances = applications.stream()
.flatMap(application -> application.instances().values().stream())
.collect(Collectors.toUnmodifiableList());
metric.set(DEPLOYMENT_FAIL_METRIC, deploymentFailRatio(instances) * 100, metric.createContext(Map.of()));
averageDeploymentDurations(instances, clock.instant()).forEach((application, duration) -> {
metric.set(DEPLOYMENT_AVERAGE_DURATION, duration.getSeconds(), metric.createContext(dimensions(application)));
});
deploymentsFailingUpgrade(instances).forEach((application, failingJobs) -> {
metric.set(DEPLOYMENT_FAILING_UPGRADES, failingJobs, metric.createContext(dimensions(application)));
});
deploymentWarnings(instances).forEach((application, warnings) -> {
metric.set(DEPLOYMENT_WARNINGS, warnings, metric.createContext(dimensions(application)));
});
for (Application application : applications)
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()))));
} | .flatMap(ApplicationVersion::buildTime) | private void reportDeploymentMetrics() {
List<Application> applications = ApplicationList.from(controller().applications().asList())
.withProductionDeployment().asList().stream()
.collect(Collectors.toUnmodifiableList());
List<Instance> instances = applications.stream()
.flatMap(application -> application.instances().values().stream())
.collect(Collectors.toUnmodifiableList());
metric.set(DEPLOYMENT_FAIL_METRIC, deploymentFailRatio(instances) * 100, metric.createContext(Map.of()));
averageDeploymentDurations(instances, clock.instant()).forEach((application, duration) -> {
metric.set(DEPLOYMENT_AVERAGE_DURATION, duration.getSeconds(), metric.createContext(dimensions(application)));
});
deploymentsFailingUpgrade(instances).forEach((application, failingJobs) -> {
metric.set(DEPLOYMENT_FAILING_UPGRADES, failingJobs, metric.createContext(dimensions(application)));
});
deploymentWarnings(instances).forEach((application, warnings) -> {
metric.set(DEPLOYMENT_WARNINGS, warnings, metric.createContext(dimensions(application)));
});
for (Application application : applications)
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()))));
} | class MetricsReporter extends Maintainer {
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 NODES_FAILING_SYSTEM_UPGRADE = "deployment.nodesFailingSystemUpgrade";
public static final String REMAINING_ROTATIONS = "remaining_rotations";
public static final String NAME_SERVICE_REQUESTS_QUEUED = "dns.queuedRequests";
private static final Duration NODE_UPGRADE_TIMEOUT = Duration.ofHours(1);
private final Metric metric;
private final Clock clock;
public MetricsReporter(Controller controller, Metric metric, JobControl jobControl) {
super(controller, Duration.ofMinutes(1), jobControl);
this.metric = metric;
this.clock = controller.clock();
}
@Override
public void maintain() {
reportDeploymentMetrics();
reportRemainingRotations();
reportQueuedNameServiceRequests();
reportNodesFailingSystemUpgrade();
}
private void reportRemainingRotations() {
try (RotationLock lock = controller().applications().rotationRepository().lock()) {
int availableRotations = controller().applications().rotationRepository().availableRotations(lock).size();
metric.set(REMAINING_ROTATIONS, availableRotations, metric.createContext(Map.of()));
}
}
private void reportQueuedNameServiceRequests() {
metric.set(NAME_SERVICE_REQUESTS_QUEUED, controller().curator().readNameServiceQueue().requests().size(),
metric.createContext(Map.of()));
}
private void reportNodesFailingSystemUpgrade() {
metric.set(NODES_FAILING_SYSTEM_UPGRADE, nodesFailingSystemUpgrade(), metric.createContext(Map.of()));
}
private int nodesFailingSystemUpgrade() {
if (!controller().versionStatus().isUpgrading()) return 0;
var nodesFailingUpgrade = 0;
var acceptableInstant = clock.instant().minus(NODE_UPGRADE_TIMEOUT);
for (var vespaVersion : controller().versionStatus().versions()) {
if (vespaVersion.confidence() == VespaVersion.Confidence.broken) continue;
for (var nodeVersion : vespaVersion.nodeVersions().asMap().values()) {
if (!nodeVersion.changing()) continue;
if (nodeVersion.changedAt().isBefore(acceptableInstant)) nodesFailingUpgrade++;
}
}
return nodesFailingUpgrade;
}
private static double deploymentFailRatio(List<Instance> instances) {
return instances.stream()
.mapToInt(instance -> instance.deploymentJobs().hasFailures() ? 1 : 0)
.average().orElse(0);
}
private static Map<ApplicationId, Duration> averageDeploymentDurations(List<Instance> instances, Instant now) {
return instances.stream()
.collect(Collectors.toMap(Instance::id,
instance -> averageDeploymentDuration(instance, now)));
}
private static Map<ApplicationId, Integer> deploymentsFailingUpgrade(List<Instance> instances) {
return instances.stream()
.collect(Collectors.toMap(Instance::id, MetricsReporter::deploymentsFailingUpgrade));
}
private static int deploymentsFailingUpgrade(Instance instance) {
return JobList.from(instance).upgrading().failing().size();
}
private static Duration averageDeploymentDuration(Instance instance, Instant now) {
List<Duration> jobDurations = instance.deploymentJobs().jobStatus().values().stream()
.filter(status -> status.lastTriggered().isPresent())
.map(status -> {
Instant triggeredAt = status.lastTriggered().get().at();
Instant runningUntil = status.lastCompleted()
.map(JobStatus.JobRun::at)
.filter(at -> at.isAfter(triggeredAt))
.orElse(now);
return Duration.between(triggeredAt, runningUntil);
})
.collect(Collectors.toList());
return jobDurations.stream()
.reduce(Duration::plus)
.map(totalDuration -> totalDuration.dividedBy(jobDurations.size()))
.orElse(Duration.ZERO);
}
private static Map<ApplicationId, Integer> deploymentWarnings(List<Instance> instances) {
return instances.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());
}
} | class MetricsReporter extends Maintainer {
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 NODES_FAILING_SYSTEM_UPGRADE = "deployment.nodesFailingSystemUpgrade";
public static final String REMAINING_ROTATIONS = "remaining_rotations";
public static final String NAME_SERVICE_REQUESTS_QUEUED = "dns.queuedRequests";
private static final Duration NODE_UPGRADE_TIMEOUT = Duration.ofHours(1);
private final Metric metric;
private final Clock clock;
public MetricsReporter(Controller controller, Metric metric, JobControl jobControl) {
super(controller, Duration.ofMinutes(1), jobControl);
this.metric = metric;
this.clock = controller.clock();
}
@Override
public void maintain() {
reportDeploymentMetrics();
reportRemainingRotations();
reportQueuedNameServiceRequests();
reportNodesFailingSystemUpgrade();
}
private void reportRemainingRotations() {
try (RotationLock lock = controller().applications().rotationRepository().lock()) {
int availableRotations = controller().applications().rotationRepository().availableRotations(lock).size();
metric.set(REMAINING_ROTATIONS, availableRotations, metric.createContext(Map.of()));
}
}
private void reportQueuedNameServiceRequests() {
metric.set(NAME_SERVICE_REQUESTS_QUEUED, controller().curator().readNameServiceQueue().requests().size(),
metric.createContext(Map.of()));
}
private void reportNodesFailingSystemUpgrade() {
metric.set(NODES_FAILING_SYSTEM_UPGRADE, nodesFailingSystemUpgrade(), metric.createContext(Map.of()));
}
private int nodesFailingSystemUpgrade() {
if (!controller().versionStatus().isUpgrading()) return 0;
var nodesFailingUpgrade = 0;
var acceptableInstant = clock.instant().minus(NODE_UPGRADE_TIMEOUT);
for (var vespaVersion : controller().versionStatus().versions()) {
if (vespaVersion.confidence() == VespaVersion.Confidence.broken) continue;
for (var nodeVersion : vespaVersion.nodeVersions().asMap().values()) {
if (!nodeVersion.changing()) continue;
if (nodeVersion.changedAt().isBefore(acceptableInstant)) nodesFailingUpgrade++;
}
}
return nodesFailingUpgrade;
}
private static double deploymentFailRatio(List<Instance> instances) {
return instances.stream()
.mapToInt(instance -> instance.deploymentJobs().hasFailures() ? 1 : 0)
.average().orElse(0);
}
private static Map<ApplicationId, Duration> averageDeploymentDurations(List<Instance> instances, Instant now) {
return instances.stream()
.collect(Collectors.toMap(Instance::id,
instance -> averageDeploymentDuration(instance, now)));
}
private static Map<ApplicationId, Integer> deploymentsFailingUpgrade(List<Instance> instances) {
return instances.stream()
.collect(Collectors.toMap(Instance::id, MetricsReporter::deploymentsFailingUpgrade));
}
private static int deploymentsFailingUpgrade(Instance instance) {
return JobList.from(instance).upgrading().failing().size();
}
private static Duration averageDeploymentDuration(Instance instance, Instant now) {
List<Duration> jobDurations = instance.deploymentJobs().jobStatus().values().stream()
.filter(status -> status.lastTriggered().isPresent())
.map(status -> {
Instant triggeredAt = status.lastTriggered().get().at();
Instant runningUntil = status.lastCompleted()
.map(JobStatus.JobRun::at)
.filter(at -> at.isAfter(triggeredAt))
.orElse(now);
return Duration.between(triggeredAt, runningUntil);
})
.collect(Collectors.toList());
return jobDurations.stream()
.reduce(Duration::plus)
.map(totalDuration -> totalDuration.dividedBy(jobDurations.size()))
.orElse(Duration.ZERO);
}
private static Map<ApplicationId, Integer> deploymentWarnings(List<Instance> instances) {
return instances.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());
}
} |
```suggestion // DELETE an application is available to developers. ``` | public void testUserManagement() {
ContainerTester tester = new ContainerTester(container, responseFiles);
assertEquals(SystemName.Public, tester.controller().system());
Set<Role> operator = Set.of(Role.hostedOperator());
ApplicationId id = ApplicationId.from("my-tenant", "my-app", "default");
tester.assertResponse(request("/application/v4/"),
accessDenied, 403);
tester.assertResponse(request("/application/v4/tenant")
.roles(operator),
"[]");
tester.assertResponse(request("/api/application/v4/tenant")
.roles(operator),
"[]");
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.data("{\"token\":\"hello\"}"),
accessDenied, 403);
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.roles(operator)
.user("administrator@tenant")
.data("{\"token\":\"hello\"}"),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/user/", PUT)
.roles(operator),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"Not authenticated or not a user.\"}", 403);
tester.assertResponse(request("/user/v1/"),
accessDenied, 403);
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
.roles(Set.of(Role.administrator(id.tenant())))
.data("{\"user\":\"evil@evil\",\"roleName\":\"hostedOperator\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'hostedOperator'.\"}", 400);
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
.roles(Set.of(Role.administrator(id.tenant())))
.data("{\"user\":\"developer@tenant\",\"roleName\":\"developer\"}"),
"{\"message\":\"user 'developer@tenant' is now a member of role 'developer' of 'my-tenant'\"}");
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"user\":\"developer@tenant\",\"roleName\":\"administrator\"}"),
accessDenied, 403);
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app", POST)
.roles(Set.of(Role.administrator(TenantName.from("my-tenant"))))
.data("{\"user\":\"headless@app\",\"roleName\":\"headless\"}"),
"{\"error-code\":\"INTERNAL_SERVER_ERROR\",\"message\":\"NullPointerException\"}", 500);
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app", POST)
.user("developer@tenant")
.roles(Set.of(Role.developer(id.tenant()))),
new File("application-created.json"));
tester.assertResponse(request("/application/v4/tenant/other-tenant/application/my-app", POST)
.roles(Set.of(Role.administrator(id.tenant()))),
accessDenied, 403);
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app", POST)
.roles(Set.of(Role.hostedOperator()))
.data("{\"user\":\"developer@app\",\"roleName\":\"developer\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'developer'.\"}", 400);
tester.assertResponse(request("/user/v1/tenant/my-tenant")
.roles(Set.of(Role.reader(id.tenant()))),
new File("tenant-roles.json"));
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app")
.roles(Set.of(Role.administrator(id.tenant()))),
new File("application-roles.json"));
tester.assertResponse(request("/api/user/v1/tenant/my-tenant/application/my-app")
.roles(Set.of(Role.administrator(id.tenant()))),
new File("application-roles.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app/key", POST)
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
new File("first-deploy-key.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
.user("joe@dev")
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
new File("first-developer-key.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
.user("operator@tenant")
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Key "+ quotedPemPublicKey + " is already owned by joe@dev\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
.user("developer@tenant")
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + otherPemPublicKey + "\"}"),
new File("both-developer-keys.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/")
.roles(Set.of(Role.reader(id.tenant()))),
new File("tenant-with-keys.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", DELETE)
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
new File("second-developer-key.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app", DELETE)
.roles(Set.of(Role.developer(id.tenant()))),
"{\"message\":\"Deleted application my-tenant.my-app\"}");
tester.assertResponse(request("/user/v1/tenant/my-tenant", DELETE)
.roles(Set.of(Role.administrator(id.tenant())))
.data("{\"user\":\"developer@tenant\",\"roleName\":\"developer\"}"),
"{\"message\":\"user 'developer@tenant' is no longer a member of role 'developer' of 'my-tenant'\"}");
tester.assertResponse(request("/user/v1/tenant/my-tenant", DELETE)
.roles(operator)
.data("{\"user\":\"administrator@tenant\",\"roleName\":\"administrator\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Can't remove the last administrator of a tenant.\"}", 400);
tester.assertResponse(request("/application/v4/tenant/my-tenant", DELETE)
.roles(Set.of(Role.tenantOwner(id.tenant()))),
new File("tenant-without-applications.json"));
} | public void testUserManagement() {
ContainerTester tester = new ContainerTester(container, responseFiles);
assertEquals(SystemName.Public, tester.controller().system());
Set<Role> operator = Set.of(Role.hostedOperator());
ApplicationId id = ApplicationId.from("my-tenant", "my-app", "default");
tester.assertResponse(request("/application/v4/"),
accessDenied, 403);
tester.assertResponse(request("/application/v4/tenant")
.roles(operator),
"[]");
tester.assertResponse(request("/api/application/v4/tenant")
.roles(operator),
"[]");
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.data("{\"token\":\"hello\"}"),
accessDenied, 403);
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.roles(operator)
.user("administrator@tenant")
.data("{\"token\":\"hello\"}"),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/user/", PUT)
.roles(operator),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"Not authenticated or not a user.\"}", 403);
tester.assertResponse(request("/user/v1/"),
accessDenied, 403);
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
.roles(Set.of(Role.administrator(id.tenant())))
.data("{\"user\":\"evil@evil\",\"roleName\":\"hostedOperator\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'hostedOperator'.\"}", 400);
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
.roles(Set.of(Role.administrator(id.tenant())))
.data("{\"user\":\"developer@tenant\",\"roleName\":\"developer\"}"),
"{\"message\":\"user 'developer@tenant' is now a member of role 'developer' of 'my-tenant'\"}");
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"user\":\"developer@tenant\",\"roleName\":\"administrator\"}"),
accessDenied, 403);
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app", POST)
.roles(Set.of(Role.administrator(TenantName.from("my-tenant"))))
.data("{\"user\":\"headless@app\",\"roleName\":\"headless\"}"),
"{\"error-code\":\"INTERNAL_SERVER_ERROR\",\"message\":\"NullPointerException\"}", 500);
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app", POST)
.user("developer@tenant")
.roles(Set.of(Role.developer(id.tenant()))),
new File("application-created.json"));
tester.assertResponse(request("/application/v4/tenant/other-tenant/application/my-app", POST)
.roles(Set.of(Role.administrator(id.tenant()))),
accessDenied, 403);
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app", POST)
.roles(Set.of(Role.hostedOperator()))
.data("{\"user\":\"developer@app\",\"roleName\":\"developer\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'developer'.\"}", 400);
tester.assertResponse(request("/user/v1/tenant/my-tenant")
.roles(Set.of(Role.reader(id.tenant()))),
new File("tenant-roles.json"));
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app")
.roles(Set.of(Role.administrator(id.tenant()))),
new File("application-roles.json"));
tester.assertResponse(request("/api/user/v1/tenant/my-tenant/application/my-app")
.roles(Set.of(Role.administrator(id.tenant()))),
new File("application-roles.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app/key", POST)
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
new File("first-deploy-key.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
.user("joe@dev")
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
new File("first-developer-key.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
.user("operator@tenant")
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Key "+ quotedPemPublicKey + " is already owned by joe@dev\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
.user("developer@tenant")
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + otherPemPublicKey + "\"}"),
new File("both-developer-keys.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/")
.roles(Set.of(Role.reader(id.tenant()))),
new File("tenant-with-keys.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", DELETE)
.roles(Set.of(Role.developer(id.tenant())))
.data("{\"key\":\"" + pemPublicKey + "\"}"),
new File("second-developer-key.json"));
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app", DELETE)
.roles(Set.of(Role.developer(id.tenant()))),
"{\"message\":\"Deleted application my-tenant.my-app\"}");
tester.assertResponse(request("/user/v1/tenant/my-tenant", DELETE)
.roles(Set.of(Role.administrator(id.tenant())))
.data("{\"user\":\"developer@tenant\",\"roleName\":\"developer\"}"),
"{\"message\":\"user 'developer@tenant' is no longer a member of role 'developer' of 'my-tenant'\"}");
tester.assertResponse(request("/user/v1/tenant/my-tenant", DELETE)
.roles(operator)
.data("{\"user\":\"administrator@tenant\",\"roleName\":\"administrator\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Can't remove the last administrator of a tenant.\"}", 400);
tester.assertResponse(request("/application/v4/tenant/my-tenant", DELETE)
.roles(Set.of(Role.tenantOwner(id.tenant()))),
new File("tenant-without-applications.json"));
} | class UserApiTest extends ControllerContainerCloudTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String otherPemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFELzPyinTfQ/sZnTmRp5E4Ve/sbE\n" +
"pDhJeqczkyFcT2PysJ5sZwm7rKPEeXDOhzTPCyRvbUqc2SGdWbKUGGa/Yw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final String otherQuotedPemPublicKey = otherPemPublicKey.replaceAll("\\n", "\\\\n");
@Test
} | class UserApiTest extends ControllerContainerCloudTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String otherPemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFELzPyinTfQ/sZnTmRp5E4Ve/sbE\n" +
"pDhJeqczkyFcT2PysJ5sZwm7rKPEeXDOhzTPCyRvbUqc2SGdWbKUGGa/Yw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final String otherQuotedPemPublicKey = otherPemPublicKey.replaceAll("\\n", "\\\\n");
@Test
} | |
And here we need to update the test application’s deployment.xml | private LockedApplication withoutDeletedDeployments(LockedApplication application, InstanceName instance) {
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
List<Deployment> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.filter(deployment -> ! deploymentSpec.includes(deployment.zone().environment(),
Optional.of(deployment.zone().region())))
.collect(Collectors.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(deployment -> deployment.zone().region().value())
.collect(Collectors.joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
for (Deployment deployment : deploymentsToRemove)
application = deactivate(application, instance, deployment.zone());
return application;
} | .filter(deployment -> ! deploymentSpec.includes(deployment.zone().environment(), | private LockedApplication withoutDeletedDeployments(LockedApplication application, InstanceName instance) {
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
List<Deployment> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.filter(deployment -> ! deploymentSpec.includes(deployment.zone().environment(),
Optional.of(deployment.zone().region())))
.collect(Collectors.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(deployment -> deployment.zone().region().value())
.collect(Collectors.joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
for (Deployment deployment : deploymentsToRemove)
application = deactivate(application, instance, deployment.zone());
return application;
} | 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 RotationRepository rotationRepository;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final RoutingGenerator routingGenerator;
private final RoutingPolicies routingPolicies;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final BooleanFlag provisionApplicationCertificate;
private final DeploymentSpecValidator deploymentSpecValidator;
ApplicationController(Controller controller, CuratorDb curator,
AccessControl accessControl, RotationsConfig rotationsConfig,
Clock clock) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.routingGenerator = controller.serviceRegistry().routingGenerator();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
routingPolicies = new RoutingPolicies(controller);
rotationRepository = new RotationRepository(rotationsConfig, this, curator);
deploymentTrigger = new DeploymentTrigger(controller, controller.serviceRegistry().buildService(), clock);
provisionApplicationCertificate = Flags.PROVISION_APPLICATION_CERTIFICATE.bindTo(controller.flagSource());
deploymentSpecValidator = new DeploymentSpecValidator(controller);
Once.after(Duration.ofMinutes(1), () -> {
Instant start = clock.instant();
int count = 0;
for (Application application : curator.readApplications()) {
lockApplicationIfPresent(application.id(), this::store);
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 application with the given id, or null if it is not present */
public Optional<Application> getApplication(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id));
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(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();
}
/** 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(ApplicationId id, Iterable<ZoneId> zones) {
ImmutableMap.Builder<ZoneId, List<String>> clusters = ImmutableMap.builder();
for (ZoneId zone : zones)
clusters.put(zone, ImmutableList.copyOf(configServer.getContentClusters(new DeploymentId(id, zone))));
return clusters.build();
}
/** 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());
}
/** Change the global endpoint status for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
findGlobalEndpoint(deployment).map(endpoint -> {
try {
configServer.setGlobalRotationStatus(deployment, endpoint.upstreamName(), status);
return endpoint;
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + deployment, e);
}
}).orElseThrow(() -> new IllegalArgumentException("No global endpoint exists for " + deployment));
}
/** Get global endpoint status for given deployment */
public Map<RoutingEndpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
return findGlobalEndpoint(deployment).map(endpoint -> {
try {
EndpointStatus status = configServer.getGlobalRotationStatus(deployment, endpoint.upstreamName());
return Map.of(endpoint, status);
} catch (Exception e) {
throw new RuntimeException("Failed to get rotation status of " + deployment, e);
}
}).orElseGet(Collections::emptyMap);
}
/** Find the global endpoint of given deployment, if any */
private Optional<RoutingEndpoint> findGlobalEndpoint(DeploymentId deployment) {
return routingGenerator.endpoints(deployment).stream()
.filter(RoutingEndpoint::isGlobal)
.findFirst();
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public Application createApplication(TenantAndApplicationId id, Optional<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());
Optional<Tenant> tenant = controller.tenants().get(id.tenant());
if (tenant.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
if (tenant.get().type() != Tenant.Type.user) {
if (credentials.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': No credentials provided");
accessControl.createApplication(id, credentials.get());
}
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) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
lockApplicationOrThrow(TenantAndApplicationId.from(id), 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");
store(application.withNewInstance(id.instance()));
log.info("Created " + id);
});
}
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options);
}
/** Deploys an application. If the application does not exist it is created. */
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 ( getApplication(applicationId).isEmpty()
&& controller.tenants().require(instanceId.tenant()).type() == Tenant.Type.user)
createApplication(applicationId, Optional.empty());
if (getInstance(instanceId).isEmpty())
createInstance(instanceId);
try (Lock deploymentLock = lockForDeployment(instanceId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<ApplicationCertificate> applicationCertificate;
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 + "."));
Optional<JobStatus> job = Optional.ofNullable(application.get().require(instance).deploymentJobs().jobStatus().get(jobType));
if ( job.isEmpty()
|| job.get().lastTriggered().isEmpty()
|| job.get().lastCompleted().isPresent() && job.get().lastCompleted().get().at().isAfter(job.get().lastTriggered().get().at()))
return unexpectedDeployment(instanceId, zone);
JobRun triggered = job.get().lastTriggered().get();
platformVersion = preferOldestVersion ? triggered.sourcePlatform().orElse(triggered.platform())
: triggered.platform();
applicationVersion = preferOldestVersion ? triggered.sourceApplication().orElse(triggered.application())
: triggered.application();
applicationPackage = getApplicationPackage(instanceId, application.get().internal(), applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, instanceId, jobType);
validateRun(application.get(), instance, zone, platformVersion, applicationVersion);
}
if (zone.environment().isProduction())
application = withRotation(application, instance);
endpoints = registerEndpointsInDns(application.get().deploymentSpec(), application.get().require(instanceId.instance()), zone);
if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
applicationCertificate = getApplicationCertificate(application.get().require(instance));
} else {
applicationCertificate = Optional.empty();
}
if ( ! preferOldestVersion
&& ! application.get().internal()
&& ! zone.environment().isManuallyDeployed()) {
storeWithUpdatedConfig(application, applicationPackage);
}
}
options = withVersion(platformVersion, options);
ActivateResult result = deploy(instanceId, applicationPackage, zone, options, endpoints,
applicationCertificate.orElse(null));
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, boolean internal, ApplicationVersion version) {
try {
return internal
? new ApplicationPackage(applicationStore.get(id, version))
: new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()));
}
catch (RuntimeException e) {
try {
log.info("Fetching application package for " + id + " from alternate repository; it is now deployed "
+ (internal ? "internally" : "externally") + "\nException was: " + Exceptions.toMessageString(e));
return internal
? new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()))
: new ApplicationPackage(applicationStore.get(id, version));
}
catch (RuntimeException s) {
e.addSuppressed(s);
throw e;
}
}
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public void storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
deploymentSpecValidator.validate(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
for (InstanceName instanceName : application.get().instances().keySet()) {
application = withoutDeletedDeployments(application, instanceName);
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
application = application.with(instanceName, instance -> withoutUnreferencedDeploymentJobs(deploymentSpec, instance));
}
store(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)
);
DeployOptions options = withVersion(version, DeployOptions.none());
return deploy(application.id(), applicationPackage, zone, options, Set.of(), /* No application cert */ null);
} 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, DeployOptions options) {
return deploy(tester.id(), applicationPackage, zone, options, Set.of(), /* No application cert for tester*/ null);
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, DeployOptions deployOptions, Set<ContainerEndpoint> endpoints,
ApplicationCertificate applicationCertificate) {
DeploymentId deploymentId = new DeploymentId(application, zone);
try {
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(deploymentId, deployOptions, Set.of(), endpoints, applicationCertificate, applicationPackage.zippedContent());
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
routingPolicies.refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
/** Makes sure the application has a global rotation, if eligible. */
private LockedApplication withRotation(LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(application.get().deploymentSpec(),
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
store(application);
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
private Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
var registerLegacyNames = deploymentSpec.globalServiceId().isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId())
.scope(Endpoint.Scope.global);
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
if (!registerLegacyNames) {
endpoints = endpoints.legacy(false);
}
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.asList().forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
private Optional<ApplicationCertificate> getApplicationCertificate(Instance instance) {
boolean provisionCertificate = provisionApplicationCertificate.with(FetchVector.Dimension.APPLICATION_ID,
instance.id().serializedForm()).value();
if (!provisionCertificate) {
return Optional.empty();
}
Optional<ApplicationCertificate> applicationCertificate = curator.readApplicationCertificate(instance.id());
if(applicationCertificate.isPresent())
return applicationCertificate;
ApplicationCertificate newCertificate = controller.serviceRegistry().applicationCertificateProvider().requestCaSignedCertificate(instance.id(), dnsNamesOf(instance.id()));
curator.writeApplicationCertificate(instance.id(), newCertificate);
return Optional.of(newCertificate);
}
/** Returns all valid DNS names of given application */
private List<String> dnsNamesOf(ApplicationId applicationId) {
List<String> endpointDnsNames = new ArrayList<>();
endpointDnsNames.add(Endpoint.createHashedCn(applicationId, controller.system()));
var globalDefaultEndpoint = Endpoint.of(applicationId).named(EndpointId.default_());
var rotationEndpoints = Endpoint.of(applicationId).wildcard();
var zoneLocalEndpoints = controller.zoneRegistry().zones().directlyRouted().zones().stream().flatMap(zone -> Stream.of(
Endpoint.of(applicationId).target(ClusterSpec.Id.from("default"), zone.getId()),
Endpoint.of(applicationId).wildcard(zone.getId())
));
Stream.concat(Stream.of(globalDefaultEndpoint, rotationEndpoints), zoneLocalEndpoints)
.map(Endpoint.EndpointBuilder::directRouting)
.map(endpoint -> endpoint.on(Endpoint.Port.tls()))
.map(endpointBuilder -> endpointBuilder.in(controller.system()))
.map(Endpoint::dnsName).forEach(endpointDnsNames::add);
return Collections.unmodifiableList(endpointDnsNames);
}
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 Instance withoutUnreferencedDeploymentJobs(DeploymentSpec deploymentSpec, Instance instance) {
for (JobType job : JobList.from(instance).production().mapToList(JobStatus::type)) {
ZoneId zone = job.zone(controller.system());
if (deploymentSpec.includes(zone.environment(), Optional.of(zone.region())))
continue;
instance = instance.withoutDeploymentJob(job);
}
return instance;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/** Returns the endpoints of the deployment, or empty if the request fails */
public List<URI> getDeploymentEndpoints(DeploymentId deploymentId) {
if ( ! getInstance(deploymentId.applicationId())
.map(application -> application.deployments().containsKey(deploymentId.zoneId()))
.orElse(deploymentId.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", deploymentId.toString());
try {
return ImmutableList.copyOf(routingGenerator.endpoints(deploymentId).stream()
.map(RoutingEndpoint::endpoint)
.map(URI::create)
.iterator());
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e);
return Collections.emptyList();
}
}
/** Returns the non-empty endpoints per cluster in the given deployment, or empty if endpoints can't be found. */
public Map<ClusterSpec.Id, URI> clusterEndpoints(DeploymentId id) {
if ( ! getInstance(id.applicationId())
.map(application -> application.deployments().containsKey(id.zoneId()))
.orElse(id.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", id.toString());
try {
var endpoints = routingGenerator.clusterEndpoints(id);
if ( ! endpoints.isEmpty())
return endpoints;
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + id, e);
}
return routingPolicies.get(id).stream()
.filter(policy -> policy.endpointIn(controller.system()).scope() == Endpoint.Scope.zone)
.collect(Collectors.toUnmodifiableMap(policy -> policy.cluster(),
policy -> policy.endpointIn(controller.system()).url()));
}
/** Returns all zone-specific cluster endpoints for the given application, in the given zones. */
public Map<ZoneId, Map<ClusterSpec.Id, URI>> clusterEndpoints(ApplicationId id, Collection<ZoneId> zones) {
Map<ZoneId, Map<ClusterSpec.Id, URI>> deployments = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (ZoneId zone : zones) {
var endpoints = clusterEndpoints(new DeploymentId(id, zone));
if ( ! endpoints.isEmpty())
deployments.put(zone, endpoints);
}
return Collections.unmodifiableMap(deployments);
}
/**
* 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, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(id.tenant());
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + id + "': No credentials provided");
List<ApplicationId> instances = requireApplication(id).instances().keySet().stream()
.map(id::instance)
.collect(Collectors.toUnmodifiableList());
if (instances.size() > 1)
throw new IllegalArgumentException("Could not delete application; more than one instance present: " + instances);
for (ApplicationId instance : instances)
deleteInstance(instance);
if (tenant.type() != Tenant.Type.user)
accessControl.deleteApplication(id, credentials.get());
curator.removeApplication(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(Collectors.joining(", ")));
applicationStore.removeAll(instanceId);
applicationStore.removeAll(TesterId.of(instanceId));
Instance instance = application.get().require(instanceId.instance());
instance.rotations().forEach(assignedRotation -> {
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId());
endpoints.asList().stream()
.map(Endpoint::dnsName)
.forEach(name -> {
controller.nameServiceForwarder().removeRecords(Record.Type.CNAME, RecordName.from(name), Priority.normal);
});
});
curator.writeApplication(application.without(instanceId.instance()).get());
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 {
routingPolicies.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(Application application, InstanceName instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = application.require(instance).deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! application.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).",
application.id().instance(instance), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/** Returns the rotation repository, used for managing global rotation assignments */
public RotationRepository rotationRepository() {
return rotationRepository;
}
public RoutingPolicies routingPolicies() {
return routingPolicies;
}
/**
* 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, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
applicationPackage.deploymentSpec().athenzDomain().ifPresent(identityDomain -> {
Tenant tenant = controller.tenants().require(tenantName);
deployer.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.ifPresentOrElse(user -> {
if ( ! ((AthenzFacade) accessControl).hasTenantAdminAccess(user, new AthenzDomain(identityDomain.value())))
throw new IllegalArgumentException("User " + user.getFullName() + " is not allowed to launch " +
"services in Athenz domain " + identityDomain.value() + ". " +
"Please reach out to the domain admin.");
},
() -> {
if (tenant.type() != Tenant.Type.athenz)
throw new IllegalArgumentException("Athenz domain defined in deployment.xml, but no " +
"Athenz domain for tenant " + tenantName.value());
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain.getName(), identityDomain.value()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.value() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
});
});
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(athenzDomain -> {
controller.zoneRegistry().zones().reachable().ids()
.forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService(zone.environment(), zone.region())
.map(service -> new AthenzService(athenzDomain.value(), service.value()))
.ifPresent(service -> {
boolean allowedToLaunch = ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, service);
if (!allowedToLaunch)
throw new IllegalArgumentException("Not allowed to launch Athenz service " + service.getFullName());
});
});
});
}
/** Returns the latest known version within the given major. */
private 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 RotationRepository rotationRepository;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final RoutingGenerator routingGenerator;
private final RoutingPolicies routingPolicies;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final BooleanFlag provisionApplicationCertificate;
private final DeploymentSpecValidator deploymentSpecValidator;
ApplicationController(Controller controller, CuratorDb curator,
AccessControl accessControl, RotationsConfig rotationsConfig,
Clock clock) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.routingGenerator = controller.serviceRegistry().routingGenerator();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
routingPolicies = new RoutingPolicies(controller);
rotationRepository = new RotationRepository(rotationsConfig, this, curator);
deploymentTrigger = new DeploymentTrigger(controller, controller.serviceRegistry().buildService(), clock);
provisionApplicationCertificate = Flags.PROVISION_APPLICATION_CERTIFICATE.bindTo(controller.flagSource());
deploymentSpecValidator = new DeploymentSpecValidator(controller);
Once.after(Duration.ofMinutes(1), () -> {
Instant start = clock.instant();
int count = 0;
for (Application application : curator.readApplications()) {
lockApplicationIfPresent(application.id(), this::store);
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 application with the given id, or null if it is not present */
public Optional<Application> getApplication(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id));
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(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();
}
/** 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(ApplicationId id, Iterable<ZoneId> zones) {
ImmutableMap.Builder<ZoneId, List<String>> clusters = ImmutableMap.builder();
for (ZoneId zone : zones)
clusters.put(zone, ImmutableList.copyOf(configServer.getContentClusters(new DeploymentId(id, zone))));
return clusters.build();
}
/** 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());
}
/** Change the global endpoint status for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
findGlobalEndpoint(deployment).map(endpoint -> {
try {
configServer.setGlobalRotationStatus(deployment, endpoint.upstreamName(), status);
return endpoint;
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + deployment, e);
}
}).orElseThrow(() -> new IllegalArgumentException("No global endpoint exists for " + deployment));
}
/** Get global endpoint status for given deployment */
public Map<RoutingEndpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
return findGlobalEndpoint(deployment).map(endpoint -> {
try {
EndpointStatus status = configServer.getGlobalRotationStatus(deployment, endpoint.upstreamName());
return Map.of(endpoint, status);
} catch (Exception e) {
throw new RuntimeException("Failed to get rotation status of " + deployment, e);
}
}).orElseGet(Collections::emptyMap);
}
/** Find the global endpoint of given deployment, if any */
private Optional<RoutingEndpoint> findGlobalEndpoint(DeploymentId deployment) {
return routingGenerator.endpoints(deployment).stream()
.filter(RoutingEndpoint::isGlobal)
.findFirst();
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public Application createApplication(TenantAndApplicationId id, Optional<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());
Optional<Tenant> tenant = controller.tenants().get(id.tenant());
if (tenant.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
if (tenant.get().type() != Tenant.Type.user) {
if (credentials.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': No credentials provided");
accessControl.createApplication(id, credentials.get());
}
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) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
lockApplicationOrThrow(TenantAndApplicationId.from(id), 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");
store(application.withNewInstance(id.instance()));
log.info("Created " + id);
});
}
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options);
}
/** Deploys an application. If the application does not exist it is created. */
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 ( getApplication(applicationId).isEmpty()
&& controller.tenants().require(instanceId.tenant()).type() == Tenant.Type.user)
createApplication(applicationId, Optional.empty());
if (getInstance(instanceId).isEmpty())
createInstance(instanceId);
try (Lock deploymentLock = lockForDeployment(instanceId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<ApplicationCertificate> applicationCertificate;
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 + "."));
Optional<JobStatus> job = Optional.ofNullable(application.get().require(instance).deploymentJobs().jobStatus().get(jobType));
if ( job.isEmpty()
|| job.get().lastTriggered().isEmpty()
|| job.get().lastCompleted().isPresent() && job.get().lastCompleted().get().at().isAfter(job.get().lastTriggered().get().at()))
return unexpectedDeployment(instanceId, zone);
JobRun triggered = job.get().lastTriggered().get();
platformVersion = preferOldestVersion ? triggered.sourcePlatform().orElse(triggered.platform())
: triggered.platform();
applicationVersion = preferOldestVersion ? triggered.sourceApplication().orElse(triggered.application())
: triggered.application();
applicationPackage = getApplicationPackage(instanceId, application.get().internal(), applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, instanceId, jobType);
validateRun(application.get(), instance, zone, platformVersion, applicationVersion);
}
if (zone.environment().isProduction())
application = withRotation(application, instance);
endpoints = registerEndpointsInDns(application.get().deploymentSpec(), application.get().require(instanceId.instance()), zone);
if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
applicationCertificate = getApplicationCertificate(application.get().require(instance));
} else {
applicationCertificate = Optional.empty();
}
if ( ! preferOldestVersion
&& ! application.get().internal()
&& ! zone.environment().isManuallyDeployed()) {
storeWithUpdatedConfig(application, applicationPackage);
}
}
options = withVersion(platformVersion, options);
ActivateResult result = deploy(instanceId, applicationPackage, zone, options, endpoints,
applicationCertificate.orElse(null));
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, boolean internal, ApplicationVersion version) {
try {
return internal
? new ApplicationPackage(applicationStore.get(id, version))
: new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()));
}
catch (RuntimeException e) {
try {
log.info("Fetching application package for " + id + " from alternate repository; it is now deployed "
+ (internal ? "internally" : "externally") + "\nException was: " + Exceptions.toMessageString(e));
return internal
? new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()))
: new ApplicationPackage(applicationStore.get(id, version));
}
catch (RuntimeException s) {
e.addSuppressed(s);
throw e;
}
}
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public void storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
deploymentSpecValidator.validate(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
for (InstanceName instanceName : application.get().instances().keySet()) {
application = withoutDeletedDeployments(application, instanceName);
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
application = application.with(instanceName, instance -> withoutUnreferencedDeploymentJobs(deploymentSpec, instance));
}
store(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)
);
DeployOptions options = withVersion(version, DeployOptions.none());
return deploy(application.id(), applicationPackage, zone, options, Set.of(), /* No application cert */ null);
} 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, DeployOptions options) {
return deploy(tester.id(), applicationPackage, zone, options, Set.of(), /* No application cert for tester*/ null);
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, DeployOptions deployOptions, Set<ContainerEndpoint> endpoints,
ApplicationCertificate applicationCertificate) {
DeploymentId deploymentId = new DeploymentId(application, zone);
try {
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(deploymentId, deployOptions, Set.of(), endpoints, applicationCertificate, applicationPackage.zippedContent());
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
routingPolicies.refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
/** Makes sure the application has a global rotation, if eligible. */
private LockedApplication withRotation(LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(application.get().deploymentSpec(),
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
store(application);
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
private Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
var registerLegacyNames = deploymentSpec.globalServiceId().isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId())
.scope(Endpoint.Scope.global);
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
if (!registerLegacyNames) {
endpoints = endpoints.legacy(false);
}
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.asList().forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
private Optional<ApplicationCertificate> getApplicationCertificate(Instance instance) {
boolean provisionCertificate = provisionApplicationCertificate.with(FetchVector.Dimension.APPLICATION_ID,
instance.id().serializedForm()).value();
if (!provisionCertificate) {
return Optional.empty();
}
Optional<ApplicationCertificate> applicationCertificate = curator.readApplicationCertificate(instance.id());
if(applicationCertificate.isPresent())
return applicationCertificate;
ApplicationCertificate newCertificate = controller.serviceRegistry().applicationCertificateProvider().requestCaSignedCertificate(instance.id(), dnsNamesOf(instance.id()));
curator.writeApplicationCertificate(instance.id(), newCertificate);
return Optional.of(newCertificate);
}
/** Returns all valid DNS names of given application */
private List<String> dnsNamesOf(ApplicationId applicationId) {
List<String> endpointDnsNames = new ArrayList<>();
endpointDnsNames.add(Endpoint.createHashedCn(applicationId, controller.system()));
var globalDefaultEndpoint = Endpoint.of(applicationId).named(EndpointId.default_());
var rotationEndpoints = Endpoint.of(applicationId).wildcard();
var zoneLocalEndpoints = controller.zoneRegistry().zones().directlyRouted().zones().stream().flatMap(zone -> Stream.of(
Endpoint.of(applicationId).target(ClusterSpec.Id.from("default"), zone.getId()),
Endpoint.of(applicationId).wildcard(zone.getId())
));
Stream.concat(Stream.of(globalDefaultEndpoint, rotationEndpoints), zoneLocalEndpoints)
.map(Endpoint.EndpointBuilder::directRouting)
.map(endpoint -> endpoint.on(Endpoint.Port.tls()))
.map(endpointBuilder -> endpointBuilder.in(controller.system()))
.map(Endpoint::dnsName).forEach(endpointDnsNames::add);
return Collections.unmodifiableList(endpointDnsNames);
}
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 Instance withoutUnreferencedDeploymentJobs(DeploymentSpec deploymentSpec, Instance instance) {
for (JobType job : JobList.from(instance).production().mapToList(JobStatus::type)) {
ZoneId zone = job.zone(controller.system());
if (deploymentSpec.includes(zone.environment(), Optional.of(zone.region())))
continue;
instance = instance.withoutDeploymentJob(job);
}
return instance;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/** Returns the endpoints of the deployment, or empty if the request fails */
public List<URI> getDeploymentEndpoints(DeploymentId deploymentId) {
if ( ! getInstance(deploymentId.applicationId())
.map(application -> application.deployments().containsKey(deploymentId.zoneId()))
.orElse(deploymentId.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", deploymentId.toString());
try {
return ImmutableList.copyOf(routingGenerator.endpoints(deploymentId).stream()
.map(RoutingEndpoint::endpoint)
.map(URI::create)
.iterator());
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e);
return Collections.emptyList();
}
}
/** Returns the non-empty endpoints per cluster in the given deployment, or empty if endpoints can't be found. */
public Map<ClusterSpec.Id, URI> clusterEndpoints(DeploymentId id) {
if ( ! getInstance(id.applicationId())
.map(application -> application.deployments().containsKey(id.zoneId()))
.orElse(id.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", id.toString());
try {
var endpoints = routingGenerator.clusterEndpoints(id);
if ( ! endpoints.isEmpty())
return endpoints;
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + id, e);
}
return routingPolicies.get(id).stream()
.filter(policy -> policy.endpointIn(controller.system()).scope() == Endpoint.Scope.zone)
.collect(Collectors.toUnmodifiableMap(policy -> policy.cluster(),
policy -> policy.endpointIn(controller.system()).url()));
}
/** Returns all zone-specific cluster endpoints for the given application, in the given zones. */
public Map<ZoneId, Map<ClusterSpec.Id, URI>> clusterEndpoints(ApplicationId id, Collection<ZoneId> zones) {
Map<ZoneId, Map<ClusterSpec.Id, URI>> deployments = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (ZoneId zone : zones) {
var endpoints = clusterEndpoints(new DeploymentId(id, zone));
if ( ! endpoints.isEmpty())
deployments.put(zone, endpoints);
}
return Collections.unmodifiableMap(deployments);
}
/**
* 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, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(id.tenant());
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + id + "': No credentials provided");
List<ApplicationId> instances = requireApplication(id).instances().keySet().stream()
.map(id::instance)
.collect(Collectors.toUnmodifiableList());
if (instances.size() > 1)
throw new IllegalArgumentException("Could not delete application; more than one instance present: " + instances);
for (ApplicationId instance : instances)
deleteInstance(instance);
if (tenant.type() != Tenant.Type.user)
accessControl.deleteApplication(id, credentials.get());
curator.removeApplication(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(Collectors.joining(", ")));
applicationStore.removeAll(instanceId);
applicationStore.removeAll(TesterId.of(instanceId));
Instance instance = application.get().require(instanceId.instance());
instance.rotations().forEach(assignedRotation -> {
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId());
endpoints.asList().stream()
.map(Endpoint::dnsName)
.forEach(name -> {
controller.nameServiceForwarder().removeRecords(Record.Type.CNAME, RecordName.from(name), Priority.normal);
});
});
curator.writeApplication(application.without(instanceId.instance()).get());
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 {
routingPolicies.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(Application application, InstanceName instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = application.require(instance).deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! application.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).",
application.id().instance(instance), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/** Returns the rotation repository, used for managing global rotation assignments */
public RotationRepository rotationRepository() {
return rotationRepository;
}
public RoutingPolicies routingPolicies() {
return routingPolicies;
}
/**
* 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, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
applicationPackage.deploymentSpec().athenzDomain().ifPresent(identityDomain -> {
Tenant tenant = controller.tenants().require(tenantName);
deployer.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.ifPresentOrElse(user -> {
if ( ! ((AthenzFacade) accessControl).hasTenantAdminAccess(user, new AthenzDomain(identityDomain.value())))
throw new IllegalArgumentException("User " + user.getFullName() + " is not allowed to launch " +
"services in Athenz domain " + identityDomain.value() + ". " +
"Please reach out to the domain admin.");
},
() -> {
if (tenant.type() != Tenant.Type.athenz)
throw new IllegalArgumentException("Athenz domain defined in deployment.xml, but no " +
"Athenz domain for tenant " + tenantName.value());
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain.getName(), identityDomain.value()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.value() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
});
});
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(athenzDomain -> {
controller.zoneRegistry().zones().reachable().ids()
.forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService(zone.environment(), zone.region())
.map(service -> new AthenzService(athenzDomain.value(), service.value()))
.ifPresent(service -> {
boolean allowedToLaunch = ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, service);
if (!allowedToLaunch)
throw new IllegalArgumentException("Not allowed to launch Athenz service " + service.getFullName());
});
});
});
}
/** Returns the latest known version within the given major. */
private 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);
}
} |
Should only be needed for the one who deploys to production I think? I sent a PR to remove that test. | private LockedApplication withoutDeletedDeployments(LockedApplication application, InstanceName instance) {
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
List<Deployment> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.filter(deployment -> ! deploymentSpec.includes(deployment.zone().environment(),
Optional.of(deployment.zone().region())))
.collect(Collectors.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(deployment -> deployment.zone().region().value())
.collect(Collectors.joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
for (Deployment deployment : deploymentsToRemove)
application = deactivate(application, instance, deployment.zone());
return application;
} | .filter(deployment -> ! deploymentSpec.includes(deployment.zone().environment(), | private LockedApplication withoutDeletedDeployments(LockedApplication application, InstanceName instance) {
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
List<Deployment> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.filter(deployment -> ! deploymentSpec.includes(deployment.zone().environment(),
Optional.of(deployment.zone().region())))
.collect(Collectors.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(deployment -> deployment.zone().region().value())
.collect(Collectors.joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
for (Deployment deployment : deploymentsToRemove)
application = deactivate(application, instance, deployment.zone());
return application;
} | 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 RotationRepository rotationRepository;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final RoutingGenerator routingGenerator;
private final RoutingPolicies routingPolicies;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final BooleanFlag provisionApplicationCertificate;
private final DeploymentSpecValidator deploymentSpecValidator;
ApplicationController(Controller controller, CuratorDb curator,
AccessControl accessControl, RotationsConfig rotationsConfig,
Clock clock) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.routingGenerator = controller.serviceRegistry().routingGenerator();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
routingPolicies = new RoutingPolicies(controller);
rotationRepository = new RotationRepository(rotationsConfig, this, curator);
deploymentTrigger = new DeploymentTrigger(controller, controller.serviceRegistry().buildService(), clock);
provisionApplicationCertificate = Flags.PROVISION_APPLICATION_CERTIFICATE.bindTo(controller.flagSource());
deploymentSpecValidator = new DeploymentSpecValidator(controller);
Once.after(Duration.ofMinutes(1), () -> {
Instant start = clock.instant();
int count = 0;
for (Application application : curator.readApplications()) {
lockApplicationIfPresent(application.id(), this::store);
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 application with the given id, or null if it is not present */
public Optional<Application> getApplication(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id));
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(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();
}
/** 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(ApplicationId id, Iterable<ZoneId> zones) {
ImmutableMap.Builder<ZoneId, List<String>> clusters = ImmutableMap.builder();
for (ZoneId zone : zones)
clusters.put(zone, ImmutableList.copyOf(configServer.getContentClusters(new DeploymentId(id, zone))));
return clusters.build();
}
/** 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());
}
/** Change the global endpoint status for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
findGlobalEndpoint(deployment).map(endpoint -> {
try {
configServer.setGlobalRotationStatus(deployment, endpoint.upstreamName(), status);
return endpoint;
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + deployment, e);
}
}).orElseThrow(() -> new IllegalArgumentException("No global endpoint exists for " + deployment));
}
/** Get global endpoint status for given deployment */
public Map<RoutingEndpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
return findGlobalEndpoint(deployment).map(endpoint -> {
try {
EndpointStatus status = configServer.getGlobalRotationStatus(deployment, endpoint.upstreamName());
return Map.of(endpoint, status);
} catch (Exception e) {
throw new RuntimeException("Failed to get rotation status of " + deployment, e);
}
}).orElseGet(Collections::emptyMap);
}
/** Find the global endpoint of given deployment, if any */
private Optional<RoutingEndpoint> findGlobalEndpoint(DeploymentId deployment) {
return routingGenerator.endpoints(deployment).stream()
.filter(RoutingEndpoint::isGlobal)
.findFirst();
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public Application createApplication(TenantAndApplicationId id, Optional<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());
Optional<Tenant> tenant = controller.tenants().get(id.tenant());
if (tenant.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
if (tenant.get().type() != Tenant.Type.user) {
if (credentials.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': No credentials provided");
accessControl.createApplication(id, credentials.get());
}
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) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
lockApplicationOrThrow(TenantAndApplicationId.from(id), 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");
store(application.withNewInstance(id.instance()));
log.info("Created " + id);
});
}
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options);
}
/** Deploys an application. If the application does not exist it is created. */
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 ( getApplication(applicationId).isEmpty()
&& controller.tenants().require(instanceId.tenant()).type() == Tenant.Type.user)
createApplication(applicationId, Optional.empty());
if (getInstance(instanceId).isEmpty())
createInstance(instanceId);
try (Lock deploymentLock = lockForDeployment(instanceId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<ApplicationCertificate> applicationCertificate;
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 + "."));
Optional<JobStatus> job = Optional.ofNullable(application.get().require(instance).deploymentJobs().jobStatus().get(jobType));
if ( job.isEmpty()
|| job.get().lastTriggered().isEmpty()
|| job.get().lastCompleted().isPresent() && job.get().lastCompleted().get().at().isAfter(job.get().lastTriggered().get().at()))
return unexpectedDeployment(instanceId, zone);
JobRun triggered = job.get().lastTriggered().get();
platformVersion = preferOldestVersion ? triggered.sourcePlatform().orElse(triggered.platform())
: triggered.platform();
applicationVersion = preferOldestVersion ? triggered.sourceApplication().orElse(triggered.application())
: triggered.application();
applicationPackage = getApplicationPackage(instanceId, application.get().internal(), applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, instanceId, jobType);
validateRun(application.get(), instance, zone, platformVersion, applicationVersion);
}
if (zone.environment().isProduction())
application = withRotation(application, instance);
endpoints = registerEndpointsInDns(application.get().deploymentSpec(), application.get().require(instanceId.instance()), zone);
if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
applicationCertificate = getApplicationCertificate(application.get().require(instance));
} else {
applicationCertificate = Optional.empty();
}
if ( ! preferOldestVersion
&& ! application.get().internal()
&& ! zone.environment().isManuallyDeployed()) {
storeWithUpdatedConfig(application, applicationPackage);
}
}
options = withVersion(platformVersion, options);
ActivateResult result = deploy(instanceId, applicationPackage, zone, options, endpoints,
applicationCertificate.orElse(null));
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, boolean internal, ApplicationVersion version) {
try {
return internal
? new ApplicationPackage(applicationStore.get(id, version))
: new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()));
}
catch (RuntimeException e) {
try {
log.info("Fetching application package for " + id + " from alternate repository; it is now deployed "
+ (internal ? "internally" : "externally") + "\nException was: " + Exceptions.toMessageString(e));
return internal
? new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()))
: new ApplicationPackage(applicationStore.get(id, version));
}
catch (RuntimeException s) {
e.addSuppressed(s);
throw e;
}
}
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public void storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
deploymentSpecValidator.validate(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
for (InstanceName instanceName : application.get().instances().keySet()) {
application = withoutDeletedDeployments(application, instanceName);
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
application = application.with(instanceName, instance -> withoutUnreferencedDeploymentJobs(deploymentSpec, instance));
}
store(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)
);
DeployOptions options = withVersion(version, DeployOptions.none());
return deploy(application.id(), applicationPackage, zone, options, Set.of(), /* No application cert */ null);
} 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, DeployOptions options) {
return deploy(tester.id(), applicationPackage, zone, options, Set.of(), /* No application cert for tester*/ null);
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, DeployOptions deployOptions, Set<ContainerEndpoint> endpoints,
ApplicationCertificate applicationCertificate) {
DeploymentId deploymentId = new DeploymentId(application, zone);
try {
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(deploymentId, deployOptions, Set.of(), endpoints, applicationCertificate, applicationPackage.zippedContent());
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
routingPolicies.refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
/** Makes sure the application has a global rotation, if eligible. */
private LockedApplication withRotation(LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(application.get().deploymentSpec(),
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
store(application);
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
private Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
var registerLegacyNames = deploymentSpec.globalServiceId().isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId())
.scope(Endpoint.Scope.global);
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
if (!registerLegacyNames) {
endpoints = endpoints.legacy(false);
}
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.asList().forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
private Optional<ApplicationCertificate> getApplicationCertificate(Instance instance) {
boolean provisionCertificate = provisionApplicationCertificate.with(FetchVector.Dimension.APPLICATION_ID,
instance.id().serializedForm()).value();
if (!provisionCertificate) {
return Optional.empty();
}
Optional<ApplicationCertificate> applicationCertificate = curator.readApplicationCertificate(instance.id());
if(applicationCertificate.isPresent())
return applicationCertificate;
ApplicationCertificate newCertificate = controller.serviceRegistry().applicationCertificateProvider().requestCaSignedCertificate(instance.id(), dnsNamesOf(instance.id()));
curator.writeApplicationCertificate(instance.id(), newCertificate);
return Optional.of(newCertificate);
}
/** Returns all valid DNS names of given application */
private List<String> dnsNamesOf(ApplicationId applicationId) {
List<String> endpointDnsNames = new ArrayList<>();
endpointDnsNames.add(Endpoint.createHashedCn(applicationId, controller.system()));
var globalDefaultEndpoint = Endpoint.of(applicationId).named(EndpointId.default_());
var rotationEndpoints = Endpoint.of(applicationId).wildcard();
var zoneLocalEndpoints = controller.zoneRegistry().zones().directlyRouted().zones().stream().flatMap(zone -> Stream.of(
Endpoint.of(applicationId).target(ClusterSpec.Id.from("default"), zone.getId()),
Endpoint.of(applicationId).wildcard(zone.getId())
));
Stream.concat(Stream.of(globalDefaultEndpoint, rotationEndpoints), zoneLocalEndpoints)
.map(Endpoint.EndpointBuilder::directRouting)
.map(endpoint -> endpoint.on(Endpoint.Port.tls()))
.map(endpointBuilder -> endpointBuilder.in(controller.system()))
.map(Endpoint::dnsName).forEach(endpointDnsNames::add);
return Collections.unmodifiableList(endpointDnsNames);
}
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 Instance withoutUnreferencedDeploymentJobs(DeploymentSpec deploymentSpec, Instance instance) {
for (JobType job : JobList.from(instance).production().mapToList(JobStatus::type)) {
ZoneId zone = job.zone(controller.system());
if (deploymentSpec.includes(zone.environment(), Optional.of(zone.region())))
continue;
instance = instance.withoutDeploymentJob(job);
}
return instance;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/** Returns the endpoints of the deployment, or empty if the request fails */
public List<URI> getDeploymentEndpoints(DeploymentId deploymentId) {
if ( ! getInstance(deploymentId.applicationId())
.map(application -> application.deployments().containsKey(deploymentId.zoneId()))
.orElse(deploymentId.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", deploymentId.toString());
try {
return ImmutableList.copyOf(routingGenerator.endpoints(deploymentId).stream()
.map(RoutingEndpoint::endpoint)
.map(URI::create)
.iterator());
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e);
return Collections.emptyList();
}
}
/** Returns the non-empty endpoints per cluster in the given deployment, or empty if endpoints can't be found. */
public Map<ClusterSpec.Id, URI> clusterEndpoints(DeploymentId id) {
if ( ! getInstance(id.applicationId())
.map(application -> application.deployments().containsKey(id.zoneId()))
.orElse(id.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", id.toString());
try {
var endpoints = routingGenerator.clusterEndpoints(id);
if ( ! endpoints.isEmpty())
return endpoints;
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + id, e);
}
return routingPolicies.get(id).stream()
.filter(policy -> policy.endpointIn(controller.system()).scope() == Endpoint.Scope.zone)
.collect(Collectors.toUnmodifiableMap(policy -> policy.cluster(),
policy -> policy.endpointIn(controller.system()).url()));
}
/** Returns all zone-specific cluster endpoints for the given application, in the given zones. */
public Map<ZoneId, Map<ClusterSpec.Id, URI>> clusterEndpoints(ApplicationId id, Collection<ZoneId> zones) {
Map<ZoneId, Map<ClusterSpec.Id, URI>> deployments = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (ZoneId zone : zones) {
var endpoints = clusterEndpoints(new DeploymentId(id, zone));
if ( ! endpoints.isEmpty())
deployments.put(zone, endpoints);
}
return Collections.unmodifiableMap(deployments);
}
/**
* 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, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(id.tenant());
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + id + "': No credentials provided");
List<ApplicationId> instances = requireApplication(id).instances().keySet().stream()
.map(id::instance)
.collect(Collectors.toUnmodifiableList());
if (instances.size() > 1)
throw new IllegalArgumentException("Could not delete application; more than one instance present: " + instances);
for (ApplicationId instance : instances)
deleteInstance(instance);
if (tenant.type() != Tenant.Type.user)
accessControl.deleteApplication(id, credentials.get());
curator.removeApplication(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(Collectors.joining(", ")));
applicationStore.removeAll(instanceId);
applicationStore.removeAll(TesterId.of(instanceId));
Instance instance = application.get().require(instanceId.instance());
instance.rotations().forEach(assignedRotation -> {
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId());
endpoints.asList().stream()
.map(Endpoint::dnsName)
.forEach(name -> {
controller.nameServiceForwarder().removeRecords(Record.Type.CNAME, RecordName.from(name), Priority.normal);
});
});
curator.writeApplication(application.without(instanceId.instance()).get());
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 {
routingPolicies.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(Application application, InstanceName instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = application.require(instance).deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! application.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).",
application.id().instance(instance), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/** Returns the rotation repository, used for managing global rotation assignments */
public RotationRepository rotationRepository() {
return rotationRepository;
}
public RoutingPolicies routingPolicies() {
return routingPolicies;
}
/**
* 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, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
applicationPackage.deploymentSpec().athenzDomain().ifPresent(identityDomain -> {
Tenant tenant = controller.tenants().require(tenantName);
deployer.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.ifPresentOrElse(user -> {
if ( ! ((AthenzFacade) accessControl).hasTenantAdminAccess(user, new AthenzDomain(identityDomain.value())))
throw new IllegalArgumentException("User " + user.getFullName() + " is not allowed to launch " +
"services in Athenz domain " + identityDomain.value() + ". " +
"Please reach out to the domain admin.");
},
() -> {
if (tenant.type() != Tenant.Type.athenz)
throw new IllegalArgumentException("Athenz domain defined in deployment.xml, but no " +
"Athenz domain for tenant " + tenantName.value());
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain.getName(), identityDomain.value()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.value() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
});
});
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(athenzDomain -> {
controller.zoneRegistry().zones().reachable().ids()
.forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService(zone.environment(), zone.region())
.map(service -> new AthenzService(athenzDomain.value(), service.value()))
.ifPresent(service -> {
boolean allowedToLaunch = ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, service);
if (!allowedToLaunch)
throw new IllegalArgumentException("Not allowed to launch Athenz service " + service.getFullName());
});
});
});
}
/** Returns the latest known version within the given major. */
private 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 RotationRepository rotationRepository;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final RoutingGenerator routingGenerator;
private final RoutingPolicies routingPolicies;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final BooleanFlag provisionApplicationCertificate;
private final DeploymentSpecValidator deploymentSpecValidator;
ApplicationController(Controller controller, CuratorDb curator,
AccessControl accessControl, RotationsConfig rotationsConfig,
Clock clock) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.routingGenerator = controller.serviceRegistry().routingGenerator();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
routingPolicies = new RoutingPolicies(controller);
rotationRepository = new RotationRepository(rotationsConfig, this, curator);
deploymentTrigger = new DeploymentTrigger(controller, controller.serviceRegistry().buildService(), clock);
provisionApplicationCertificate = Flags.PROVISION_APPLICATION_CERTIFICATE.bindTo(controller.flagSource());
deploymentSpecValidator = new DeploymentSpecValidator(controller);
Once.after(Duration.ofMinutes(1), () -> {
Instant start = clock.instant();
int count = 0;
for (Application application : curator.readApplications()) {
lockApplicationIfPresent(application.id(), this::store);
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 application with the given id, or null if it is not present */
public Optional<Application> getApplication(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id));
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(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();
}
/** 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(ApplicationId id, Iterable<ZoneId> zones) {
ImmutableMap.Builder<ZoneId, List<String>> clusters = ImmutableMap.builder();
for (ZoneId zone : zones)
clusters.put(zone, ImmutableList.copyOf(configServer.getContentClusters(new DeploymentId(id, zone))));
return clusters.build();
}
/** 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());
}
/** Change the global endpoint status for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
findGlobalEndpoint(deployment).map(endpoint -> {
try {
configServer.setGlobalRotationStatus(deployment, endpoint.upstreamName(), status);
return endpoint;
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + deployment, e);
}
}).orElseThrow(() -> new IllegalArgumentException("No global endpoint exists for " + deployment));
}
/** Get global endpoint status for given deployment */
public Map<RoutingEndpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
return findGlobalEndpoint(deployment).map(endpoint -> {
try {
EndpointStatus status = configServer.getGlobalRotationStatus(deployment, endpoint.upstreamName());
return Map.of(endpoint, status);
} catch (Exception e) {
throw new RuntimeException("Failed to get rotation status of " + deployment, e);
}
}).orElseGet(Collections::emptyMap);
}
/** Find the global endpoint of given deployment, if any */
private Optional<RoutingEndpoint> findGlobalEndpoint(DeploymentId deployment) {
return routingGenerator.endpoints(deployment).stream()
.filter(RoutingEndpoint::isGlobal)
.findFirst();
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public Application createApplication(TenantAndApplicationId id, Optional<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());
Optional<Tenant> tenant = controller.tenants().get(id.tenant());
if (tenant.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
if (tenant.get().type() != Tenant.Type.user) {
if (credentials.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': No credentials provided");
accessControl.createApplication(id, credentials.get());
}
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) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
lockApplicationOrThrow(TenantAndApplicationId.from(id), 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");
store(application.withNewInstance(id.instance()));
log.info("Created " + id);
});
}
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options);
}
/** Deploys an application. If the application does not exist it is created. */
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 ( getApplication(applicationId).isEmpty()
&& controller.tenants().require(instanceId.tenant()).type() == Tenant.Type.user)
createApplication(applicationId, Optional.empty());
if (getInstance(instanceId).isEmpty())
createInstance(instanceId);
try (Lock deploymentLock = lockForDeployment(instanceId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<ApplicationCertificate> applicationCertificate;
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 + "."));
Optional<JobStatus> job = Optional.ofNullable(application.get().require(instance).deploymentJobs().jobStatus().get(jobType));
if ( job.isEmpty()
|| job.get().lastTriggered().isEmpty()
|| job.get().lastCompleted().isPresent() && job.get().lastCompleted().get().at().isAfter(job.get().lastTriggered().get().at()))
return unexpectedDeployment(instanceId, zone);
JobRun triggered = job.get().lastTriggered().get();
platformVersion = preferOldestVersion ? triggered.sourcePlatform().orElse(triggered.platform())
: triggered.platform();
applicationVersion = preferOldestVersion ? triggered.sourceApplication().orElse(triggered.application())
: triggered.application();
applicationPackage = getApplicationPackage(instanceId, application.get().internal(), applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, instanceId, jobType);
validateRun(application.get(), instance, zone, platformVersion, applicationVersion);
}
if (zone.environment().isProduction())
application = withRotation(application, instance);
endpoints = registerEndpointsInDns(application.get().deploymentSpec(), application.get().require(instanceId.instance()), zone);
if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
applicationCertificate = getApplicationCertificate(application.get().require(instance));
} else {
applicationCertificate = Optional.empty();
}
if ( ! preferOldestVersion
&& ! application.get().internal()
&& ! zone.environment().isManuallyDeployed()) {
storeWithUpdatedConfig(application, applicationPackage);
}
}
options = withVersion(platformVersion, options);
ActivateResult result = deploy(instanceId, applicationPackage, zone, options, endpoints,
applicationCertificate.orElse(null));
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, boolean internal, ApplicationVersion version) {
try {
return internal
? new ApplicationPackage(applicationStore.get(id, version))
: new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()));
}
catch (RuntimeException e) {
try {
log.info("Fetching application package for " + id + " from alternate repository; it is now deployed "
+ (internal ? "internally" : "externally") + "\nException was: " + Exceptions.toMessageString(e));
return internal
? new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()))
: new ApplicationPackage(applicationStore.get(id, version));
}
catch (RuntimeException s) {
e.addSuppressed(s);
throw e;
}
}
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public void storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
deploymentSpecValidator.validate(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
for (InstanceName instanceName : application.get().instances().keySet()) {
application = withoutDeletedDeployments(application, instanceName);
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
application = application.with(instanceName, instance -> withoutUnreferencedDeploymentJobs(deploymentSpec, instance));
}
store(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)
);
DeployOptions options = withVersion(version, DeployOptions.none());
return deploy(application.id(), applicationPackage, zone, options, Set.of(), /* No application cert */ null);
} 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, DeployOptions options) {
return deploy(tester.id(), applicationPackage, zone, options, Set.of(), /* No application cert for tester*/ null);
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, DeployOptions deployOptions, Set<ContainerEndpoint> endpoints,
ApplicationCertificate applicationCertificate) {
DeploymentId deploymentId = new DeploymentId(application, zone);
try {
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(deploymentId, deployOptions, Set.of(), endpoints, applicationCertificate, applicationPackage.zippedContent());
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
routingPolicies.refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
/** Makes sure the application has a global rotation, if eligible. */
private LockedApplication withRotation(LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(application.get().deploymentSpec(),
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
store(application);
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
private Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
var registerLegacyNames = deploymentSpec.globalServiceId().isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId())
.scope(Endpoint.Scope.global);
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
if (!registerLegacyNames) {
endpoints = endpoints.legacy(false);
}
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.asList().forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
private Optional<ApplicationCertificate> getApplicationCertificate(Instance instance) {
boolean provisionCertificate = provisionApplicationCertificate.with(FetchVector.Dimension.APPLICATION_ID,
instance.id().serializedForm()).value();
if (!provisionCertificate) {
return Optional.empty();
}
Optional<ApplicationCertificate> applicationCertificate = curator.readApplicationCertificate(instance.id());
if(applicationCertificate.isPresent())
return applicationCertificate;
ApplicationCertificate newCertificate = controller.serviceRegistry().applicationCertificateProvider().requestCaSignedCertificate(instance.id(), dnsNamesOf(instance.id()));
curator.writeApplicationCertificate(instance.id(), newCertificate);
return Optional.of(newCertificate);
}
/** Returns all valid DNS names of given application */
private List<String> dnsNamesOf(ApplicationId applicationId) {
List<String> endpointDnsNames = new ArrayList<>();
endpointDnsNames.add(Endpoint.createHashedCn(applicationId, controller.system()));
var globalDefaultEndpoint = Endpoint.of(applicationId).named(EndpointId.default_());
var rotationEndpoints = Endpoint.of(applicationId).wildcard();
var zoneLocalEndpoints = controller.zoneRegistry().zones().directlyRouted().zones().stream().flatMap(zone -> Stream.of(
Endpoint.of(applicationId).target(ClusterSpec.Id.from("default"), zone.getId()),
Endpoint.of(applicationId).wildcard(zone.getId())
));
Stream.concat(Stream.of(globalDefaultEndpoint, rotationEndpoints), zoneLocalEndpoints)
.map(Endpoint.EndpointBuilder::directRouting)
.map(endpoint -> endpoint.on(Endpoint.Port.tls()))
.map(endpointBuilder -> endpointBuilder.in(controller.system()))
.map(Endpoint::dnsName).forEach(endpointDnsNames::add);
return Collections.unmodifiableList(endpointDnsNames);
}
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 Instance withoutUnreferencedDeploymentJobs(DeploymentSpec deploymentSpec, Instance instance) {
for (JobType job : JobList.from(instance).production().mapToList(JobStatus::type)) {
ZoneId zone = job.zone(controller.system());
if (deploymentSpec.includes(zone.environment(), Optional.of(zone.region())))
continue;
instance = instance.withoutDeploymentJob(job);
}
return instance;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/** Returns the endpoints of the deployment, or empty if the request fails */
public List<URI> getDeploymentEndpoints(DeploymentId deploymentId) {
if ( ! getInstance(deploymentId.applicationId())
.map(application -> application.deployments().containsKey(deploymentId.zoneId()))
.orElse(deploymentId.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", deploymentId.toString());
try {
return ImmutableList.copyOf(routingGenerator.endpoints(deploymentId).stream()
.map(RoutingEndpoint::endpoint)
.map(URI::create)
.iterator());
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e);
return Collections.emptyList();
}
}
/** Returns the non-empty endpoints per cluster in the given deployment, or empty if endpoints can't be found. */
public Map<ClusterSpec.Id, URI> clusterEndpoints(DeploymentId id) {
if ( ! getInstance(id.applicationId())
.map(application -> application.deployments().containsKey(id.zoneId()))
.orElse(id.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", id.toString());
try {
var endpoints = routingGenerator.clusterEndpoints(id);
if ( ! endpoints.isEmpty())
return endpoints;
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + id, e);
}
return routingPolicies.get(id).stream()
.filter(policy -> policy.endpointIn(controller.system()).scope() == Endpoint.Scope.zone)
.collect(Collectors.toUnmodifiableMap(policy -> policy.cluster(),
policy -> policy.endpointIn(controller.system()).url()));
}
/** Returns all zone-specific cluster endpoints for the given application, in the given zones. */
public Map<ZoneId, Map<ClusterSpec.Id, URI>> clusterEndpoints(ApplicationId id, Collection<ZoneId> zones) {
Map<ZoneId, Map<ClusterSpec.Id, URI>> deployments = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (ZoneId zone : zones) {
var endpoints = clusterEndpoints(new DeploymentId(id, zone));
if ( ! endpoints.isEmpty())
deployments.put(zone, endpoints);
}
return Collections.unmodifiableMap(deployments);
}
/**
* 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, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(id.tenant());
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + id + "': No credentials provided");
List<ApplicationId> instances = requireApplication(id).instances().keySet().stream()
.map(id::instance)
.collect(Collectors.toUnmodifiableList());
if (instances.size() > 1)
throw new IllegalArgumentException("Could not delete application; more than one instance present: " + instances);
for (ApplicationId instance : instances)
deleteInstance(instance);
if (tenant.type() != Tenant.Type.user)
accessControl.deleteApplication(id, credentials.get());
curator.removeApplication(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(Collectors.joining(", ")));
applicationStore.removeAll(instanceId);
applicationStore.removeAll(TesterId.of(instanceId));
Instance instance = application.get().require(instanceId.instance());
instance.rotations().forEach(assignedRotation -> {
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId());
endpoints.asList().stream()
.map(Endpoint::dnsName)
.forEach(name -> {
controller.nameServiceForwarder().removeRecords(Record.Type.CNAME, RecordName.from(name), Priority.normal);
});
});
curator.writeApplication(application.without(instanceId.instance()).get());
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 {
routingPolicies.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(Application application, InstanceName instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = application.require(instance).deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! application.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).",
application.id().instance(instance), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/** Returns the rotation repository, used for managing global rotation assignments */
public RotationRepository rotationRepository() {
return rotationRepository;
}
public RoutingPolicies routingPolicies() {
return routingPolicies;
}
/**
* 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, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
applicationPackage.deploymentSpec().athenzDomain().ifPresent(identityDomain -> {
Tenant tenant = controller.tenants().require(tenantName);
deployer.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.ifPresentOrElse(user -> {
if ( ! ((AthenzFacade) accessControl).hasTenantAdminAccess(user, new AthenzDomain(identityDomain.value())))
throw new IllegalArgumentException("User " + user.getFullName() + " is not allowed to launch " +
"services in Athenz domain " + identityDomain.value() + ". " +
"Please reach out to the domain admin.");
},
() -> {
if (tenant.type() != Tenant.Type.athenz)
throw new IllegalArgumentException("Athenz domain defined in deployment.xml, but no " +
"Athenz domain for tenant " + tenantName.value());
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain.getName(), identityDomain.value()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.value() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
});
});
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(athenzDomain -> {
controller.zoneRegistry().zones().reachable().ids()
.forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService(zone.environment(), zone.region())
.map(service -> new AthenzService(athenzDomain.value(), service.value()))
.ifPresent(service -> {
boolean allowedToLaunch = ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, service);
if (!allowedToLaunch)
throw new IllegalArgumentException("Not allowed to launch Athenz service " + service.getFullName());
});
});
});
}
/** Returns the latest known version within the given major. */
private 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);
}
} |
Yes, when we orchestrate things, we'll never deploy illegally like this. | private LockedApplication withoutDeletedDeployments(LockedApplication application, InstanceName instance) {
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
List<Deployment> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.filter(deployment -> ! deploymentSpec.includes(deployment.zone().environment(),
Optional.of(deployment.zone().region())))
.collect(Collectors.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(deployment -> deployment.zone().region().value())
.collect(Collectors.joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
for (Deployment deployment : deploymentsToRemove)
application = deactivate(application, instance, deployment.zone());
return application;
} | .filter(deployment -> ! deploymentSpec.includes(deployment.zone().environment(), | private LockedApplication withoutDeletedDeployments(LockedApplication application, InstanceName instance) {
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
List<Deployment> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.filter(deployment -> ! deploymentSpec.includes(deployment.zone().environment(),
Optional.of(deployment.zone().region())))
.collect(Collectors.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(deployment -> deployment.zone().region().value())
.collect(Collectors.joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
for (Deployment deployment : deploymentsToRemove)
application = deactivate(application, instance, deployment.zone());
return application;
} | 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 RotationRepository rotationRepository;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final RoutingGenerator routingGenerator;
private final RoutingPolicies routingPolicies;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final BooleanFlag provisionApplicationCertificate;
private final DeploymentSpecValidator deploymentSpecValidator;
ApplicationController(Controller controller, CuratorDb curator,
AccessControl accessControl, RotationsConfig rotationsConfig,
Clock clock) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.routingGenerator = controller.serviceRegistry().routingGenerator();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
routingPolicies = new RoutingPolicies(controller);
rotationRepository = new RotationRepository(rotationsConfig, this, curator);
deploymentTrigger = new DeploymentTrigger(controller, controller.serviceRegistry().buildService(), clock);
provisionApplicationCertificate = Flags.PROVISION_APPLICATION_CERTIFICATE.bindTo(controller.flagSource());
deploymentSpecValidator = new DeploymentSpecValidator(controller);
Once.after(Duration.ofMinutes(1), () -> {
Instant start = clock.instant();
int count = 0;
for (Application application : curator.readApplications()) {
lockApplicationIfPresent(application.id(), this::store);
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 application with the given id, or null if it is not present */
public Optional<Application> getApplication(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id));
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(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();
}
/** 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(ApplicationId id, Iterable<ZoneId> zones) {
ImmutableMap.Builder<ZoneId, List<String>> clusters = ImmutableMap.builder();
for (ZoneId zone : zones)
clusters.put(zone, ImmutableList.copyOf(configServer.getContentClusters(new DeploymentId(id, zone))));
return clusters.build();
}
/** 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());
}
/** Change the global endpoint status for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
findGlobalEndpoint(deployment).map(endpoint -> {
try {
configServer.setGlobalRotationStatus(deployment, endpoint.upstreamName(), status);
return endpoint;
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + deployment, e);
}
}).orElseThrow(() -> new IllegalArgumentException("No global endpoint exists for " + deployment));
}
/** Get global endpoint status for given deployment */
public Map<RoutingEndpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
return findGlobalEndpoint(deployment).map(endpoint -> {
try {
EndpointStatus status = configServer.getGlobalRotationStatus(deployment, endpoint.upstreamName());
return Map.of(endpoint, status);
} catch (Exception e) {
throw new RuntimeException("Failed to get rotation status of " + deployment, e);
}
}).orElseGet(Collections::emptyMap);
}
/** Find the global endpoint of given deployment, if any */
private Optional<RoutingEndpoint> findGlobalEndpoint(DeploymentId deployment) {
return routingGenerator.endpoints(deployment).stream()
.filter(RoutingEndpoint::isGlobal)
.findFirst();
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public Application createApplication(TenantAndApplicationId id, Optional<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());
Optional<Tenant> tenant = controller.tenants().get(id.tenant());
if (tenant.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
if (tenant.get().type() != Tenant.Type.user) {
if (credentials.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': No credentials provided");
accessControl.createApplication(id, credentials.get());
}
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) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
lockApplicationOrThrow(TenantAndApplicationId.from(id), 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");
store(application.withNewInstance(id.instance()));
log.info("Created " + id);
});
}
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options);
}
/** Deploys an application. If the application does not exist it is created. */
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 ( getApplication(applicationId).isEmpty()
&& controller.tenants().require(instanceId.tenant()).type() == Tenant.Type.user)
createApplication(applicationId, Optional.empty());
if (getInstance(instanceId).isEmpty())
createInstance(instanceId);
try (Lock deploymentLock = lockForDeployment(instanceId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<ApplicationCertificate> applicationCertificate;
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 + "."));
Optional<JobStatus> job = Optional.ofNullable(application.get().require(instance).deploymentJobs().jobStatus().get(jobType));
if ( job.isEmpty()
|| job.get().lastTriggered().isEmpty()
|| job.get().lastCompleted().isPresent() && job.get().lastCompleted().get().at().isAfter(job.get().lastTriggered().get().at()))
return unexpectedDeployment(instanceId, zone);
JobRun triggered = job.get().lastTriggered().get();
platformVersion = preferOldestVersion ? triggered.sourcePlatform().orElse(triggered.platform())
: triggered.platform();
applicationVersion = preferOldestVersion ? triggered.sourceApplication().orElse(triggered.application())
: triggered.application();
applicationPackage = getApplicationPackage(instanceId, application.get().internal(), applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, instanceId, jobType);
validateRun(application.get(), instance, zone, platformVersion, applicationVersion);
}
if (zone.environment().isProduction())
application = withRotation(application, instance);
endpoints = registerEndpointsInDns(application.get().deploymentSpec(), application.get().require(instanceId.instance()), zone);
if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
applicationCertificate = getApplicationCertificate(application.get().require(instance));
} else {
applicationCertificate = Optional.empty();
}
if ( ! preferOldestVersion
&& ! application.get().internal()
&& ! zone.environment().isManuallyDeployed()) {
storeWithUpdatedConfig(application, applicationPackage);
}
}
options = withVersion(platformVersion, options);
ActivateResult result = deploy(instanceId, applicationPackage, zone, options, endpoints,
applicationCertificate.orElse(null));
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, boolean internal, ApplicationVersion version) {
try {
return internal
? new ApplicationPackage(applicationStore.get(id, version))
: new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()));
}
catch (RuntimeException e) {
try {
log.info("Fetching application package for " + id + " from alternate repository; it is now deployed "
+ (internal ? "internally" : "externally") + "\nException was: " + Exceptions.toMessageString(e));
return internal
? new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()))
: new ApplicationPackage(applicationStore.get(id, version));
}
catch (RuntimeException s) {
e.addSuppressed(s);
throw e;
}
}
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public void storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
deploymentSpecValidator.validate(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
for (InstanceName instanceName : application.get().instances().keySet()) {
application = withoutDeletedDeployments(application, instanceName);
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
application = application.with(instanceName, instance -> withoutUnreferencedDeploymentJobs(deploymentSpec, instance));
}
store(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)
);
DeployOptions options = withVersion(version, DeployOptions.none());
return deploy(application.id(), applicationPackage, zone, options, Set.of(), /* No application cert */ null);
} 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, DeployOptions options) {
return deploy(tester.id(), applicationPackage, zone, options, Set.of(), /* No application cert for tester*/ null);
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, DeployOptions deployOptions, Set<ContainerEndpoint> endpoints,
ApplicationCertificate applicationCertificate) {
DeploymentId deploymentId = new DeploymentId(application, zone);
try {
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(deploymentId, deployOptions, Set.of(), endpoints, applicationCertificate, applicationPackage.zippedContent());
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
routingPolicies.refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
/** Makes sure the application has a global rotation, if eligible. */
private LockedApplication withRotation(LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(application.get().deploymentSpec(),
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
store(application);
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
private Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
var registerLegacyNames = deploymentSpec.globalServiceId().isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId())
.scope(Endpoint.Scope.global);
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
if (!registerLegacyNames) {
endpoints = endpoints.legacy(false);
}
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.asList().forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
private Optional<ApplicationCertificate> getApplicationCertificate(Instance instance) {
boolean provisionCertificate = provisionApplicationCertificate.with(FetchVector.Dimension.APPLICATION_ID,
instance.id().serializedForm()).value();
if (!provisionCertificate) {
return Optional.empty();
}
Optional<ApplicationCertificate> applicationCertificate = curator.readApplicationCertificate(instance.id());
if(applicationCertificate.isPresent())
return applicationCertificate;
ApplicationCertificate newCertificate = controller.serviceRegistry().applicationCertificateProvider().requestCaSignedCertificate(instance.id(), dnsNamesOf(instance.id()));
curator.writeApplicationCertificate(instance.id(), newCertificate);
return Optional.of(newCertificate);
}
/** Returns all valid DNS names of given application */
private List<String> dnsNamesOf(ApplicationId applicationId) {
List<String> endpointDnsNames = new ArrayList<>();
endpointDnsNames.add(Endpoint.createHashedCn(applicationId, controller.system()));
var globalDefaultEndpoint = Endpoint.of(applicationId).named(EndpointId.default_());
var rotationEndpoints = Endpoint.of(applicationId).wildcard();
var zoneLocalEndpoints = controller.zoneRegistry().zones().directlyRouted().zones().stream().flatMap(zone -> Stream.of(
Endpoint.of(applicationId).target(ClusterSpec.Id.from("default"), zone.getId()),
Endpoint.of(applicationId).wildcard(zone.getId())
));
Stream.concat(Stream.of(globalDefaultEndpoint, rotationEndpoints), zoneLocalEndpoints)
.map(Endpoint.EndpointBuilder::directRouting)
.map(endpoint -> endpoint.on(Endpoint.Port.tls()))
.map(endpointBuilder -> endpointBuilder.in(controller.system()))
.map(Endpoint::dnsName).forEach(endpointDnsNames::add);
return Collections.unmodifiableList(endpointDnsNames);
}
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 Instance withoutUnreferencedDeploymentJobs(DeploymentSpec deploymentSpec, Instance instance) {
for (JobType job : JobList.from(instance).production().mapToList(JobStatus::type)) {
ZoneId zone = job.zone(controller.system());
if (deploymentSpec.includes(zone.environment(), Optional.of(zone.region())))
continue;
instance = instance.withoutDeploymentJob(job);
}
return instance;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/** Returns the endpoints of the deployment, or empty if the request fails */
public List<URI> getDeploymentEndpoints(DeploymentId deploymentId) {
if ( ! getInstance(deploymentId.applicationId())
.map(application -> application.deployments().containsKey(deploymentId.zoneId()))
.orElse(deploymentId.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", deploymentId.toString());
try {
return ImmutableList.copyOf(routingGenerator.endpoints(deploymentId).stream()
.map(RoutingEndpoint::endpoint)
.map(URI::create)
.iterator());
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e);
return Collections.emptyList();
}
}
/** Returns the non-empty endpoints per cluster in the given deployment, or empty if endpoints can't be found. */
public Map<ClusterSpec.Id, URI> clusterEndpoints(DeploymentId id) {
if ( ! getInstance(id.applicationId())
.map(application -> application.deployments().containsKey(id.zoneId()))
.orElse(id.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", id.toString());
try {
var endpoints = routingGenerator.clusterEndpoints(id);
if ( ! endpoints.isEmpty())
return endpoints;
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + id, e);
}
return routingPolicies.get(id).stream()
.filter(policy -> policy.endpointIn(controller.system()).scope() == Endpoint.Scope.zone)
.collect(Collectors.toUnmodifiableMap(policy -> policy.cluster(),
policy -> policy.endpointIn(controller.system()).url()));
}
/** Returns all zone-specific cluster endpoints for the given application, in the given zones. */
public Map<ZoneId, Map<ClusterSpec.Id, URI>> clusterEndpoints(ApplicationId id, Collection<ZoneId> zones) {
Map<ZoneId, Map<ClusterSpec.Id, URI>> deployments = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (ZoneId zone : zones) {
var endpoints = clusterEndpoints(new DeploymentId(id, zone));
if ( ! endpoints.isEmpty())
deployments.put(zone, endpoints);
}
return Collections.unmodifiableMap(deployments);
}
/**
* 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, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(id.tenant());
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + id + "': No credentials provided");
List<ApplicationId> instances = requireApplication(id).instances().keySet().stream()
.map(id::instance)
.collect(Collectors.toUnmodifiableList());
if (instances.size() > 1)
throw new IllegalArgumentException("Could not delete application; more than one instance present: " + instances);
for (ApplicationId instance : instances)
deleteInstance(instance);
if (tenant.type() != Tenant.Type.user)
accessControl.deleteApplication(id, credentials.get());
curator.removeApplication(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(Collectors.joining(", ")));
applicationStore.removeAll(instanceId);
applicationStore.removeAll(TesterId.of(instanceId));
Instance instance = application.get().require(instanceId.instance());
instance.rotations().forEach(assignedRotation -> {
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId());
endpoints.asList().stream()
.map(Endpoint::dnsName)
.forEach(name -> {
controller.nameServiceForwarder().removeRecords(Record.Type.CNAME, RecordName.from(name), Priority.normal);
});
});
curator.writeApplication(application.without(instanceId.instance()).get());
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 {
routingPolicies.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(Application application, InstanceName instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = application.require(instance).deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! application.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).",
application.id().instance(instance), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/** Returns the rotation repository, used for managing global rotation assignments */
public RotationRepository rotationRepository() {
return rotationRepository;
}
public RoutingPolicies routingPolicies() {
return routingPolicies;
}
/**
* 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, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
applicationPackage.deploymentSpec().athenzDomain().ifPresent(identityDomain -> {
Tenant tenant = controller.tenants().require(tenantName);
deployer.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.ifPresentOrElse(user -> {
if ( ! ((AthenzFacade) accessControl).hasTenantAdminAccess(user, new AthenzDomain(identityDomain.value())))
throw new IllegalArgumentException("User " + user.getFullName() + " is not allowed to launch " +
"services in Athenz domain " + identityDomain.value() + ". " +
"Please reach out to the domain admin.");
},
() -> {
if (tenant.type() != Tenant.Type.athenz)
throw new IllegalArgumentException("Athenz domain defined in deployment.xml, but no " +
"Athenz domain for tenant " + tenantName.value());
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain.getName(), identityDomain.value()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.value() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
});
});
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(athenzDomain -> {
controller.zoneRegistry().zones().reachable().ids()
.forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService(zone.environment(), zone.region())
.map(service -> new AthenzService(athenzDomain.value(), service.value()))
.ifPresent(service -> {
boolean allowedToLaunch = ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, service);
if (!allowedToLaunch)
throw new IllegalArgumentException("Not allowed to launch Athenz service " + service.getFullName());
});
});
});
}
/** Returns the latest known version within the given major. */
private 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 RotationRepository rotationRepository;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final RoutingGenerator routingGenerator;
private final RoutingPolicies routingPolicies;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final BooleanFlag provisionApplicationCertificate;
private final DeploymentSpecValidator deploymentSpecValidator;
ApplicationController(Controller controller, CuratorDb curator,
AccessControl accessControl, RotationsConfig rotationsConfig,
Clock clock) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.routingGenerator = controller.serviceRegistry().routingGenerator();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
routingPolicies = new RoutingPolicies(controller);
rotationRepository = new RotationRepository(rotationsConfig, this, curator);
deploymentTrigger = new DeploymentTrigger(controller, controller.serviceRegistry().buildService(), clock);
provisionApplicationCertificate = Flags.PROVISION_APPLICATION_CERTIFICATE.bindTo(controller.flagSource());
deploymentSpecValidator = new DeploymentSpecValidator(controller);
Once.after(Duration.ofMinutes(1), () -> {
Instant start = clock.instant();
int count = 0;
for (Application application : curator.readApplications()) {
lockApplicationIfPresent(application.id(), this::store);
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 application with the given id, or null if it is not present */
public Optional<Application> getApplication(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id));
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(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();
}
/** 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(ApplicationId id, Iterable<ZoneId> zones) {
ImmutableMap.Builder<ZoneId, List<String>> clusters = ImmutableMap.builder();
for (ZoneId zone : zones)
clusters.put(zone, ImmutableList.copyOf(configServer.getContentClusters(new DeploymentId(id, zone))));
return clusters.build();
}
/** 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());
}
/** Change the global endpoint status for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
findGlobalEndpoint(deployment).map(endpoint -> {
try {
configServer.setGlobalRotationStatus(deployment, endpoint.upstreamName(), status);
return endpoint;
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + deployment, e);
}
}).orElseThrow(() -> new IllegalArgumentException("No global endpoint exists for " + deployment));
}
/** Get global endpoint status for given deployment */
public Map<RoutingEndpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
return findGlobalEndpoint(deployment).map(endpoint -> {
try {
EndpointStatus status = configServer.getGlobalRotationStatus(deployment, endpoint.upstreamName());
return Map.of(endpoint, status);
} catch (Exception e) {
throw new RuntimeException("Failed to get rotation status of " + deployment, e);
}
}).orElseGet(Collections::emptyMap);
}
/** Find the global endpoint of given deployment, if any */
private Optional<RoutingEndpoint> findGlobalEndpoint(DeploymentId deployment) {
return routingGenerator.endpoints(deployment).stream()
.filter(RoutingEndpoint::isGlobal)
.findFirst();
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public Application createApplication(TenantAndApplicationId id, Optional<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());
Optional<Tenant> tenant = controller.tenants().get(id.tenant());
if (tenant.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
if (tenant.get().type() != Tenant.Type.user) {
if (credentials.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': No credentials provided");
accessControl.createApplication(id, credentials.get());
}
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) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
lockApplicationOrThrow(TenantAndApplicationId.from(id), 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");
store(application.withNewInstance(id.instance()));
log.info("Created " + id);
});
}
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options);
}
/** Deploys an application. If the application does not exist it is created. */
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 ( getApplication(applicationId).isEmpty()
&& controller.tenants().require(instanceId.tenant()).type() == Tenant.Type.user)
createApplication(applicationId, Optional.empty());
if (getInstance(instanceId).isEmpty())
createInstance(instanceId);
try (Lock deploymentLock = lockForDeployment(instanceId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<ApplicationCertificate> applicationCertificate;
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 + "."));
Optional<JobStatus> job = Optional.ofNullable(application.get().require(instance).deploymentJobs().jobStatus().get(jobType));
if ( job.isEmpty()
|| job.get().lastTriggered().isEmpty()
|| job.get().lastCompleted().isPresent() && job.get().lastCompleted().get().at().isAfter(job.get().lastTriggered().get().at()))
return unexpectedDeployment(instanceId, zone);
JobRun triggered = job.get().lastTriggered().get();
platformVersion = preferOldestVersion ? triggered.sourcePlatform().orElse(triggered.platform())
: triggered.platform();
applicationVersion = preferOldestVersion ? triggered.sourceApplication().orElse(triggered.application())
: triggered.application();
applicationPackage = getApplicationPackage(instanceId, application.get().internal(), applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, instanceId, jobType);
validateRun(application.get(), instance, zone, platformVersion, applicationVersion);
}
if (zone.environment().isProduction())
application = withRotation(application, instance);
endpoints = registerEndpointsInDns(application.get().deploymentSpec(), application.get().require(instanceId.instance()), zone);
if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
applicationCertificate = getApplicationCertificate(application.get().require(instance));
} else {
applicationCertificate = Optional.empty();
}
if ( ! preferOldestVersion
&& ! application.get().internal()
&& ! zone.environment().isManuallyDeployed()) {
storeWithUpdatedConfig(application, applicationPackage);
}
}
options = withVersion(platformVersion, options);
ActivateResult result = deploy(instanceId, applicationPackage, zone, options, endpoints,
applicationCertificate.orElse(null));
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, boolean internal, ApplicationVersion version) {
try {
return internal
? new ApplicationPackage(applicationStore.get(id, version))
: new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()));
}
catch (RuntimeException e) {
try {
log.info("Fetching application package for " + id + " from alternate repository; it is now deployed "
+ (internal ? "internally" : "externally") + "\nException was: " + Exceptions.toMessageString(e));
return internal
? new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()))
: new ApplicationPackage(applicationStore.get(id, version));
}
catch (RuntimeException s) {
e.addSuppressed(s);
throw e;
}
}
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public void storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
deploymentSpecValidator.validate(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
for (InstanceName instanceName : application.get().instances().keySet()) {
application = withoutDeletedDeployments(application, instanceName);
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
application = application.with(instanceName, instance -> withoutUnreferencedDeploymentJobs(deploymentSpec, instance));
}
store(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)
);
DeployOptions options = withVersion(version, DeployOptions.none());
return deploy(application.id(), applicationPackage, zone, options, Set.of(), /* No application cert */ null);
} 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, DeployOptions options) {
return deploy(tester.id(), applicationPackage, zone, options, Set.of(), /* No application cert for tester*/ null);
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, DeployOptions deployOptions, Set<ContainerEndpoint> endpoints,
ApplicationCertificate applicationCertificate) {
DeploymentId deploymentId = new DeploymentId(application, zone);
try {
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(deploymentId, deployOptions, Set.of(), endpoints, applicationCertificate, applicationPackage.zippedContent());
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
routingPolicies.refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
/** Makes sure the application has a global rotation, if eligible. */
private LockedApplication withRotation(LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(application.get().deploymentSpec(),
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
store(application);
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
private Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
var registerLegacyNames = deploymentSpec.globalServiceId().isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId())
.scope(Endpoint.Scope.global);
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
if (!registerLegacyNames) {
endpoints = endpoints.legacy(false);
}
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.asList().forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
private Optional<ApplicationCertificate> getApplicationCertificate(Instance instance) {
boolean provisionCertificate = provisionApplicationCertificate.with(FetchVector.Dimension.APPLICATION_ID,
instance.id().serializedForm()).value();
if (!provisionCertificate) {
return Optional.empty();
}
Optional<ApplicationCertificate> applicationCertificate = curator.readApplicationCertificate(instance.id());
if(applicationCertificate.isPresent())
return applicationCertificate;
ApplicationCertificate newCertificate = controller.serviceRegistry().applicationCertificateProvider().requestCaSignedCertificate(instance.id(), dnsNamesOf(instance.id()));
curator.writeApplicationCertificate(instance.id(), newCertificate);
return Optional.of(newCertificate);
}
/** Returns all valid DNS names of given application */
private List<String> dnsNamesOf(ApplicationId applicationId) {
List<String> endpointDnsNames = new ArrayList<>();
endpointDnsNames.add(Endpoint.createHashedCn(applicationId, controller.system()));
var globalDefaultEndpoint = Endpoint.of(applicationId).named(EndpointId.default_());
var rotationEndpoints = Endpoint.of(applicationId).wildcard();
var zoneLocalEndpoints = controller.zoneRegistry().zones().directlyRouted().zones().stream().flatMap(zone -> Stream.of(
Endpoint.of(applicationId).target(ClusterSpec.Id.from("default"), zone.getId()),
Endpoint.of(applicationId).wildcard(zone.getId())
));
Stream.concat(Stream.of(globalDefaultEndpoint, rotationEndpoints), zoneLocalEndpoints)
.map(Endpoint.EndpointBuilder::directRouting)
.map(endpoint -> endpoint.on(Endpoint.Port.tls()))
.map(endpointBuilder -> endpointBuilder.in(controller.system()))
.map(Endpoint::dnsName).forEach(endpointDnsNames::add);
return Collections.unmodifiableList(endpointDnsNames);
}
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 Instance withoutUnreferencedDeploymentJobs(DeploymentSpec deploymentSpec, Instance instance) {
for (JobType job : JobList.from(instance).production().mapToList(JobStatus::type)) {
ZoneId zone = job.zone(controller.system());
if (deploymentSpec.includes(zone.environment(), Optional.of(zone.region())))
continue;
instance = instance.withoutDeploymentJob(job);
}
return instance;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/** Returns the endpoints of the deployment, or empty if the request fails */
public List<URI> getDeploymentEndpoints(DeploymentId deploymentId) {
if ( ! getInstance(deploymentId.applicationId())
.map(application -> application.deployments().containsKey(deploymentId.zoneId()))
.orElse(deploymentId.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", deploymentId.toString());
try {
return ImmutableList.copyOf(routingGenerator.endpoints(deploymentId).stream()
.map(RoutingEndpoint::endpoint)
.map(URI::create)
.iterator());
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e);
return Collections.emptyList();
}
}
/** Returns the non-empty endpoints per cluster in the given deployment, or empty if endpoints can't be found. */
public Map<ClusterSpec.Id, URI> clusterEndpoints(DeploymentId id) {
if ( ! getInstance(id.applicationId())
.map(application -> application.deployments().containsKey(id.zoneId()))
.orElse(id.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", id.toString());
try {
var endpoints = routingGenerator.clusterEndpoints(id);
if ( ! endpoints.isEmpty())
return endpoints;
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + id, e);
}
return routingPolicies.get(id).stream()
.filter(policy -> policy.endpointIn(controller.system()).scope() == Endpoint.Scope.zone)
.collect(Collectors.toUnmodifiableMap(policy -> policy.cluster(),
policy -> policy.endpointIn(controller.system()).url()));
}
/** Returns all zone-specific cluster endpoints for the given application, in the given zones. */
public Map<ZoneId, Map<ClusterSpec.Id, URI>> clusterEndpoints(ApplicationId id, Collection<ZoneId> zones) {
Map<ZoneId, Map<ClusterSpec.Id, URI>> deployments = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (ZoneId zone : zones) {
var endpoints = clusterEndpoints(new DeploymentId(id, zone));
if ( ! endpoints.isEmpty())
deployments.put(zone, endpoints);
}
return Collections.unmodifiableMap(deployments);
}
/**
* 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, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(id.tenant());
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + id + "': No credentials provided");
List<ApplicationId> instances = requireApplication(id).instances().keySet().stream()
.map(id::instance)
.collect(Collectors.toUnmodifiableList());
if (instances.size() > 1)
throw new IllegalArgumentException("Could not delete application; more than one instance present: " + instances);
for (ApplicationId instance : instances)
deleteInstance(instance);
if (tenant.type() != Tenant.Type.user)
accessControl.deleteApplication(id, credentials.get());
curator.removeApplication(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(Collectors.joining(", ")));
applicationStore.removeAll(instanceId);
applicationStore.removeAll(TesterId.of(instanceId));
Instance instance = application.get().require(instanceId.instance());
instance.rotations().forEach(assignedRotation -> {
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId());
endpoints.asList().stream()
.map(Endpoint::dnsName)
.forEach(name -> {
controller.nameServiceForwarder().removeRecords(Record.Type.CNAME, RecordName.from(name), Priority.normal);
});
});
curator.writeApplication(application.without(instanceId.instance()).get());
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 {
routingPolicies.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(Application application, InstanceName instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = application.require(instance).deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! application.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).",
application.id().instance(instance), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/** Returns the rotation repository, used for managing global rotation assignments */
public RotationRepository rotationRepository() {
return rotationRepository;
}
public RoutingPolicies routingPolicies() {
return routingPolicies;
}
/**
* 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, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
applicationPackage.deploymentSpec().athenzDomain().ifPresent(identityDomain -> {
Tenant tenant = controller.tenants().require(tenantName);
deployer.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.ifPresentOrElse(user -> {
if ( ! ((AthenzFacade) accessControl).hasTenantAdminAccess(user, new AthenzDomain(identityDomain.value())))
throw new IllegalArgumentException("User " + user.getFullName() + " is not allowed to launch " +
"services in Athenz domain " + identityDomain.value() + ". " +
"Please reach out to the domain admin.");
},
() -> {
if (tenant.type() != Tenant.Type.athenz)
throw new IllegalArgumentException("Athenz domain defined in deployment.xml, but no " +
"Athenz domain for tenant " + tenantName.value());
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain.getName(), identityDomain.value()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.value() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
});
});
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(athenzDomain -> {
controller.zoneRegistry().zones().reachable().ids()
.forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService(zone.environment(), zone.region())
.map(service -> new AthenzService(athenzDomain.value(), service.value()))
.ifPresent(service -> {
boolean allowedToLaunch = ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, service);
if (!allowedToLaunch)
throw new IllegalArgumentException("Not allowed to launch Athenz service " + service.getFullName());
});
});
});
}
/** Returns the latest known version within the given major. */
private 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);
}
} |
This | private LockedApplication withoutDeletedDeployments(LockedApplication application, InstanceName instance) {
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
List<Deployment> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.filter(deployment -> ! deploymentSpec.requireInstance(instance).includes(deployment.zone().environment(),
Optional.of(deployment.zone().region())))
.collect(Collectors.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(deployment -> deployment.zone().region().value())
.collect(Collectors.joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
for (Deployment deployment : deploymentsToRemove)
application = deactivate(application, instance, deployment.zone());
return application;
} | .filter(deployment -> ! deploymentSpec.requireInstance(instance).includes(deployment.zone().environment(), | private LockedApplication withoutDeletedDeployments(LockedApplication application, InstanceName instance) {
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
List<Deployment> deploymentsToRemove = application.get().require(instance).productionDeployments().values().stream()
.filter(deployment -> ! deploymentSpec.requireInstance(instance).includes(deployment.zone().environment(),
Optional.of(deployment.zone().region())))
.collect(Collectors.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(deployment -> deployment.zone().region().value())
.collect(Collectors.joining(", ")) +
", but does not include " +
(deploymentsToRemove.size() > 1 ? "these zones" : "this zone") +
" in deployment.xml. " +
ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval));
for (Deployment deployment : deploymentsToRemove)
application = deactivate(application, instance, deployment.zone());
return application;
} | 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 RotationRepository rotationRepository;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final RoutingGenerator routingGenerator;
private final RoutingPolicies routingPolicies;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final BooleanFlag provisionApplicationCertificate;
private final DeploymentSpecValidator deploymentSpecValidator;
ApplicationController(Controller controller, CuratorDb curator,
AccessControl accessControl, RotationsConfig rotationsConfig,
Clock clock) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.routingGenerator = controller.serviceRegistry().routingGenerator();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
routingPolicies = new RoutingPolicies(controller);
rotationRepository = new RotationRepository(rotationsConfig, this, curator);
deploymentTrigger = new DeploymentTrigger(controller, controller.serviceRegistry().buildService(), clock);
provisionApplicationCertificate = Flags.PROVISION_APPLICATION_CERTIFICATE.bindTo(controller.flagSource());
deploymentSpecValidator = new DeploymentSpecValidator(controller);
Once.after(Duration.ofMinutes(1), () -> {
Instant start = clock.instant();
int count = 0;
for (Application application : curator.readApplications()) {
lockApplicationIfPresent(application.id(), this::store);
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 application with the given id, or null if it is not present */
public Optional<Application> getApplication(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id));
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(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();
}
/** 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(ApplicationId id, Iterable<ZoneId> zones) {
ImmutableMap.Builder<ZoneId, List<String>> clusters = ImmutableMap.builder();
for (ZoneId zone : zones)
clusters.put(zone, ImmutableList.copyOf(configServer.getContentClusters(new DeploymentId(id, zone))));
return clusters.build();
}
/** 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());
}
/** Change the global endpoint status for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
findGlobalEndpoint(deployment).map(endpoint -> {
try {
configServer.setGlobalRotationStatus(deployment, endpoint.upstreamName(), status);
return endpoint;
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + deployment, e);
}
}).orElseThrow(() -> new IllegalArgumentException("No global endpoint exists for " + deployment));
}
/** Get global endpoint status for given deployment */
public Map<RoutingEndpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
return findGlobalEndpoint(deployment).map(endpoint -> {
try {
EndpointStatus status = configServer.getGlobalRotationStatus(deployment, endpoint.upstreamName());
return Map.of(endpoint, status);
} catch (Exception e) {
throw new RuntimeException("Failed to get rotation status of " + deployment, e);
}
}).orElseGet(Collections::emptyMap);
}
/** Find the global endpoint of given deployment, if any */
private Optional<RoutingEndpoint> findGlobalEndpoint(DeploymentId deployment) {
return routingGenerator.endpoints(deployment).stream()
.filter(RoutingEndpoint::isGlobal)
.findFirst();
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public Application createApplication(TenantAndApplicationId id, Optional<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());
Optional<Tenant> tenant = controller.tenants().get(id.tenant());
if (tenant.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
if (tenant.get().type() != Tenant.Type.user) {
if (credentials.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': No credentials provided");
accessControl.createApplication(id, credentials.get());
}
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) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
lockApplicationOrThrow(TenantAndApplicationId.from(id), 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");
store(application.withNewInstance(id.instance()));
log.info("Created " + id);
});
}
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options);
}
/** Deploys an application. If the application does not exist it is created. */
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 ( getApplication(applicationId).isEmpty()
&& controller.tenants().require(instanceId.tenant()).type() == Tenant.Type.user)
createApplication(applicationId, Optional.empty());
if (getInstance(instanceId).isEmpty())
createInstance(instanceId);
try (Lock deploymentLock = lockForDeployment(instanceId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<ApplicationCertificate> applicationCertificate;
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 + "."));
Optional<JobStatus> job = Optional.ofNullable(application.get().require(instance).deploymentJobs().jobStatus().get(jobType));
if ( job.isEmpty()
|| job.get().lastTriggered().isEmpty()
|| job.get().lastCompleted().isPresent() && job.get().lastCompleted().get().at().isAfter(job.get().lastTriggered().get().at()))
return unexpectedDeployment(instanceId, zone);
JobRun triggered = job.get().lastTriggered().get();
platformVersion = preferOldestVersion ? triggered.sourcePlatform().orElse(triggered.platform())
: triggered.platform();
applicationVersion = preferOldestVersion ? triggered.sourceApplication().orElse(triggered.application())
: triggered.application();
applicationPackage = getApplicationPackage(instanceId, application.get().internal(), applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, instanceId, jobType);
validateRun(application.get(), instance, zone, platformVersion, applicationVersion);
}
if (zone.environment().isProduction())
application = withRotation(applicationPackage.deploymentSpec(), application, instance);
endpoints = registerEndpointsInDns(applicationPackage.deploymentSpec(), application.get().require(instanceId.instance()), zone);
if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
applicationCertificate = getApplicationCertificate(application.get().require(instance));
} else {
applicationCertificate = Optional.empty();
}
if ( ! preferOldestVersion
&& ! application.get().internal()
&& ! zone.environment().isManuallyDeployed()) {
storeWithUpdatedConfig(application, applicationPackage);
}
}
options = withVersion(platformVersion, options);
ActivateResult result = deploy(instanceId, applicationPackage, zone, options, endpoints,
applicationCertificate.orElse(null));
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, boolean internal, ApplicationVersion version) {
try {
return internal
? new ApplicationPackage(applicationStore.get(id, version))
: new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()));
}
catch (RuntimeException e) {
try {
log.info("Fetching application package for " + id + " from alternate repository; it is now deployed "
+ (internal ? "internally" : "externally") + "\nException was: " + Exceptions.toMessageString(e));
return internal
? new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()))
: new ApplicationPackage(applicationStore.get(id, version));
}
catch (RuntimeException s) {
e.addSuppressed(s);
throw e;
}
}
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public void storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
deploymentSpecValidator.validate(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
for (InstanceName instanceName : application.get().instances().keySet()) {
application = withoutDeletedDeployments(application, instanceName);
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
application = application.with(instanceName, instance -> withoutUnreferencedDeploymentJobs(deploymentSpec, instance));
}
store(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)
);
DeployOptions options = withVersion(version, DeployOptions.none());
return deploy(application.id(), applicationPackage, zone, options, Set.of(), /* No application cert */ null);
} 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, DeployOptions options) {
return deploy(tester.id(), applicationPackage, zone, options, Set.of(), /* No application cert for tester*/ null);
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, DeployOptions deployOptions, Set<ContainerEndpoint> endpoints,
ApplicationCertificate applicationCertificate) {
DeploymentId deploymentId = new DeploymentId(application, zone);
try {
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(deploymentId, deployOptions, Set.of(), endpoints, applicationCertificate, applicationPackage.zippedContent());
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
routingPolicies.refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
/** Makes sure the application has a global rotation, if eligible. */
private LockedApplication withRotation(DeploymentSpec deploymentSpec, LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(deploymentSpec,
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
store(application);
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
private Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
boolean registerLegacyNames = deploymentSpec.instance(instance.name()).flatMap(i -> i.globalServiceId()).isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId())
.scope(Endpoint.Scope.global);
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
if (!registerLegacyNames) {
endpoints = endpoints.legacy(false);
}
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.asList().forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
private Optional<ApplicationCertificate> getApplicationCertificate(Instance instance) {
boolean provisionCertificate = provisionApplicationCertificate.with(FetchVector.Dimension.APPLICATION_ID,
instance.id().serializedForm()).value();
if (!provisionCertificate) {
return Optional.empty();
}
Optional<ApplicationCertificate> applicationCertificate = curator.readApplicationCertificate(instance.id());
if(applicationCertificate.isPresent())
return applicationCertificate;
ApplicationCertificate newCertificate = controller.serviceRegistry().applicationCertificateProvider().requestCaSignedCertificate(instance.id(), dnsNamesOf(instance.id()));
curator.writeApplicationCertificate(instance.id(), newCertificate);
return Optional.of(newCertificate);
}
/** Returns all valid DNS names of given application */
private List<String> dnsNamesOf(ApplicationId applicationId) {
List<String> endpointDnsNames = new ArrayList<>();
endpointDnsNames.add(Endpoint.createHashedCn(applicationId, controller.system()));
var globalDefaultEndpoint = Endpoint.of(applicationId).named(EndpointId.default_());
var rotationEndpoints = Endpoint.of(applicationId).wildcard();
var zoneLocalEndpoints = controller.zoneRegistry().zones().directlyRouted().zones().stream().flatMap(zone -> Stream.of(
Endpoint.of(applicationId).target(ClusterSpec.Id.from("default"), zone.getId()),
Endpoint.of(applicationId).wildcard(zone.getId())
));
Stream.concat(Stream.of(globalDefaultEndpoint, rotationEndpoints), zoneLocalEndpoints)
.map(Endpoint.EndpointBuilder::directRouting)
.map(endpoint -> endpoint.on(Endpoint.Port.tls()))
.map(endpointBuilder -> endpointBuilder.in(controller.system()))
.map(Endpoint::dnsName).forEach(endpointDnsNames::add);
return Collections.unmodifiableList(endpointDnsNames);
}
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 Instance withoutUnreferencedDeploymentJobs(DeploymentSpec deploymentSpec, Instance instance) {
for (JobType job : JobList.from(instance).production().mapToList(JobStatus::type)) {
ZoneId zone = job.zone(controller.system());
if (deploymentSpec.requireInstance(instance.name()).includes(zone.environment(), Optional.of(zone.region())))
continue;
instance = instance.withoutDeploymentJob(job);
}
return instance;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/** Returns the endpoints of the deployment, or empty if the request fails */
public List<URI> getDeploymentEndpoints(DeploymentId deploymentId) {
if ( ! getInstance(deploymentId.applicationId())
.map(application -> application.deployments().containsKey(deploymentId.zoneId()))
.orElse(deploymentId.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", deploymentId.toString());
try {
return ImmutableList.copyOf(routingGenerator.endpoints(deploymentId).stream()
.map(RoutingEndpoint::endpoint)
.map(URI::create)
.iterator());
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e);
return Collections.emptyList();
}
}
/** Returns the non-empty endpoints per cluster in the given deployment, or empty if endpoints can't be found. */
public Map<ClusterSpec.Id, URI> clusterEndpoints(DeploymentId id) {
if ( ! getInstance(id.applicationId())
.map(application -> application.deployments().containsKey(id.zoneId()))
.orElse(id.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", id.toString());
try {
var endpoints = routingGenerator.clusterEndpoints(id);
if ( ! endpoints.isEmpty())
return endpoints;
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + id, e);
}
return routingPolicies.get(id).stream()
.filter(policy -> policy.endpointIn(controller.system()).scope() == Endpoint.Scope.zone)
.collect(Collectors.toUnmodifiableMap(policy -> policy.cluster(),
policy -> policy.endpointIn(controller.system()).url()));
}
/** Returns all zone-specific cluster endpoints for the given application, in the given zones. */
public Map<ZoneId, Map<ClusterSpec.Id, URI>> clusterEndpoints(ApplicationId id, Collection<ZoneId> zones) {
Map<ZoneId, Map<ClusterSpec.Id, URI>> deployments = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (ZoneId zone : zones) {
var endpoints = clusterEndpoints(new DeploymentId(id, zone));
if ( ! endpoints.isEmpty())
deployments.put(zone, endpoints);
}
return Collections.unmodifiableMap(deployments);
}
/**
* 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, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(id.tenant());
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + id + "': No credentials provided");
List<ApplicationId> instances = requireApplication(id).instances().keySet().stream()
.map(id::instance)
.collect(Collectors.toUnmodifiableList());
if (instances.size() > 1)
throw new IllegalArgumentException("Could not delete application; more than one instance present: " + instances);
for (ApplicationId instance : instances)
deleteInstance(instance);
if (tenant.type() != Tenant.Type.user)
accessControl.deleteApplication(id, credentials.get());
curator.removeApplication(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(Collectors.joining(", ")));
applicationStore.removeAll(instanceId);
applicationStore.removeAll(TesterId.of(instanceId));
Instance instance = application.get().require(instanceId.instance());
instance.rotations().forEach(assignedRotation -> {
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId());
endpoints.asList().stream()
.map(Endpoint::dnsName)
.forEach(name -> {
controller.nameServiceForwarder().removeRecords(Record.Type.CNAME, RecordName.from(name), Priority.normal);
});
});
curator.writeApplication(application.without(instanceId.instance()).get());
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 {
routingPolicies.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(Application application, InstanceName instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = application.require(instance).deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! application.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).",
application.id().instance(instance), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/** Returns the rotation repository, used for managing global rotation assignments */
public RotationRepository rotationRepository() {
return rotationRepository;
}
public RoutingPolicies routingPolicies() {
return routingPolicies;
}
/**
* 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, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
applicationPackage.deploymentSpec().athenzDomain().ifPresent(identityDomain -> {
Tenant tenant = controller.tenants().require(tenantName);
deployer.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.ifPresentOrElse(user -> {
if ( ! ((AthenzFacade) accessControl).hasTenantAdminAccess(user, new AthenzDomain(identityDomain.value())))
throw new IllegalArgumentException("User " + user.getFullName() + " is not allowed to launch " +
"services in Athenz domain " + identityDomain.value() + ". " +
"Please reach out to the domain admin.");
},
() -> {
if (tenant.type() != Tenant.Type.athenz)
throw new IllegalArgumentException("Athenz domain defined in deployment.xml, but no " +
"Athenz domain for tenant " + tenantName.value());
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain.getName(), identityDomain.value()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.value() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
});
});
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(athenzDomain -> {
controller.zoneRegistry().zones().reachable().ids()
.forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService(zone.environment(), zone.region())
.map(service -> new AthenzService(athenzDomain.value(), service.value()))
.ifPresent(service -> {
boolean allowedToLaunch = ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, service);
if (!allowedToLaunch)
throw new IllegalArgumentException("Not allowed to launch Athenz service " + service.getFullName());
});
});
});
}
/** Returns the latest known version within the given major. */
private 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 RotationRepository rotationRepository;
private final AccessControl accessControl;
private final ConfigServer configServer;
private final RoutingGenerator routingGenerator;
private final RoutingPolicies routingPolicies;
private final Clock clock;
private final DeploymentTrigger deploymentTrigger;
private final BooleanFlag provisionApplicationCertificate;
private final DeploymentSpecValidator deploymentSpecValidator;
ApplicationController(Controller controller, CuratorDb curator,
AccessControl accessControl, RotationsConfig rotationsConfig,
Clock clock) {
this.controller = controller;
this.curator = curator;
this.accessControl = accessControl;
this.configServer = controller.serviceRegistry().configServer();
this.routingGenerator = controller.serviceRegistry().routingGenerator();
this.clock = clock;
this.artifactRepository = controller.serviceRegistry().artifactRepository();
this.applicationStore = controller.serviceRegistry().applicationStore();
routingPolicies = new RoutingPolicies(controller);
rotationRepository = new RotationRepository(rotationsConfig, this, curator);
deploymentTrigger = new DeploymentTrigger(controller, controller.serviceRegistry().buildService(), clock);
provisionApplicationCertificate = Flags.PROVISION_APPLICATION_CERTIFICATE.bindTo(controller.flagSource());
deploymentSpecValidator = new DeploymentSpecValidator(controller);
Once.after(Duration.ofMinutes(1), () -> {
Instant start = clock.instant();
int count = 0;
for (Application application : curator.readApplications()) {
lockApplicationIfPresent(application.id(), this::store);
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 application with the given id, or null if it is not present */
public Optional<Application> getApplication(ApplicationId id) {
return getApplication(TenantAndApplicationId.from(id));
}
/** Returns the instance with the given id, or null if it is not present */
public Optional<Instance> getInstance(ApplicationId id) {
return getApplication(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();
}
/** 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(ApplicationId id, Iterable<ZoneId> zones) {
ImmutableMap.Builder<ZoneId, List<String>> clusters = ImmutableMap.builder();
for (ZoneId zone : zones)
clusters.put(zone, ImmutableList.copyOf(configServer.getContentClusters(new DeploymentId(id, zone))));
return clusters.build();
}
/** 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());
}
/** Change the global endpoint status for given deployment */
public void setGlobalRotationStatus(DeploymentId deployment, EndpointStatus status) {
findGlobalEndpoint(deployment).map(endpoint -> {
try {
configServer.setGlobalRotationStatus(deployment, endpoint.upstreamName(), status);
return endpoint;
} catch (Exception e) {
throw new RuntimeException("Failed to set rotation status of " + deployment, e);
}
}).orElseThrow(() -> new IllegalArgumentException("No global endpoint exists for " + deployment));
}
/** Get global endpoint status for given deployment */
public Map<RoutingEndpoint, EndpointStatus> globalRotationStatus(DeploymentId deployment) {
return findGlobalEndpoint(deployment).map(endpoint -> {
try {
EndpointStatus status = configServer.getGlobalRotationStatus(deployment, endpoint.upstreamName());
return Map.of(endpoint, status);
} catch (Exception e) {
throw new RuntimeException("Failed to get rotation status of " + deployment, e);
}
}).orElseGet(Collections::emptyMap);
}
/** Find the global endpoint of given deployment, if any */
private Optional<RoutingEndpoint> findGlobalEndpoint(DeploymentId deployment) {
return routingGenerator.endpoints(deployment).stream()
.filter(RoutingEndpoint::isGlobal)
.findFirst();
}
/**
* Creates a new application for an existing tenant.
*
* @throws IllegalArgumentException if the application already exists
*/
public Application createApplication(TenantAndApplicationId id, Optional<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());
Optional<Tenant> tenant = controller.tenants().get(id.tenant());
if (tenant.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist");
if (tenant.get().type() != Tenant.Type.user) {
if (credentials.isEmpty())
throw new IllegalArgumentException("Could not create '" + id + "': No credentials provided");
accessControl.createApplication(id, credentials.get());
}
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) {
if (id.instance().isTester())
throw new IllegalArgumentException("'" + id + "' is a tester application!");
lockApplicationOrThrow(TenantAndApplicationId.from(id), 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");
store(application.withNewInstance(id.instance()));
log.info("Created " + id);
});
}
public ActivateResult deploy(ApplicationId applicationId, ZoneId zone,
Optional<ApplicationPackage> applicationPackageFromDeployer,
DeployOptions options) {
return deploy(applicationId, zone, applicationPackageFromDeployer, Optional.empty(), options);
}
/** Deploys an application. If the application does not exist it is created. */
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 ( getApplication(applicationId).isEmpty()
&& controller.tenants().require(instanceId.tenant()).type() == Tenant.Type.user)
createApplication(applicationId, Optional.empty());
if (getInstance(instanceId).isEmpty())
createInstance(instanceId);
try (Lock deploymentLock = lockForDeployment(instanceId, zone)) {
Version platformVersion;
ApplicationVersion applicationVersion;
ApplicationPackage applicationPackage;
Set<ContainerEndpoint> endpoints;
Optional<ApplicationCertificate> applicationCertificate;
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 + "."));
Optional<JobStatus> job = Optional.ofNullable(application.get().require(instance).deploymentJobs().jobStatus().get(jobType));
if ( job.isEmpty()
|| job.get().lastTriggered().isEmpty()
|| job.get().lastCompleted().isPresent() && job.get().lastCompleted().get().at().isAfter(job.get().lastTriggered().get().at()))
return unexpectedDeployment(instanceId, zone);
JobRun triggered = job.get().lastTriggered().get();
platformVersion = preferOldestVersion ? triggered.sourcePlatform().orElse(triggered.platform())
: triggered.platform();
applicationVersion = preferOldestVersion ? triggered.sourceApplication().orElse(triggered.application())
: triggered.application();
applicationPackage = getApplicationPackage(instanceId, application.get().internal(), applicationVersion);
applicationPackage = withTesterCertificate(applicationPackage, instanceId, jobType);
validateRun(application.get(), instance, zone, platformVersion, applicationVersion);
}
if (zone.environment().isProduction())
application = withRotation(applicationPackage.deploymentSpec(), application, instance);
endpoints = registerEndpointsInDns(applicationPackage.deploymentSpec(), application.get().require(instanceId.instance()), zone);
if (controller.zoneRegistry().zones().directlyRouted().ids().contains(zone)) {
applicationCertificate = getApplicationCertificate(application.get().require(instance));
} else {
applicationCertificate = Optional.empty();
}
if ( ! preferOldestVersion
&& ! application.get().internal()
&& ! zone.environment().isManuallyDeployed()) {
storeWithUpdatedConfig(application, applicationPackage);
}
}
options = withVersion(platformVersion, options);
ActivateResult result = deploy(instanceId, applicationPackage, zone, options, endpoints,
applicationCertificate.orElse(null));
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, boolean internal, ApplicationVersion version) {
try {
return internal
? new ApplicationPackage(applicationStore.get(id, version))
: new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()));
}
catch (RuntimeException e) {
try {
log.info("Fetching application package for " + id + " from alternate repository; it is now deployed "
+ (internal ? "internally" : "externally") + "\nException was: " + Exceptions.toMessageString(e));
return internal
? new ApplicationPackage(artifactRepository.getApplicationPackage(id, version.id()))
: new ApplicationPackage(applicationStore.get(id, version));
}
catch (RuntimeException s) {
e.addSuppressed(s);
throw e;
}
}
}
/** Stores the deployment spec and validation overrides from the application package, and runs cleanup. */
public void storeWithUpdatedConfig(LockedApplication application, ApplicationPackage applicationPackage) {
deploymentSpecValidator.validate(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.deploymentSpec());
application = application.with(applicationPackage.validationOverrides());
for (InstanceName instanceName : application.get().instances().keySet()) {
application = withoutDeletedDeployments(application, instanceName);
DeploymentSpec deploymentSpec = application.get().deploymentSpec();
application = application.with(instanceName, instance -> withoutUnreferencedDeploymentJobs(deploymentSpec, instance));
}
store(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)
);
DeployOptions options = withVersion(version, DeployOptions.none());
return deploy(application.id(), applicationPackage, zone, options, Set.of(), /* No application cert */ null);
} 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, DeployOptions options) {
return deploy(tester.id(), applicationPackage, zone, options, Set.of(), /* No application cert for tester*/ null);
}
private ActivateResult deploy(ApplicationId application, ApplicationPackage applicationPackage,
ZoneId zone, DeployOptions deployOptions, Set<ContainerEndpoint> endpoints,
ApplicationCertificate applicationCertificate) {
DeploymentId deploymentId = new DeploymentId(application, zone);
try {
ConfigServer.PreparedApplication preparedApplication =
configServer.deploy(deploymentId, deployOptions, Set.of(), endpoints, applicationCertificate, applicationPackage.zippedContent());
return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse(),
applicationPackage.zippedContent().length);
} finally {
routingPolicies.refresh(application, applicationPackage.deploymentSpec(), zone);
}
}
/** Makes sure the application has a global rotation, if eligible. */
private LockedApplication withRotation(DeploymentSpec deploymentSpec, LockedApplication application, InstanceName instanceName) {
try (RotationLock rotationLock = rotationRepository.lock()) {
var rotations = rotationRepository.getOrAssignRotations(deploymentSpec,
application.get().require(instanceName),
rotationLock);
application = application.with(instanceName, instance -> instance.with(rotations));
store(application);
}
return application;
}
/**
* Register endpoints for rotations assigned to given application and zone in DNS.
*
* @return the registered endpoints
*/
private Set<ContainerEndpoint> registerEndpointsInDns(DeploymentSpec deploymentSpec, Instance instance, ZoneId zone) {
var containerEndpoints = new HashSet<ContainerEndpoint>();
boolean registerLegacyNames = deploymentSpec.instance(instance.name()).flatMap(i -> i.globalServiceId()).isPresent();
for (var assignedRotation : instance.rotations()) {
var names = new ArrayList<String>();
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId())
.scope(Endpoint.Scope.global);
if (!registerLegacyNames && !assignedRotation.regions().contains(zone.region())) {
continue;
}
if (!registerLegacyNames) {
endpoints = endpoints.legacy(false);
}
var rotation = rotationRepository.getRotation(assignedRotation.rotationId());
if (rotation.isPresent()) {
endpoints.asList().forEach(endpoint -> {
controller.nameServiceForwarder().createCname(RecordName.from(endpoint.dnsName()),
RecordData.fqdn(rotation.get().name()),
Priority.normal);
names.add(endpoint.dnsName());
});
}
names.add(assignedRotation.rotationId().asString());
containerEndpoints.add(new ContainerEndpoint(assignedRotation.clusterId().value(), names));
}
return Collections.unmodifiableSet(containerEndpoints);
}
private Optional<ApplicationCertificate> getApplicationCertificate(Instance instance) {
boolean provisionCertificate = provisionApplicationCertificate.with(FetchVector.Dimension.APPLICATION_ID,
instance.id().serializedForm()).value();
if (!provisionCertificate) {
return Optional.empty();
}
Optional<ApplicationCertificate> applicationCertificate = curator.readApplicationCertificate(instance.id());
if(applicationCertificate.isPresent())
return applicationCertificate;
ApplicationCertificate newCertificate = controller.serviceRegistry().applicationCertificateProvider().requestCaSignedCertificate(instance.id(), dnsNamesOf(instance.id()));
curator.writeApplicationCertificate(instance.id(), newCertificate);
return Optional.of(newCertificate);
}
/** Returns all valid DNS names of given application */
private List<String> dnsNamesOf(ApplicationId applicationId) {
List<String> endpointDnsNames = new ArrayList<>();
endpointDnsNames.add(Endpoint.createHashedCn(applicationId, controller.system()));
var globalDefaultEndpoint = Endpoint.of(applicationId).named(EndpointId.default_());
var rotationEndpoints = Endpoint.of(applicationId).wildcard();
var zoneLocalEndpoints = controller.zoneRegistry().zones().directlyRouted().zones().stream().flatMap(zone -> Stream.of(
Endpoint.of(applicationId).target(ClusterSpec.Id.from("default"), zone.getId()),
Endpoint.of(applicationId).wildcard(zone.getId())
));
Stream.concat(Stream.of(globalDefaultEndpoint, rotationEndpoints), zoneLocalEndpoints)
.map(Endpoint.EndpointBuilder::directRouting)
.map(endpoint -> endpoint.on(Endpoint.Port.tls()))
.map(endpointBuilder -> endpointBuilder.in(controller.system()))
.map(Endpoint::dnsName).forEach(endpointDnsNames::add);
return Collections.unmodifiableList(endpointDnsNames);
}
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 Instance withoutUnreferencedDeploymentJobs(DeploymentSpec deploymentSpec, Instance instance) {
for (JobType job : JobList.from(instance).production().mapToList(JobStatus::type)) {
ZoneId zone = job.zone(controller.system());
if (deploymentSpec.requireInstance(instance.name()).includes(zone.environment(), Optional.of(zone.region())))
continue;
instance = instance.withoutDeploymentJob(job);
}
return instance;
}
private DeployOptions withVersion(Version version, DeployOptions options) {
return new DeployOptions(options.deployDirectly,
Optional.of(version),
options.ignoreValidationErrors,
options.deployCurrentVersion);
}
/** Returns the endpoints of the deployment, or empty if the request fails */
public List<URI> getDeploymentEndpoints(DeploymentId deploymentId) {
if ( ! getInstance(deploymentId.applicationId())
.map(application -> application.deployments().containsKey(deploymentId.zoneId()))
.orElse(deploymentId.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", deploymentId.toString());
try {
return ImmutableList.copyOf(routingGenerator.endpoints(deploymentId).stream()
.map(RoutingEndpoint::endpoint)
.map(URI::create)
.iterator());
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e);
return Collections.emptyList();
}
}
/** Returns the non-empty endpoints per cluster in the given deployment, or empty if endpoints can't be found. */
public Map<ClusterSpec.Id, URI> clusterEndpoints(DeploymentId id) {
if ( ! getInstance(id.applicationId())
.map(application -> application.deployments().containsKey(id.zoneId()))
.orElse(id.applicationId().instance().isTester()))
throw new NotExistsException("Deployment", id.toString());
try {
var endpoints = routingGenerator.clusterEndpoints(id);
if ( ! endpoints.isEmpty())
return endpoints;
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Failed to get endpoint information for " + id, e);
}
return routingPolicies.get(id).stream()
.filter(policy -> policy.endpointIn(controller.system()).scope() == Endpoint.Scope.zone)
.collect(Collectors.toUnmodifiableMap(policy -> policy.cluster(),
policy -> policy.endpointIn(controller.system()).url()));
}
/** Returns all zone-specific cluster endpoints for the given application, in the given zones. */
public Map<ZoneId, Map<ClusterSpec.Id, URI>> clusterEndpoints(ApplicationId id, Collection<ZoneId> zones) {
Map<ZoneId, Map<ClusterSpec.Id, URI>> deployments = new TreeMap<>(Comparator.comparing(ZoneId::value));
for (ZoneId zone : zones) {
var endpoints = clusterEndpoints(new DeploymentId(id, zone));
if ( ! endpoints.isEmpty())
deployments.put(zone, endpoints);
}
return Collections.unmodifiableMap(deployments);
}
/**
* 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, Optional<Credentials> credentials) {
Tenant tenant = controller.tenants().require(id.tenant());
if (tenant.type() != Tenant.Type.user && credentials.isEmpty())
throw new IllegalArgumentException("Could not delete application '" + id + "': No credentials provided");
List<ApplicationId> instances = requireApplication(id).instances().keySet().stream()
.map(id::instance)
.collect(Collectors.toUnmodifiableList());
if (instances.size() > 1)
throw new IllegalArgumentException("Could not delete application; more than one instance present: " + instances);
for (ApplicationId instance : instances)
deleteInstance(instance);
if (tenant.type() != Tenant.Type.user)
accessControl.deleteApplication(id, credentials.get());
curator.removeApplication(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(Collectors.joining(", ")));
applicationStore.removeAll(instanceId);
applicationStore.removeAll(TesterId.of(instanceId));
Instance instance = application.get().require(instanceId.instance());
instance.rotations().forEach(assignedRotation -> {
var endpoints = instance.endpointsIn(controller.system(), assignedRotation.endpointId());
endpoints.asList().stream()
.map(Endpoint::dnsName)
.forEach(name -> {
controller.nameServiceForwarder().removeRecords(Record.Type.CNAME, RecordName.from(name), Priority.normal);
});
});
curator.writeApplication(application.without(instanceId.instance()).get());
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 {
routingPolicies.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(Application application, InstanceName instance, ZoneId zone, Version platformVersion, ApplicationVersion applicationVersion) {
Deployment deployment = application.require(instance).deployments().get(zone);
if ( zone.environment().isProduction() && deployment != null
&& ( platformVersion.compareTo(deployment.version()) < 0 && ! application.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).",
application.id().instance(instance), zone, platformVersion, applicationVersion, deployment.version(), deployment.applicationVersion()));
}
/** Returns the rotation repository, used for managing global rotation assignments */
public RotationRepository rotationRepository() {
return rotationRepository;
}
public RoutingPolicies routingPolicies() {
return routingPolicies;
}
/**
* 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, ApplicationPackage applicationPackage, Optional<Principal> deployer) {
verifyAllowedLaunchAthenzService(applicationPackage.deploymentSpec());
applicationPackage.deploymentSpec().athenzDomain().ifPresent(identityDomain -> {
Tenant tenant = controller.tenants().require(tenantName);
deployer.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.ifPresentOrElse(user -> {
if ( ! ((AthenzFacade) accessControl).hasTenantAdminAccess(user, new AthenzDomain(identityDomain.value())))
throw new IllegalArgumentException("User " + user.getFullName() + " is not allowed to launch " +
"services in Athenz domain " + identityDomain.value() + ". " +
"Please reach out to the domain admin.");
},
() -> {
if (tenant.type() != Tenant.Type.athenz)
throw new IllegalArgumentException("Athenz domain defined in deployment.xml, but no " +
"Athenz domain for tenant " + tenantName.value());
AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
if ( ! Objects.equals(tenantDomain.getName(), identityDomain.value()))
throw new IllegalArgumentException("Athenz domain in deployment.xml: [" + identityDomain.value() + "] " +
"must match tenant domain: [" + tenantDomain.getName() + "]");
});
});
}
/*
* Verifies that the configured athenz service (if any) can be launched.
*/
private void verifyAllowedLaunchAthenzService(DeploymentSpec deploymentSpec) {
deploymentSpec.athenzDomain().ifPresent(athenzDomain -> {
controller.zoneRegistry().zones().reachable().ids()
.forEach(zone -> {
AthenzIdentity configServerAthenzIdentity = controller.zoneRegistry().getConfigServerHttpsIdentity(zone);
deploymentSpec.athenzService(zone.environment(), zone.region())
.map(service -> new AthenzService(athenzDomain.value(), service.value()))
.ifPresent(service -> {
boolean allowedToLaunch = ((AthenzFacade) accessControl).canLaunch(configServerAthenzIdentity, service);
if (!allowedToLaunch)
throw new IllegalArgumentException("Not allowed to launch Athenz service " + service.getFullName());
});
});
});
}
/** Returns the latest known version within the given major. */
private 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);
}
} |
Could just make an instant from the field, without optionality — non-existent value is 0, which is EPOCH. | private RotationStatus rotationStatusFromSlime(Inspector parentObject) {
var object = parentObject.field(rotationStatusField);
var statusMap = new LinkedHashMap<RotationId, RotationStatus.Targets>();
object.traverse((ArrayTraverser) (idx, statusObject) -> statusMap.put(new RotationId(statusObject.field(rotationIdField).asString()),
new RotationStatus.Targets(
singleRotationStatusFromSlime(statusObject.field(statusField)),
Serializers.optionalInstant(statusObject.field(lastUpdatedField)).orElse(Instant.EPOCH))));
return RotationStatus.from(statusMap);
} | Serializers.optionalInstant(statusObject.field(lastUpdatedField)).orElse(Instant.EPOCH)))); | private RotationStatus rotationStatusFromSlime(Inspector parentObject) {
var object = parentObject.field(rotationStatusField);
var statusMap = new LinkedHashMap<RotationId, RotationStatus.Targets>();
object.traverse((ArrayTraverser) (idx, statusObject) -> statusMap.put(new RotationId(statusObject.field(rotationIdField).asString()),
new RotationStatus.Targets(
singleRotationStatusFromSlime(statusObject.field(statusField)),
Instant.ofEpochMilli(statusObject.field(lastUpdatedField).asLong()))));
return RotationStatus.from(statusMap);
} | class ApplicationSerializer {
private static final String idField = "id";
private static final String createdAtField = "createdAt";
private static final String deploymentSpecField = "deploymentSpecField";
private static final String validationOverridesField = "validationOverrides";
private static final String instancesField = "instances";
private static final String deployingField = "deployingField";
private static final String projectIdField = "projectId";
private static final String latestVersionField = "latestVersion";
private static final String builtInternallyField = "builtInternally";
private static final String pinnedField = "pinned";
private static final String outstandingChangeField = "outstandingChangeField";
private static final String deploymentIssueField = "deploymentIssueId";
private static final String ownershipIssueIdField = "ownershipIssueId";
private static final String ownerField = "confirmedOwner";
private static final String majorVersionField = "majorVersion";
private static final String writeQualityField = "writeQuality";
private static final String queryQualityField = "queryQuality";
private static final String pemDeployKeysField = "pemDeployKeys";
private static final String assignedRotationClusterField = "clusterId";
private static final String assignedRotationRotationField = "rotationId";
private static final String instanceNameField = "instanceName";
private static final String deploymentsField = "deployments";
private static final String deploymentJobsField = "deploymentJobs";
private static final String assignedRotationsField = "assignedRotations";
private static final String assignedRotationEndpointField = "endpointId";
private static final String zoneField = "zone";
private static final String environmentField = "environment";
private static final String regionField = "region";
private static final String deployTimeField = "deployTime";
private static final String applicationBuildNumberField = "applicationBuildNumber";
private static final String applicationPackageRevisionField = "applicationPackageRevision";
private static final String sourceRevisionField = "sourceRevision";
private static final String repositoryField = "repositoryField";
private static final String branchField = "branchField";
private static final String commitField = "commitField";
private static final String authorEmailField = "authorEmailField";
private static final String compileVersionField = "compileVersion";
private static final String buildTimeField = "buildTime";
private static final String lastQueriedField = "lastQueried";
private static final String lastWrittenField = "lastWritten";
private static final String lastQueriesPerSecondField = "lastQueriesPerSecond";
private static final String lastWritesPerSecondField = "lastWritesPerSecond";
private static final String jobStatusField = "jobStatus";
private static final String jobTypeField = "jobType";
private static final String errorField = "jobError";
private static final String lastTriggeredField = "lastTriggered";
private static final String lastCompletedField = "lastCompleted";
private static final String firstFailingField = "firstFailing";
private static final String lastSuccessField = "lastSuccess";
private static final String pausedUntilField = "pausedUntil";
private static final String jobRunIdField = "id";
private static final String versionField = "version";
private static final String revisionField = "revision";
private static final String sourceVersionField = "sourceVersion";
private static final String sourceApplicationField = "sourceRevision";
private static final String reasonField = "reason";
private static final String atField = "at";
private static final String clusterInfoField = "clusterInfo";
private static final String clusterInfoFlavorField = "flavor";
private static final String clusterInfoCostField = "cost";
private static final String clusterInfoCpuField = "flavorCpu";
private static final String clusterInfoMemField = "flavorMem";
private static final String clusterInfoDiskField = "flavorDisk";
private static final String clusterInfoTypeField = "clusterType";
private static final String clusterInfoHostnamesField = "hostnames";
private static final String deploymentMetricsField = "metrics";
private static final String deploymentMetricsQPSField = "queriesPerSecond";
private static final String deploymentMetricsWPSField = "writesPerSecond";
private static final String deploymentMetricsDocsField = "documentCount";
private static final String deploymentMetricsQueryLatencyField = "queryLatencyMillis";
private static final String deploymentMetricsWriteLatencyField = "writeLatencyMillis";
private static final String deploymentMetricsUpdateTime = "lastUpdated";
private static final String deploymentMetricsWarningsField = "warnings";
private static final String rotationStatusField = "rotationStatus2";
private static final String rotationIdField = "rotationId";
private static final String lastUpdatedField = "lastUpdated";
private static final String rotationStateField = "state";
private static final String statusField = "status";
public Slime toSlime(Application application) {
Slime slime = new Slime();
Cursor root = slime.setObject();
root.setString(idField, application.id().serialized());
root.setLong(createdAtField, application.createdAt().toEpochMilli());
root.setString(deploymentSpecField, application.deploymentSpec().xmlForm());
root.setString(validationOverridesField, application.validationOverrides().xmlForm());
application.projectId().ifPresent(projectId -> root.setLong(projectIdField, projectId));
application.deploymentIssueId().ifPresent(jiraIssueId -> root.setString(deploymentIssueField, jiraIssueId.value()));
application.ownershipIssueId().ifPresent(issueId -> root.setString(ownershipIssueIdField, issueId.value()));
root.setBool(builtInternallyField, application.internal());
toSlime(application.change(), root, deployingField);
toSlime(application.outstandingChange(), root, outstandingChangeField);
application.owner().ifPresent(owner -> root.setString(ownerField, owner.username()));
application.majorVersion().ifPresent(majorVersion -> root.setLong(majorVersionField, majorVersion));
root.setDouble(queryQualityField, application.metrics().queryServiceQuality());
root.setDouble(writeQualityField, application.metrics().writeServiceQuality());
deployKeysToSlime(application.deployKeys(), root.setArray(pemDeployKeysField));
application.latestVersion().ifPresent(version -> toSlime(version, root.setObject(latestVersionField)));
instancesToSlime(application, root.setArray(instancesField));
return slime;
}
private void instancesToSlime(Application application, Cursor array) {
for (Instance instance : application.instances().values()) {
Cursor instanceObject = array.addObject();
instanceObject.setString(instanceNameField, instance.name().value());
deploymentsToSlime(instance.deployments().values(), instanceObject.setArray(deploymentsField));
toSlime(instance.deploymentJobs(), instanceObject.setObject(deploymentJobsField));
assignedRotationsToSlime(instance.rotations(), instanceObject, assignedRotationsField);
toSlime(instance.rotationStatus(), instanceObject.setArray(rotationStatusField));
}
}
private void deployKeysToSlime(Set<PublicKey> deployKeys, Cursor array) {
deployKeys.forEach(key -> array.addString(KeyUtils.toPem(key)));
}
private void deploymentsToSlime(Collection<Deployment> deployments, Cursor array) {
for (Deployment deployment : deployments)
deploymentToSlime(deployment, array.addObject());
}
private void deploymentToSlime(Deployment deployment, Cursor object) {
zoneIdToSlime(deployment.zone(), object.setObject(zoneField));
object.setString(versionField, deployment.version().toString());
object.setLong(deployTimeField, deployment.at().toEpochMilli());
toSlime(deployment.applicationVersion(), object.setObject(applicationPackageRevisionField));
clusterInfoToSlime(deployment.clusterInfo(), object);
deploymentMetricsToSlime(deployment.metrics(), object);
deployment.activity().lastQueried().ifPresent(instant -> object.setLong(lastQueriedField, instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> object.setLong(lastWrittenField, instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> object.setDouble(lastQueriesPerSecondField, value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> object.setDouble(lastWritesPerSecondField, value));
}
private void deploymentMetricsToSlime(DeploymentMetrics metrics, Cursor object) {
Cursor root = object.setObject(deploymentMetricsField);
root.setDouble(deploymentMetricsQPSField, metrics.queriesPerSecond());
root.setDouble(deploymentMetricsWPSField, metrics.writesPerSecond());
root.setDouble(deploymentMetricsDocsField, metrics.documentCount());
root.setDouble(deploymentMetricsQueryLatencyField, metrics.queryLatencyMillis());
root.setDouble(deploymentMetricsWriteLatencyField, metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> root.setLong(deploymentMetricsUpdateTime, instant.toEpochMilli()));
if (!metrics.warnings().isEmpty()) {
Cursor warningsObject = root.setObject(deploymentMetricsWarningsField);
metrics.warnings().forEach((warning, count) -> warningsObject.setLong(warning.name(), count));
}
}
private void clusterInfoToSlime(Map<ClusterSpec.Id, ClusterInfo> clusters, Cursor object) {
Cursor root = object.setObject(clusterInfoField);
for (Map.Entry<ClusterSpec.Id, ClusterInfo> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterInfo info, Cursor object) {
object.setString(clusterInfoFlavorField, info.getFlavor());
object.setLong(clusterInfoCostField, info.getFlavorCost());
object.setDouble(clusterInfoCpuField, info.getFlavorCPU());
object.setDouble(clusterInfoMemField, info.getFlavorMem());
object.setDouble(clusterInfoDiskField, info.getFlavorDisk());
object.setString(clusterInfoTypeField, info.getClusterType().name());
Cursor array = object.setArray(clusterInfoHostnamesField);
for (String host : info.getHostnames()) {
array.addString(host);
}
}
private void zoneIdToSlime(ZoneId zone, Cursor object) {
object.setString(environmentField, zone.environment().value());
object.setString(regionField, zone.region().value());
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if (applicationVersion.buildNumber().isPresent() && applicationVersion.source().isPresent()) {
object.setLong(applicationBuildNumberField, applicationVersion.buildNumber().getAsLong());
toSlime(applicationVersion.source().get(), object.setObject(sourceRevisionField));
applicationVersion.authorEmail().ifPresent(email -> object.setString(authorEmailField, email));
applicationVersion.compileVersion().ifPresent(version -> object.setString(compileVersionField, version.toString()));
applicationVersion.buildTime().ifPresent(time -> object.setLong(buildTimeField, time.toEpochMilli()));
}
}
private void toSlime(SourceRevision sourceRevision, Cursor object) {
object.setString(repositoryField, sourceRevision.repository());
object.setString(branchField, sourceRevision.branch());
object.setString(commitField, sourceRevision.commit());
}
private void toSlime(DeploymentJobs deploymentJobs, Cursor cursor) {
jobStatusToSlime(deploymentJobs.jobStatus().values(), cursor.setArray(jobStatusField));
}
private void jobStatusToSlime(Collection<JobStatus> jobStatuses, Cursor jobStatusArray) {
for (JobStatus jobStatus : jobStatuses)
toSlime(jobStatus, jobStatusArray.addObject());
}
private void toSlime(JobStatus jobStatus, Cursor object) {
object.setString(jobTypeField, jobStatus.type().jobName());
if (jobStatus.jobError().isPresent())
object.setString(errorField, jobStatus.jobError().get().name());
jobStatus.lastTriggered().ifPresent(run -> jobRunToSlime(run, object, lastTriggeredField));
jobStatus.lastCompleted().ifPresent(run -> jobRunToSlime(run, object, lastCompletedField));
jobStatus.lastSuccess().ifPresent(run -> jobRunToSlime(run, object, lastSuccessField));
jobStatus.firstFailing().ifPresent(run -> jobRunToSlime(run, object, firstFailingField));
jobStatus.pausedUntil().ifPresent(until -> object.setLong(pausedUntilField, until));
}
private void jobRunToSlime(JobStatus.JobRun jobRun, Cursor parent, String jobRunObjectName) {
Cursor object = parent.setObject(jobRunObjectName);
object.setLong(jobRunIdField, jobRun.id());
object.setString(versionField, jobRun.platform().toString());
toSlime(jobRun.application(), object.setObject(revisionField));
jobRun.sourcePlatform().ifPresent(version -> object.setString(sourceVersionField, version.toString()));
jobRun.sourceApplication().ifPresent(version -> toSlime(version, object.setObject(sourceApplicationField)));
object.setString(reasonField, jobRun.reason());
object.setLong(atField, jobRun.at().toEpochMilli());
}
private void toSlime(Change deploying, Cursor parentObject, String fieldName) {
if (deploying.isEmpty()) return;
Cursor object = parentObject.setObject(fieldName);
if (deploying.platform().isPresent())
object.setString(versionField, deploying.platform().get().toString());
if (deploying.application().isPresent())
toSlime(deploying.application().get(), object);
if (deploying.isPinned())
object.setBool(pinnedField, true);
}
private void toSlime(RotationStatus status, Cursor array) {
status.asMap().forEach((rotationId, targets) -> {
Cursor rotationObject = array.addObject();
rotationObject.setString(rotationIdField, rotationId.asString());
rotationObject.setLong(lastUpdatedField, targets.lastUpdated().toEpochMilli());
Cursor statusArray = rotationObject.setArray(statusField);
targets.asMap().forEach((zone, state) -> {
Cursor statusObject = statusArray.addObject();
zoneIdToSlime(zone, statusObject);
statusObject.setString(rotationStateField, state.name());
});
});
}
private void assignedRotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) {
var rotationsArray = parent.setArray(fieldName);
for (var rotation : rotations) {
var object = rotationsArray.addObject();
object.setString(assignedRotationEndpointField, rotation.endpointId().id());
object.setString(assignedRotationRotationField, rotation.rotationId().asString());
object.setString(assignedRotationClusterField, rotation.clusterId().value());
}
}
public Application fromSlime(Slime slime) {
Inspector root = slime.get();
TenantAndApplicationId id = TenantAndApplicationId.fromSerialized(root.field(idField).asString());
Instant createdAt = Instant.ofEpochMilli(root.field(createdAtField).asLong());
DeploymentSpec deploymentSpec = DeploymentSpec.fromXml(root.field(deploymentSpecField).asString(), false);
ValidationOverrides validationOverrides = ValidationOverrides.fromXml(root.field(validationOverridesField).asString());
Change deploying = changeFromSlime(root.field(deployingField));
Change outstandingChange = changeFromSlime(root.field(outstandingChangeField));
Optional<IssueId> deploymentIssueId = Serializers.optionalString(root.field(deploymentIssueField)).map(IssueId::from);
Optional<IssueId> ownershipIssueId = Serializers.optionalString(root.field(ownershipIssueIdField)).map(IssueId::from);
Optional<User> owner = Serializers.optionalString(root.field(ownerField)).map(User::from);
OptionalInt majorVersion = Serializers.optionalInteger(root.field(majorVersionField));
ApplicationMetrics metrics = new ApplicationMetrics(root.field(queryQualityField).asDouble(),
root.field(writeQualityField).asDouble());
Set<PublicKey> deployKeys = deployKeysFromSlime(root.field(pemDeployKeysField));
List<Instance> instances = instancesFromSlime(id, deploymentSpec, root.field(instancesField));
OptionalLong projectId = Serializers.optionalLong(root.field(projectIdField));
Optional<ApplicationVersion> latestVersion = latestVersionFromSlimeWithFallback(root.field(latestVersionField), instances);
boolean builtInternally = root.field(builtInternallyField).asBool();
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
deployKeys, projectId, builtInternally, latestVersion, instances);
}
private Optional<ApplicationVersion> latestVersionFromSlimeWithFallback(Inspector latestVersionObject, List<Instance> instances) {
if (latestVersionObject.valid())
return Optional.of(applicationVersionFromSlime(latestVersionObject));
return instances.stream()
.flatMap(instance -> instance.deploymentJobs().statusOf(JobType.component).stream())
.flatMap(status -> status.lastSuccess().stream())
.map(JobStatus.JobRun::application)
.findFirst();
}
private List<Instance> instancesFromSlime(TenantAndApplicationId id, DeploymentSpec deploymentSpec, Inspector field) {
List<Instance> instances = new ArrayList<>();
field.traverse((ArrayTraverser) (name, object) -> {
InstanceName instanceName = InstanceName.from(object.field(instanceNameField).asString());
List<Deployment> deployments = deploymentsFromSlime(object.field(deploymentsField));
DeploymentJobs deploymentJobs = deploymentJobsFromSlime(object.field(deploymentJobsField));
List<AssignedRotation> assignedRotations = assignedRotationsFromSlime(deploymentSpec, object);
RotationStatus rotationStatus = rotationStatusFromSlime(object);
instances.add(new Instance(id.instance(instanceName),
deployments,
deploymentJobs,
assignedRotations,
rotationStatus));
});
return instances;
}
private Set<PublicKey> deployKeysFromSlime(Inspector array) {
Set<PublicKey> keys = new LinkedHashSet<>();
array.traverse((ArrayTraverser) (__, key) -> keys.add(KeyUtils.fromPemEncodedPublicKey(key.asString())));
return keys;
}
private List<Deployment> deploymentsFromSlime(Inspector array) {
List<Deployment> deployments = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> deployments.add(deploymentFromSlime(item)));
return deployments;
}
private Deployment deploymentFromSlime(Inspector deploymentObject) {
return new Deployment(zoneIdFromSlime(deploymentObject.field(zoneField)),
applicationVersionFromSlime(deploymentObject.field(applicationPackageRevisionField)),
Version.fromString(deploymentObject.field(versionField).asString()),
Instant.ofEpochMilli(deploymentObject.field(deployTimeField).asLong()),
clusterInfoMapFromSlime(deploymentObject.field(clusterInfoField)),
deploymentMetricsFromSlime(deploymentObject.field(deploymentMetricsField)),
DeploymentActivity.create(Serializers.optionalInstant(deploymentObject.field(lastQueriedField)),
Serializers.optionalInstant(deploymentObject.field(lastWrittenField)),
Serializers.optionalDouble(deploymentObject.field(lastQueriesPerSecondField)),
Serializers.optionalDouble(deploymentObject.field(lastWritesPerSecondField))));
}
private DeploymentMetrics deploymentMetricsFromSlime(Inspector object) {
Optional<Instant> instant = object.field(deploymentMetricsUpdateTime).valid() ?
Optional.of(Instant.ofEpochMilli(object.field(deploymentMetricsUpdateTime).asLong())) :
Optional.empty();
return new DeploymentMetrics(object.field(deploymentMetricsQPSField).asDouble(),
object.field(deploymentMetricsWPSField).asDouble(),
object.field(deploymentMetricsDocsField).asDouble(),
object.field(deploymentMetricsQueryLatencyField).asDouble(),
object.field(deploymentMetricsWriteLatencyField).asDouble(),
instant,
deploymentWarningsFrom(object.field(deploymentMetricsWarningsField)));
}
private Map<DeploymentMetrics.Warning, Integer> deploymentWarningsFrom(Inspector object) {
Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>();
object.traverse((ObjectTraverser) (name, value) -> warnings.put(DeploymentMetrics.Warning.valueOf(name),
(int) value.asLong()));
return Collections.unmodifiableMap(warnings);
}
private Map<ZoneId, RotationState> singleRotationStatusFromSlime(Inspector object) {
if (!object.valid()) {
return Collections.emptyMap();
}
Map<ZoneId, RotationState> rotationStatus = new LinkedHashMap<>();
object.traverse((ArrayTraverser) (idx, statusObject) -> {
var zone = zoneIdFromSlime(statusObject);
var status = RotationState.valueOf(statusObject.field(rotationStateField).asString());
rotationStatus.put(zone, status);
});
return Collections.unmodifiableMap(rotationStatus);
}
private Map<ClusterSpec.Id, ClusterInfo> clusterInfoMapFromSlime (Inspector object) {
Map<ClusterSpec.Id, ClusterInfo> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterInfoFromSlime(value)));
return map;
}
private ClusterInfo clusterInfoFromSlime(Inspector inspector) {
String flavor = inspector.field(clusterInfoFlavorField).asString();
int cost = (int)inspector.field(clusterInfoCostField).asLong();
String type = inspector.field(clusterInfoTypeField).asString();
double flavorCpu = inspector.field(clusterInfoCpuField).asDouble();
double flavorMem = inspector.field(clusterInfoMemField).asDouble();
double flavorDisk = inspector.field(clusterInfoDiskField).asDouble();
List<String> hostnames = new ArrayList<>();
inspector.field(clusterInfoHostnamesField).traverse((ArrayTraverser)(int index, Inspector value) -> hostnames.add(value.asString()));
return new ClusterInfo(flavor, cost, flavorCpu, flavorMem, flavorDisk, ClusterSpec.Type.from(type), hostnames);
}
private ZoneId zoneIdFromSlime(Inspector object) {
return ZoneId.from(object.field(environmentField).asString(), object.field(regionField).asString());
}
private ApplicationVersion applicationVersionFromSlime(Inspector object) {
if ( ! object.valid()) return ApplicationVersion.unknown;
OptionalLong applicationBuildNumber = Serializers.optionalLong(object.field(applicationBuildNumberField));
Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField));
if (sourceRevision.isEmpty() || applicationBuildNumber.isEmpty()) {
return ApplicationVersion.unknown;
}
Optional<String> authorEmail = Serializers.optionalString(object.field(authorEmailField));
Optional<Version> compileVersion = Serializers.optionalString(object.field(compileVersionField)).map(Version::fromString);
Optional<Instant> buildTime = Serializers.optionalInstant(object.field(buildTimeField));
if (authorEmail.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong());
if (compileVersion.isEmpty() || buildTime.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get());
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get(),
compileVersion.get(), buildTime.get());
}
private Optional<SourceRevision> sourceRevisionFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new SourceRevision(object.field(repositoryField).asString(),
object.field(branchField).asString(),
object.field(commitField).asString()));
}
private DeploymentJobs deploymentJobsFromSlime(Inspector object) {
List<JobStatus> jobStatusList = jobStatusListFromSlime(object.field(jobStatusField));
return new DeploymentJobs(jobStatusList);
}
private Change changeFromSlime(Inspector object) {
if ( ! object.valid()) return Change.empty();
Inspector versionFieldValue = object.field(versionField);
Change change = Change.empty();
if (versionFieldValue.valid())
change = Change.of(Version.fromString(versionFieldValue.asString()));
if (object.field(applicationBuildNumberField).valid())
change = change.with(applicationVersionFromSlime(object));
if (object.field(pinnedField).asBool())
change = change.withPin();
return change;
}
private List<JobStatus> jobStatusListFromSlime(Inspector array) {
List<JobStatus> jobStatusList = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> jobStatusFromSlime(item).ifPresent(jobStatusList::add));
return jobStatusList;
}
private Optional<JobStatus> jobStatusFromSlime(Inspector object) {
Optional<JobType> jobType =
JobType.fromOptionalJobName(object.field(jobTypeField).asString());
if (jobType.isEmpty()) return Optional.empty();
Optional<JobError> jobError = Optional.empty();
if (object.field(errorField).valid())
jobError = Optional.of(JobError.valueOf(object.field(errorField).asString()));
return Optional.of(new JobStatus(jobType.get(),
jobError,
jobRunFromSlime(object.field(lastTriggeredField)),
jobRunFromSlime(object.field(lastCompletedField)),
jobRunFromSlime(object.field(firstFailingField)),
jobRunFromSlime(object.field(lastSuccessField)),
Serializers.optionalLong(object.field(pausedUntilField))));
}
private Optional<JobStatus.JobRun> jobRunFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new JobStatus.JobRun(object.field(jobRunIdField).asLong(),
new Version(object.field(versionField).asString()),
applicationVersionFromSlime(object.field(revisionField)),
Serializers.optionalString(object.field(sourceVersionField)).map(Version::fromString),
Optional.of(object.field(sourceApplicationField)).filter(Inspector::valid).map(this::applicationVersionFromSlime),
object.field(reasonField).asString(),
Instant.ofEpochMilli(object.field(atField).asLong())));
}
private List<AssignedRotation> assignedRotationsFromSlime(DeploymentSpec deploymentSpec, Inspector root) {
var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>();
root.field(assignedRotationsField).traverse((ArrayTraverser) (idx, inspector) -> {
var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString());
var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString());
var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString());
var regions = deploymentSpec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
} | class ApplicationSerializer {
private static final String idField = "id";
private static final String createdAtField = "createdAt";
private static final String deploymentSpecField = "deploymentSpecField";
private static final String validationOverridesField = "validationOverrides";
private static final String instancesField = "instances";
private static final String deployingField = "deployingField";
private static final String projectIdField = "projectId";
private static final String latestVersionField = "latestVersion";
private static final String builtInternallyField = "builtInternally";
private static final String pinnedField = "pinned";
private static final String outstandingChangeField = "outstandingChangeField";
private static final String deploymentIssueField = "deploymentIssueId";
private static final String ownershipIssueIdField = "ownershipIssueId";
private static final String ownerField = "confirmedOwner";
private static final String majorVersionField = "majorVersion";
private static final String writeQualityField = "writeQuality";
private static final String queryQualityField = "queryQuality";
private static final String pemDeployKeysField = "pemDeployKeys";
private static final String assignedRotationClusterField = "clusterId";
private static final String assignedRotationRotationField = "rotationId";
private static final String instanceNameField = "instanceName";
private static final String deploymentsField = "deployments";
private static final String deploymentJobsField = "deploymentJobs";
private static final String assignedRotationsField = "assignedRotations";
private static final String assignedRotationEndpointField = "endpointId";
private static final String zoneField = "zone";
private static final String environmentField = "environment";
private static final String regionField = "region";
private static final String deployTimeField = "deployTime";
private static final String applicationBuildNumberField = "applicationBuildNumber";
private static final String applicationPackageRevisionField = "applicationPackageRevision";
private static final String sourceRevisionField = "sourceRevision";
private static final String repositoryField = "repositoryField";
private static final String branchField = "branchField";
private static final String commitField = "commitField";
private static final String authorEmailField = "authorEmailField";
private static final String compileVersionField = "compileVersion";
private static final String buildTimeField = "buildTime";
private static final String lastQueriedField = "lastQueried";
private static final String lastWrittenField = "lastWritten";
private static final String lastQueriesPerSecondField = "lastQueriesPerSecond";
private static final String lastWritesPerSecondField = "lastWritesPerSecond";
private static final String jobStatusField = "jobStatus";
private static final String jobTypeField = "jobType";
private static final String errorField = "jobError";
private static final String lastTriggeredField = "lastTriggered";
private static final String lastCompletedField = "lastCompleted";
private static final String firstFailingField = "firstFailing";
private static final String lastSuccessField = "lastSuccess";
private static final String pausedUntilField = "pausedUntil";
private static final String jobRunIdField = "id";
private static final String versionField = "version";
private static final String revisionField = "revision";
private static final String sourceVersionField = "sourceVersion";
private static final String sourceApplicationField = "sourceRevision";
private static final String reasonField = "reason";
private static final String atField = "at";
private static final String clusterInfoField = "clusterInfo";
private static final String clusterInfoFlavorField = "flavor";
private static final String clusterInfoCostField = "cost";
private static final String clusterInfoCpuField = "flavorCpu";
private static final String clusterInfoMemField = "flavorMem";
private static final String clusterInfoDiskField = "flavorDisk";
private static final String clusterInfoTypeField = "clusterType";
private static final String clusterInfoHostnamesField = "hostnames";
private static final String deploymentMetricsField = "metrics";
private static final String deploymentMetricsQPSField = "queriesPerSecond";
private static final String deploymentMetricsWPSField = "writesPerSecond";
private static final String deploymentMetricsDocsField = "documentCount";
private static final String deploymentMetricsQueryLatencyField = "queryLatencyMillis";
private static final String deploymentMetricsWriteLatencyField = "writeLatencyMillis";
private static final String deploymentMetricsUpdateTime = "lastUpdated";
private static final String deploymentMetricsWarningsField = "warnings";
private static final String rotationStatusField = "rotationStatus2";
private static final String rotationIdField = "rotationId";
private static final String lastUpdatedField = "lastUpdated";
private static final String rotationStateField = "state";
private static final String statusField = "status";
public Slime toSlime(Application application) {
Slime slime = new Slime();
Cursor root = slime.setObject();
root.setString(idField, application.id().serialized());
root.setLong(createdAtField, application.createdAt().toEpochMilli());
root.setString(deploymentSpecField, application.deploymentSpec().xmlForm());
root.setString(validationOverridesField, application.validationOverrides().xmlForm());
application.projectId().ifPresent(projectId -> root.setLong(projectIdField, projectId));
application.deploymentIssueId().ifPresent(jiraIssueId -> root.setString(deploymentIssueField, jiraIssueId.value()));
application.ownershipIssueId().ifPresent(issueId -> root.setString(ownershipIssueIdField, issueId.value()));
root.setBool(builtInternallyField, application.internal());
toSlime(application.change(), root, deployingField);
toSlime(application.outstandingChange(), root, outstandingChangeField);
application.owner().ifPresent(owner -> root.setString(ownerField, owner.username()));
application.majorVersion().ifPresent(majorVersion -> root.setLong(majorVersionField, majorVersion));
root.setDouble(queryQualityField, application.metrics().queryServiceQuality());
root.setDouble(writeQualityField, application.metrics().writeServiceQuality());
deployKeysToSlime(application.deployKeys(), root.setArray(pemDeployKeysField));
application.latestVersion().ifPresent(version -> toSlime(version, root.setObject(latestVersionField)));
instancesToSlime(application, root.setArray(instancesField));
return slime;
}
private void instancesToSlime(Application application, Cursor array) {
for (Instance instance : application.instances().values()) {
Cursor instanceObject = array.addObject();
instanceObject.setString(instanceNameField, instance.name().value());
deploymentsToSlime(instance.deployments().values(), instanceObject.setArray(deploymentsField));
toSlime(instance.deploymentJobs(), instanceObject.setObject(deploymentJobsField));
assignedRotationsToSlime(instance.rotations(), instanceObject, assignedRotationsField);
toSlime(instance.rotationStatus(), instanceObject.setArray(rotationStatusField));
}
}
private void deployKeysToSlime(Set<PublicKey> deployKeys, Cursor array) {
deployKeys.forEach(key -> array.addString(KeyUtils.toPem(key)));
}
private void deploymentsToSlime(Collection<Deployment> deployments, Cursor array) {
for (Deployment deployment : deployments)
deploymentToSlime(deployment, array.addObject());
}
private void deploymentToSlime(Deployment deployment, Cursor object) {
zoneIdToSlime(deployment.zone(), object.setObject(zoneField));
object.setString(versionField, deployment.version().toString());
object.setLong(deployTimeField, deployment.at().toEpochMilli());
toSlime(deployment.applicationVersion(), object.setObject(applicationPackageRevisionField));
clusterInfoToSlime(deployment.clusterInfo(), object);
deploymentMetricsToSlime(deployment.metrics(), object);
deployment.activity().lastQueried().ifPresent(instant -> object.setLong(lastQueriedField, instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> object.setLong(lastWrittenField, instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> object.setDouble(lastQueriesPerSecondField, value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> object.setDouble(lastWritesPerSecondField, value));
}
private void deploymentMetricsToSlime(DeploymentMetrics metrics, Cursor object) {
Cursor root = object.setObject(deploymentMetricsField);
root.setDouble(deploymentMetricsQPSField, metrics.queriesPerSecond());
root.setDouble(deploymentMetricsWPSField, metrics.writesPerSecond());
root.setDouble(deploymentMetricsDocsField, metrics.documentCount());
root.setDouble(deploymentMetricsQueryLatencyField, metrics.queryLatencyMillis());
root.setDouble(deploymentMetricsWriteLatencyField, metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> root.setLong(deploymentMetricsUpdateTime, instant.toEpochMilli()));
if (!metrics.warnings().isEmpty()) {
Cursor warningsObject = root.setObject(deploymentMetricsWarningsField);
metrics.warnings().forEach((warning, count) -> warningsObject.setLong(warning.name(), count));
}
}
private void clusterInfoToSlime(Map<ClusterSpec.Id, ClusterInfo> clusters, Cursor object) {
Cursor root = object.setObject(clusterInfoField);
for (Map.Entry<ClusterSpec.Id, ClusterInfo> entry : clusters.entrySet()) {
toSlime(entry.getValue(), root.setObject(entry.getKey().value()));
}
}
private void toSlime(ClusterInfo info, Cursor object) {
object.setString(clusterInfoFlavorField, info.getFlavor());
object.setLong(clusterInfoCostField, info.getFlavorCost());
object.setDouble(clusterInfoCpuField, info.getFlavorCPU());
object.setDouble(clusterInfoMemField, info.getFlavorMem());
object.setDouble(clusterInfoDiskField, info.getFlavorDisk());
object.setString(clusterInfoTypeField, info.getClusterType().name());
Cursor array = object.setArray(clusterInfoHostnamesField);
for (String host : info.getHostnames()) {
array.addString(host);
}
}
private void zoneIdToSlime(ZoneId zone, Cursor object) {
object.setString(environmentField, zone.environment().value());
object.setString(regionField, zone.region().value());
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if (applicationVersion.buildNumber().isPresent() && applicationVersion.source().isPresent()) {
object.setLong(applicationBuildNumberField, applicationVersion.buildNumber().getAsLong());
toSlime(applicationVersion.source().get(), object.setObject(sourceRevisionField));
applicationVersion.authorEmail().ifPresent(email -> object.setString(authorEmailField, email));
applicationVersion.compileVersion().ifPresent(version -> object.setString(compileVersionField, version.toString()));
applicationVersion.buildTime().ifPresent(time -> object.setLong(buildTimeField, time.toEpochMilli()));
}
}
private void toSlime(SourceRevision sourceRevision, Cursor object) {
object.setString(repositoryField, sourceRevision.repository());
object.setString(branchField, sourceRevision.branch());
object.setString(commitField, sourceRevision.commit());
}
private void toSlime(DeploymentJobs deploymentJobs, Cursor cursor) {
jobStatusToSlime(deploymentJobs.jobStatus().values(), cursor.setArray(jobStatusField));
}
private void jobStatusToSlime(Collection<JobStatus> jobStatuses, Cursor jobStatusArray) {
for (JobStatus jobStatus : jobStatuses)
toSlime(jobStatus, jobStatusArray.addObject());
}
private void toSlime(JobStatus jobStatus, Cursor object) {
object.setString(jobTypeField, jobStatus.type().jobName());
if (jobStatus.jobError().isPresent())
object.setString(errorField, jobStatus.jobError().get().name());
jobStatus.lastTriggered().ifPresent(run -> jobRunToSlime(run, object, lastTriggeredField));
jobStatus.lastCompleted().ifPresent(run -> jobRunToSlime(run, object, lastCompletedField));
jobStatus.lastSuccess().ifPresent(run -> jobRunToSlime(run, object, lastSuccessField));
jobStatus.firstFailing().ifPresent(run -> jobRunToSlime(run, object, firstFailingField));
jobStatus.pausedUntil().ifPresent(until -> object.setLong(pausedUntilField, until));
}
private void jobRunToSlime(JobStatus.JobRun jobRun, Cursor parent, String jobRunObjectName) {
Cursor object = parent.setObject(jobRunObjectName);
object.setLong(jobRunIdField, jobRun.id());
object.setString(versionField, jobRun.platform().toString());
toSlime(jobRun.application(), object.setObject(revisionField));
jobRun.sourcePlatform().ifPresent(version -> object.setString(sourceVersionField, version.toString()));
jobRun.sourceApplication().ifPresent(version -> toSlime(version, object.setObject(sourceApplicationField)));
object.setString(reasonField, jobRun.reason());
object.setLong(atField, jobRun.at().toEpochMilli());
}
private void toSlime(Change deploying, Cursor parentObject, String fieldName) {
if (deploying.isEmpty()) return;
Cursor object = parentObject.setObject(fieldName);
if (deploying.platform().isPresent())
object.setString(versionField, deploying.platform().get().toString());
if (deploying.application().isPresent())
toSlime(deploying.application().get(), object);
if (deploying.isPinned())
object.setBool(pinnedField, true);
}
private void toSlime(RotationStatus status, Cursor array) {
status.asMap().forEach((rotationId, targets) -> {
Cursor rotationObject = array.addObject();
rotationObject.setString(rotationIdField, rotationId.asString());
rotationObject.setLong(lastUpdatedField, targets.lastUpdated().toEpochMilli());
Cursor statusArray = rotationObject.setArray(statusField);
targets.asMap().forEach((zone, state) -> {
Cursor statusObject = statusArray.addObject();
zoneIdToSlime(zone, statusObject);
statusObject.setString(rotationStateField, state.name());
});
});
}
private void assignedRotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) {
var rotationsArray = parent.setArray(fieldName);
for (var rotation : rotations) {
var object = rotationsArray.addObject();
object.setString(assignedRotationEndpointField, rotation.endpointId().id());
object.setString(assignedRotationRotationField, rotation.rotationId().asString());
object.setString(assignedRotationClusterField, rotation.clusterId().value());
}
}
public Application fromSlime(Slime slime) {
Inspector root = slime.get();
TenantAndApplicationId id = TenantAndApplicationId.fromSerialized(root.field(idField).asString());
Instant createdAt = Instant.ofEpochMilli(root.field(createdAtField).asLong());
DeploymentSpec deploymentSpec = DeploymentSpec.fromXml(root.field(deploymentSpecField).asString(), false);
ValidationOverrides validationOverrides = ValidationOverrides.fromXml(root.field(validationOverridesField).asString());
Change deploying = changeFromSlime(root.field(deployingField));
Change outstandingChange = changeFromSlime(root.field(outstandingChangeField));
Optional<IssueId> deploymentIssueId = Serializers.optionalString(root.field(deploymentIssueField)).map(IssueId::from);
Optional<IssueId> ownershipIssueId = Serializers.optionalString(root.field(ownershipIssueIdField)).map(IssueId::from);
Optional<User> owner = Serializers.optionalString(root.field(ownerField)).map(User::from);
OptionalInt majorVersion = Serializers.optionalInteger(root.field(majorVersionField));
ApplicationMetrics metrics = new ApplicationMetrics(root.field(queryQualityField).asDouble(),
root.field(writeQualityField).asDouble());
Set<PublicKey> deployKeys = deployKeysFromSlime(root.field(pemDeployKeysField));
List<Instance> instances = instancesFromSlime(id, deploymentSpec, root.field(instancesField));
OptionalLong projectId = Serializers.optionalLong(root.field(projectIdField));
Optional<ApplicationVersion> latestVersion = latestVersionFromSlimeWithFallback(root.field(latestVersionField), instances);
boolean builtInternally = root.field(builtInternallyField).asBool();
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
deployKeys, projectId, builtInternally, latestVersion, instances);
}
private Optional<ApplicationVersion> latestVersionFromSlimeWithFallback(Inspector latestVersionObject, List<Instance> instances) {
if (latestVersionObject.valid())
return Optional.of(applicationVersionFromSlime(latestVersionObject));
return instances.stream()
.flatMap(instance -> instance.deploymentJobs().statusOf(JobType.component).stream())
.flatMap(status -> status.lastSuccess().stream())
.map(JobStatus.JobRun::application)
.findFirst();
}
private List<Instance> instancesFromSlime(TenantAndApplicationId id, DeploymentSpec deploymentSpec, Inspector field) {
List<Instance> instances = new ArrayList<>();
field.traverse((ArrayTraverser) (name, object) -> {
InstanceName instanceName = InstanceName.from(object.field(instanceNameField).asString());
List<Deployment> deployments = deploymentsFromSlime(object.field(deploymentsField));
DeploymentJobs deploymentJobs = deploymentJobsFromSlime(object.field(deploymentJobsField));
List<AssignedRotation> assignedRotations = assignedRotationsFromSlime(deploymentSpec, object);
RotationStatus rotationStatus = rotationStatusFromSlime(object);
instances.add(new Instance(id.instance(instanceName),
deployments,
deploymentJobs,
assignedRotations,
rotationStatus));
});
return instances;
}
private Set<PublicKey> deployKeysFromSlime(Inspector array) {
Set<PublicKey> keys = new LinkedHashSet<>();
array.traverse((ArrayTraverser) (__, key) -> keys.add(KeyUtils.fromPemEncodedPublicKey(key.asString())));
return keys;
}
private List<Deployment> deploymentsFromSlime(Inspector array) {
List<Deployment> deployments = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> deployments.add(deploymentFromSlime(item)));
return deployments;
}
private Deployment deploymentFromSlime(Inspector deploymentObject) {
return new Deployment(zoneIdFromSlime(deploymentObject.field(zoneField)),
applicationVersionFromSlime(deploymentObject.field(applicationPackageRevisionField)),
Version.fromString(deploymentObject.field(versionField).asString()),
Instant.ofEpochMilli(deploymentObject.field(deployTimeField).asLong()),
clusterInfoMapFromSlime(deploymentObject.field(clusterInfoField)),
deploymentMetricsFromSlime(deploymentObject.field(deploymentMetricsField)),
DeploymentActivity.create(Serializers.optionalInstant(deploymentObject.field(lastQueriedField)),
Serializers.optionalInstant(deploymentObject.field(lastWrittenField)),
Serializers.optionalDouble(deploymentObject.field(lastQueriesPerSecondField)),
Serializers.optionalDouble(deploymentObject.field(lastWritesPerSecondField))));
}
private DeploymentMetrics deploymentMetricsFromSlime(Inspector object) {
Optional<Instant> instant = object.field(deploymentMetricsUpdateTime).valid() ?
Optional.of(Instant.ofEpochMilli(object.field(deploymentMetricsUpdateTime).asLong())) :
Optional.empty();
return new DeploymentMetrics(object.field(deploymentMetricsQPSField).asDouble(),
object.field(deploymentMetricsWPSField).asDouble(),
object.field(deploymentMetricsDocsField).asDouble(),
object.field(deploymentMetricsQueryLatencyField).asDouble(),
object.field(deploymentMetricsWriteLatencyField).asDouble(),
instant,
deploymentWarningsFrom(object.field(deploymentMetricsWarningsField)));
}
private Map<DeploymentMetrics.Warning, Integer> deploymentWarningsFrom(Inspector object) {
Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>();
object.traverse((ObjectTraverser) (name, value) -> warnings.put(DeploymentMetrics.Warning.valueOf(name),
(int) value.asLong()));
return Collections.unmodifiableMap(warnings);
}
private Map<ZoneId, RotationState> singleRotationStatusFromSlime(Inspector object) {
if (!object.valid()) {
return Collections.emptyMap();
}
Map<ZoneId, RotationState> rotationStatus = new LinkedHashMap<>();
object.traverse((ArrayTraverser) (idx, statusObject) -> {
var zone = zoneIdFromSlime(statusObject);
var status = RotationState.valueOf(statusObject.field(rotationStateField).asString());
rotationStatus.put(zone, status);
});
return Collections.unmodifiableMap(rotationStatus);
}
private Map<ClusterSpec.Id, ClusterInfo> clusterInfoMapFromSlime (Inspector object) {
Map<ClusterSpec.Id, ClusterInfo> map = new HashMap<>();
object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterInfoFromSlime(value)));
return map;
}
private ClusterInfo clusterInfoFromSlime(Inspector inspector) {
String flavor = inspector.field(clusterInfoFlavorField).asString();
int cost = (int)inspector.field(clusterInfoCostField).asLong();
String type = inspector.field(clusterInfoTypeField).asString();
double flavorCpu = inspector.field(clusterInfoCpuField).asDouble();
double flavorMem = inspector.field(clusterInfoMemField).asDouble();
double flavorDisk = inspector.field(clusterInfoDiskField).asDouble();
List<String> hostnames = new ArrayList<>();
inspector.field(clusterInfoHostnamesField).traverse((ArrayTraverser)(int index, Inspector value) -> hostnames.add(value.asString()));
return new ClusterInfo(flavor, cost, flavorCpu, flavorMem, flavorDisk, ClusterSpec.Type.from(type), hostnames);
}
private ZoneId zoneIdFromSlime(Inspector object) {
return ZoneId.from(object.field(environmentField).asString(), object.field(regionField).asString());
}
private ApplicationVersion applicationVersionFromSlime(Inspector object) {
if ( ! object.valid()) return ApplicationVersion.unknown;
OptionalLong applicationBuildNumber = Serializers.optionalLong(object.field(applicationBuildNumberField));
Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField));
if (sourceRevision.isEmpty() || applicationBuildNumber.isEmpty()) {
return ApplicationVersion.unknown;
}
Optional<String> authorEmail = Serializers.optionalString(object.field(authorEmailField));
Optional<Version> compileVersion = Serializers.optionalString(object.field(compileVersionField)).map(Version::fromString);
Optional<Instant> buildTime = Serializers.optionalInstant(object.field(buildTimeField));
if (authorEmail.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong());
if (compileVersion.isEmpty() || buildTime.isEmpty())
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get());
return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get(),
compileVersion.get(), buildTime.get());
}
private Optional<SourceRevision> sourceRevisionFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new SourceRevision(object.field(repositoryField).asString(),
object.field(branchField).asString(),
object.field(commitField).asString()));
}
private DeploymentJobs deploymentJobsFromSlime(Inspector object) {
List<JobStatus> jobStatusList = jobStatusListFromSlime(object.field(jobStatusField));
return new DeploymentJobs(jobStatusList);
}
private Change changeFromSlime(Inspector object) {
if ( ! object.valid()) return Change.empty();
Inspector versionFieldValue = object.field(versionField);
Change change = Change.empty();
if (versionFieldValue.valid())
change = Change.of(Version.fromString(versionFieldValue.asString()));
if (object.field(applicationBuildNumberField).valid())
change = change.with(applicationVersionFromSlime(object));
if (object.field(pinnedField).asBool())
change = change.withPin();
return change;
}
private List<JobStatus> jobStatusListFromSlime(Inspector array) {
List<JobStatus> jobStatusList = new ArrayList<>();
array.traverse((ArrayTraverser) (int i, Inspector item) -> jobStatusFromSlime(item).ifPresent(jobStatusList::add));
return jobStatusList;
}
private Optional<JobStatus> jobStatusFromSlime(Inspector object) {
Optional<JobType> jobType =
JobType.fromOptionalJobName(object.field(jobTypeField).asString());
if (jobType.isEmpty()) return Optional.empty();
Optional<JobError> jobError = Optional.empty();
if (object.field(errorField).valid())
jobError = Optional.of(JobError.valueOf(object.field(errorField).asString()));
return Optional.of(new JobStatus(jobType.get(),
jobError,
jobRunFromSlime(object.field(lastTriggeredField)),
jobRunFromSlime(object.field(lastCompletedField)),
jobRunFromSlime(object.field(firstFailingField)),
jobRunFromSlime(object.field(lastSuccessField)),
Serializers.optionalLong(object.field(pausedUntilField))));
}
private Optional<JobStatus.JobRun> jobRunFromSlime(Inspector object) {
if ( ! object.valid()) return Optional.empty();
return Optional.of(new JobStatus.JobRun(object.field(jobRunIdField).asLong(),
new Version(object.field(versionField).asString()),
applicationVersionFromSlime(object.field(revisionField)),
Serializers.optionalString(object.field(sourceVersionField)).map(Version::fromString),
Optional.of(object.field(sourceApplicationField)).filter(Inspector::valid).map(this::applicationVersionFromSlime),
object.field(reasonField).asString(),
Instant.ofEpochMilli(object.field(atField).asLong())));
}
private List<AssignedRotation> assignedRotationsFromSlime(DeploymentSpec deploymentSpec, Inspector root) {
var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>();
root.field(assignedRotationsField).traverse((ArrayTraverser) (idx, inspector) -> {
var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString());
var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString());
var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString());
var regions = deploymentSpec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
} |
I think this is used. | private void toSlime(Cursor object, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec)
.sortedJobs(instance.deploymentJobs().jobStatus().values());
Cursor deploymentJobsArray = object.setArray("deploymentJobs");
for (JobStatus job : jobStatus) {
Cursor jobObject = deploymentJobsArray.addObject();
jobObject.setString("type", job.type().jobName());
jobObject.setBool("success", job.isSuccess());
job.lastTriggered().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastTriggered")));
job.lastCompleted().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastCompleted")));
job.firstFailing().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("firstFailing")));
job.lastSuccess().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastSuccess")));
}
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.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);
});
Cursor globalRotationsArray = object.setArray("globalRotations");
instance.endpointsIn(controller.system())
.scope(Endpoint.Scope.global)
.legacy(false)
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
Set<RoutingPolicy> routingPolicies = controller.applications().routingPolicies().get(instance.id());
for (RoutingPolicy policy : routingPolicies) {
policy.rotationEndpointsIn(controller.system()).asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
}
List<Deployment> deployments = controller.applications().deploymentTrigger()
.steps(deploymentSpec)
.sortedDeployments(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());
}
}
} | policy.rotationEndpointsIn(controller.system()).asList().stream() | private void toSlime(Cursor object, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec)
.sortedJobs(instance.deploymentJobs().jobStatus().values());
Cursor deploymentJobsArray = object.setArray("deploymentJobs");
for (JobStatus job : jobStatus) {
Cursor jobObject = deploymentJobsArray.addObject();
jobObject.setString("type", job.type().jobName());
jobObject.setBool("success", job.isSuccess());
job.lastTriggered().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastTriggered")));
job.lastCompleted().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastCompleted")));
job.firstFailing().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("firstFailing")));
job.lastSuccess().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastSuccess")));
}
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.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);
});
Cursor globalRotationsArray = object.setArray("globalRotations");
instance.endpointsIn(controller.system())
.scope(Endpoint.Scope.global)
.legacy(false)
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
Set<RoutingPolicy> routingPolicies = controller.applications().routingPolicies().get(instance.id());
for (RoutingPolicy policy : routingPolicies) {
policy.rotationEndpointsIn(controller.system()).asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
}
List<Deployment> deployments = controller.applications().deploymentTrigger()
.steps(deploymentSpec)
.sortedDeployments(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());
}
}
} | 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/user")) return authenticatedUser(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}/cost")) return tenantCost(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/cost/{month}")) return tenantCost(path.get("tenant"), path.get("month"), 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}/deploying")) return deploying(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), 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"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), 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}/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}/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}/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/user")) return createUser(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"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), 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"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), 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}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), 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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"));
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"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"));
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}/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, "user", "tenant");
}
private HttpResponse authenticatedUser(HttpRequest request) {
Principal user = requireUserPrincipal(request);
if (user == null)
throw new NotAuthorizedException("You must be authenticated.");
String userName = user instanceof AthenzPrincipal ? ((AthenzPrincipal) user).getIdentity().getName() : user.getName();
TenantName tenantName = TenantName.from(UserTenant.normalizeUser(userName));
List<Tenant> tenants = controller.tenants().asList(new Credentials(user));
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setString("user", userName);
Cursor tenantsArray = response.setArray("tenants");
for (Tenant tenant : tenants)
tenantInTenantsListToSlime(tenant, request.getUri(), tenantsArray.addObject());
response.setBool("tenantExists", tenants.stream().anyMatch(tenant -> tenant.name().equals(tenantName)));
return new SlimeJsonResponse(slime);
}
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 tenantCost(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenantCost(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenantCost(Tenant tenant, HttpRequest request) {
var slime = new Slime();
var objectCursor = slime.setObject();
var monthsCursor = objectCursor.setArray("months");
return new SlimeJsonResponse(slime);
}
private HttpResponse tenantCost(String tenantName, String dateString, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenantCost(tenant, tenantCostParseDate(dateString), request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private LocalDate tenantCostParseDate(String dateString) {
var monthPattern = Pattern.compile("^(?<year>[0-9]{4})-(?<month>[0-9]{2})$");
var matcher = monthPattern.matcher(dateString);
if (matcher.matches()) {
var year = Integer.parseInt(matcher.group("year"));
var month = Integer.parseInt(matcher.group("month"));
return LocalDate.of(year, month, 1);
} else {
throw new IllegalArgumentException("Could not parse year-month '" + dateString + "'");
}
}
private HttpResponse tenantCost(Tenant tenant, LocalDate month, HttpRequest request) {
var slime = new Slime();
slime.setObject();
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Slime slime = new Slime();
Cursor array = slime.setArray();
for (Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true))
for (InstanceName instance : application.instances().keySet())
toSlime(application.id().instance(instance), array.addObject(), request);
}
return new SlimeJsonResponse(slime);
}
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 instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
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 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()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.canonicalFlavor());
nodeObject.setDouble("vcpu", node.vcpu());
nodeObject.setDouble("memoryGb", node.memoryGb());
nodeObject.setDouble("diskGb", node.diskGb());
nodeObject.setDouble("bandwidthGbps", node.bandwidthGbps());
nodeObject.setBool("fastDisk", node.fastDisk());
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
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";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
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) {
String triggered = controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName())
.stream().map(JobType::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 void toSlime(Cursor object, 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());
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if ( ! application.change().isEmpty())
toSlime(object.setObject("deploying"), application.change());
if ( ! application.outstandingChange().isEmpty())
toSlime(object.setObject("outstandingChange"), application.outstandingChange());
object.setString("compileVersion", compileVersion(application.id()).toFullString());
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : application.instances().values())
toSlime(instancesArray.addObject(), 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, Instance instance, Application application, HttpRequest request) {
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")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if ( ! application.change().isEmpty()) {
toSlime(object.setObject("deploying"), application.change());
}
if ( ! application.outstandingChange().isEmpty()) {
toSlime(object.setObject("outstandingChange"), application.outstandingChange());
}
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedJobs(instance.deploymentJobs().jobStatus().values());
object.setBool("deployedInternally", application.internal());
Cursor deploymentsArray = object.setArray("deploymentJobs");
for (JobStatus job : jobStatus) {
Cursor jobObject = deploymentsArray.addObject();
jobObject.setString("type", job.type().jobName());
jobObject.setBool("success", job.isSuccess());
job.lastTriggered().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastTriggered")));
job.lastCompleted().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastCompleted")));
job.firstFailing().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("firstFailing")));
job.lastSuccess().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastSuccess")));
}
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().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);
});
object.setString("compileVersion", compileVersion(application.id()).toFullString());
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor globalRotationsArray = object.setArray("globalRotations");
instance.endpointsIn(controller.system())
.scope(Endpoint.Scope.global)
.legacy(false)
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
Set<RoutingPolicy> routingPolicies = controller.applications().routingPolicies().get(instance.id());
for (RoutingPolicy policy : routingPolicies) {
policy.rotationEndpointsIn(controller.system()).asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
}
List<Deployment> deployments = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedDeployments(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 (!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());
}
}
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(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 endpointArray = response.setArray("endpoints");
for (var policy : controller.applications().routingPolicies().get(deploymentId)) {
Cursor endpointObject = endpointArray.addObject();
Endpoint endpoint = policy.endpointIn(controller.system());
endpointObject.setString("cluster", policy.cluster().value());
endpointObject.setBool("tls", endpoint.tls());
endpointObject.setString("url", endpoint.url().toString());
}
Cursor serviceUrlArray = response.setArray("serviceUrls");
controller.applications().getDeploymentEndpoints(deploymentId)
.forEach(endpoint -> serviceUrlArray.addString(endpoint.toString()));
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()));
controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId())).projectId()
.ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
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));
DeploymentCost appCost = new DeploymentCost(Map.of());
Cursor costObject = response.setObject("cost");
toSlime(appCost, costObject);
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"));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if ( ! revision.isPresent()) 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);
return controller.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 -> ! controller.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);
}
Inspector requestData = toSlime(request.getData()).get();
String reason = mandatory("reason", requestData).asString();
String agent = requireUserPrincipal(request).getName();
long timestamp = controller.clock().instant().getEpochSecond();
EndpointStatus.Status status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
EndpointStatus endpointStatus = new EndpointStatus(status, reason, agent, timestamp);
controller.applications().setGlobalRotationStatus(new DeploymentId(instance.id(), deployment.zone()),
endpointStatus);
return new MessageResponse(String.format("Successfully set %s in %s.%s %s service",
instance.id().toShortString(),
deployment.zone().environment().value(),
deployment.zone().region().value(),
inService ? "in" : "out of"));
}
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");
Map<RoutingEndpoint, EndpointStatus> status = controller.applications().globalRotationStatus(deploymentId);
for (RoutingEndpoint endpoint : status.keySet()) {
EndpointStatus currentStatus = status.get(endpoint);
array.addString(endpoint.upstreamName());
Cursor statusObject = array.addObject();
statusObject.setString("status", currentStatus.getStatus().name());
statusObject.setString("reason", currentStatus.getReason() == null ? "" : currentStatus.getReason());
statusObject.setString("agent", currentStatus.getAgent() == null ? "" : currentStatus.getAgent());
statusObject.setLong("timestamp", currentStatus.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();
MeteringInfo meteringInfo = controller.serviceRegistry().meteringService().getResourceSnapshots(tenant, application);
ResourceAllocation currentSnapshot = meteringInfo.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringInfo.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringInfo.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 = meteringInfo.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 tenant, String application, HttpRequest request) {
Application app = controller.applications().requireApplication(TenantAndApplicationId.from(tenant, application));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! app.change().isEmpty()) {
app.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
app.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", app.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) {
Map<?,?> result = controller.getServiceApiResponse(tenantName, applicationName, instanceName, environment, region, serviceName, restPath);
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(result, serviceName, restPath);
return response;
}
private HttpResponse createUser(HttpRequest request) {
String user = Optional.of(requireUserPrincipal(request))
.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.map(AthenzIdentity::getName)
.map(UserTenant::normalizeUser)
.orElseThrow(() -> new ForbiddenException("Not authenticated or not a user."));
UserTenant tenant = UserTenant.create(user);
try {
controller.tenants().createUser(tenant);
return new MessageResponse("Created user '" + user + "'");
} catch (AlreadyExistsException e) {
return new MessageResponse("User '" + user + "' already exists");
}
}
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);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest()));
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, boolean pin, HttpRequest request) {
request = controller.auditLogger().log(request);
String versionString = readToString(request.getData());
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(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 " + change + " for " + 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, HttpRequest request) {
controller.auditLogger().log(request);
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered " + change + " for " + 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 choice) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = application.get().change();
if (change.isEmpty()) {
response.append("No deployment in progress for " + application + " at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '" + change + "' to '" +
controller.applications().requireApplication(id).change() + "' for " + application);
});
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) {
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(),
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);
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<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,
application.get().internal(),
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,
application.get().internal(),
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
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.isPresent())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
if (tenant.get().type() == Tenant.Type.user)
controller.tenants().deleteUser((UserTenant) tenant.get());
else
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);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(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);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty())
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) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
DeploymentId deploymentId = new DeploymentId(instance.id(), ZoneId.from(environment, region));
controller.applications().deactivate(deploymentId.applicationId(), deploymentId.zoneId());
return new MessageResponse("Deactivated " + deploymentId);
}
private HttpResponse notifyJobCompletion(String tenant, String application, HttpRequest request) {
try {
DeploymentJobs.JobReport report = toJobReport(tenant, application, toSlime(request.getData()).get());
if ( report.jobType() == JobType.component
&& controller.applications().requireApplication(TenantAndApplicationId.from(report.applicationId())).internal())
throw new IllegalArgumentException(report.applicationId() + " is set up to be deployed from internally, and no " +
"longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.");
controller.applications().deploymentTrigger().notifyOfCompletion(report);
return new MessageResponse("ok");
} catch (IllegalStateException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
}
private HttpResponse testConfig(ApplicationId id, JobType type) {
Set<ZoneId> zones = controller.jobController().testedZoneAndProductionZones(id, type);
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.applications().clusterEndpoints(id, zones),
controller.applications().contentClustersByZone(id, zones)));
}
private static DeploymentJobs.JobReport toJobReport(String tenantName, String applicationName, Inspector report) {
Optional<DeploymentJobs.JobError> jobError = Optional.empty();
if (report.field("jobError").valid()) {
jobError = Optional.of(DeploymentJobs.JobError.valueOf(report.field("jobError").asString()));
}
ApplicationId id = ApplicationId.from(tenantName, applicationName, report.field("instance").asString());
JobType type = JobType.fromJobName(report.field("jobName").asString());
long buildNumber = report.field("buildNumber").asLong();
if (type == JobType.component)
return DeploymentJobs.JobReport.ofComponent(id,
report.field("projectId").asLong(),
buildNumber,
jobError,
toSourceRevision(report.field("sourceRevision")));
else
return DeploymentJobs.JobReport.ofJob(id, type, buildNumber, jobError);
}
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<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 user: 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 (Application application : applications)
for (Instance instance : application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, application, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
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 user: 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(JobStatus.JobRun jobRun, Cursor object) {
object.setLong("id", jobRun.id());
object.setString("version", jobRun.platform().toFullString());
if (!jobRun.application().isUnknown())
toSlime(jobRun.application(), object.setObject("revision"));
object.setString("reason", jobRun.reason());
object.setLong("at", jobRun.at().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));
}
public static void toSlime(DeploymentCost deploymentCost, Cursor object) {
object.setLong("tco", (long)deploymentCost.getTco());
object.setLong("waste", (long)deploymentCost.getWaste());
object.setDouble("utilization", deploymentCost.getUtilization());
Cursor clustersObject = object.setObject("cluster");
for (Map.Entry<String, ClusterCost> clusterEntry : deploymentCost.getCluster().entrySet())
toSlime(clusterEntry.getValue(), clustersObject.setObject(clusterEntry.getKey()));
}
private static void toSlime(ClusterCost clusterCost, Cursor object) {
object.setLong("count", clusterCost.getClusterInfo().getHostnames().size());
object.setString("resource", getResourceName(clusterCost.getResultUtilization()));
object.setDouble("utilization", clusterCost.getResultUtilization().getMaxUtilization());
object.setLong("tco", (int)clusterCost.getTco());
object.setLong("waste", (int)clusterCost.getWaste());
object.setString("flavor", clusterCost.getClusterInfo().getFlavor());
object.setDouble("flavorCost", clusterCost.getClusterInfo().getFlavorCost());
object.setDouble("flavorCpu", clusterCost.getClusterInfo().getFlavorCPU());
object.setDouble("flavorMem", clusterCost.getClusterInfo().getFlavorMem());
object.setDouble("flavorDisk", clusterCost.getClusterInfo().getFlavorDisk());
object.setString("type", clusterCost.getClusterInfo().getClusterType().name());
Cursor utilObject = object.setObject("util");
utilObject.setDouble("cpu", clusterCost.getResultUtilization().getCpu());
utilObject.setDouble("mem", clusterCost.getResultUtilization().getMemory());
utilObject.setDouble("disk", clusterCost.getResultUtilization().getDisk());
utilObject.setDouble("diskBusy", clusterCost.getResultUtilization().getDiskBusy());
Cursor usageObject = object.setObject("usage");
usageObject.setDouble("cpu", clusterCost.getSystemUtilization().getCpu());
usageObject.setDouble("mem", clusterCost.getSystemUtilization().getMemory());
usageObject.setDouble("disk", clusterCost.getSystemUtilization().getDisk());
usageObject.setDouble("diskBusy", clusterCost.getSystemUtilization().getDiskBusy());
Cursor hostnamesArray = object.setArray("hostnames");
for (String hostname : clusterCost.getClusterInfo().getHostnames())
hostnamesArray.addString(hostname);
}
private static String getResourceName(ClusterUtilization utilization) {
String name = "cpu";
double max = utilization.getMaxUtilization();
if (utilization.getMemory() == max) {
name = "mem";
} else if (utilization.getDisk() == max) {
name = "disk";
} else if (utilization.getDiskBusy() == max) {
name = "diskbusy";
}
return name;
}
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 String tenantType(Tenant tenant) {
switch (tenant.type()) {
case user: return "USER";
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();
SourceRevision sourceRevision = toSourceRevision(submitOptions);
String authorEmail = submitOptions.field("authorEmail").asString();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
if (DeploymentSpec.empty.equals(applicationPackage.deploymentSpec()))
throw new IllegalArgumentException("Missing required file 'deployment.xml'");
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
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";
}
} | 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/user")) return authenticatedUser(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}/cost")) return tenantCost(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/cost/{month}")) return tenantCost(path.get("tenant"), path.get("month"), 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}/deploying")) return deploying(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), 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"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), 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}/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}/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}/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/user")) return createUser(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"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), 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"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/jobreport")) return notifyJobCompletion(path.get("tenant"), path.get("application"), 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}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), 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}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"));
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"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return JobControllerApiHandlerHelper.unregisterResponse(controller.jobController(), path.get("tenant"), path.get("application"));
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}/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, "user", "tenant");
}
private HttpResponse authenticatedUser(HttpRequest request) {
Principal user = requireUserPrincipal(request);
if (user == null)
throw new NotAuthorizedException("You must be authenticated.");
String userName = user instanceof AthenzPrincipal ? ((AthenzPrincipal) user).getIdentity().getName() : user.getName();
TenantName tenantName = TenantName.from(UserTenant.normalizeUser(userName));
List<Tenant> tenants = controller.tenants().asList(new Credentials(user));
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setString("user", userName);
Cursor tenantsArray = response.setArray("tenants");
for (Tenant tenant : tenants)
tenantInTenantsListToSlime(tenant, request.getUri(), tenantsArray.addObject());
response.setBool("tenantExists", tenants.stream().anyMatch(tenant -> tenant.name().equals(tenantName)));
return new SlimeJsonResponse(slime);
}
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 tenantCost(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenantCost(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenantCost(Tenant tenant, HttpRequest request) {
var slime = new Slime();
var objectCursor = slime.setObject();
var monthsCursor = objectCursor.setArray("months");
return new SlimeJsonResponse(slime);
}
private HttpResponse tenantCost(String tenantName, String dateString, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.map(tenant -> tenantCost(tenant, tenantCostParseDate(dateString), request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private LocalDate tenantCostParseDate(String dateString) {
var monthPattern = Pattern.compile("^(?<year>[0-9]{4})-(?<month>[0-9]{2})$");
var matcher = monthPattern.matcher(dateString);
if (matcher.matches()) {
var year = Integer.parseInt(matcher.group("year"));
var month = Integer.parseInt(matcher.group("month"));
return LocalDate.of(year, month, 1);
} else {
throw new IllegalArgumentException("Could not parse year-month '" + dateString + "'");
}
}
private HttpResponse tenantCost(Tenant tenant, LocalDate month, HttpRequest request) {
var slime = new Slime();
slime.setObject();
return new SlimeJsonResponse(slime);
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Slime slime = new Slime();
Cursor array = slime.setArray();
for (Application application : controller.applications().asList(tenant)) {
if (applicationName.map(application.id().application().value()::equals).orElse(true))
for (InstanceName instance : application.instances().keySet())
toSlime(application.id().instance(instance), array.addObject(), request);
}
return new SlimeJsonResponse(slime);
}
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 instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
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 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()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
nodeObject.setString("flavor", node.canonicalFlavor());
nodeObject.setDouble("vcpu", node.vcpu());
nodeObject.setDouble("memoryGb", node.memoryGb());
nodeObject.setDouble("diskGb", node.diskGb());
nodeObject.setDouble("bandwidthGbps", node.bandwidthGbps());
nodeObject.setBool("fastDisk", node.fastDisk());
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
}
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";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
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) {
String triggered = controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName())
.stream().map(JobType::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 void toSlime(Cursor object, 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());
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if ( ! application.change().isEmpty())
toSlime(object.setObject("deploying"), application.change());
if ( ! application.outstandingChange().isEmpty())
toSlime(object.setObject("outstandingChange"), application.outstandingChange());
object.setString("compileVersion", compileVersion(application.id()).toFullString());
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : application.instances().values())
toSlime(instancesArray.addObject(), 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, Instance instance, Application application, HttpRequest request) {
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")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if ( ! application.change().isEmpty()) {
toSlime(object.setObject("deploying"), application.change());
}
if ( ! application.outstandingChange().isEmpty()) {
toSlime(object.setObject("outstandingChange"), application.outstandingChange());
}
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedJobs(instance.deploymentJobs().jobStatus().values());
object.setBool("deployedInternally", application.internal());
Cursor deploymentsArray = object.setArray("deploymentJobs");
for (JobStatus job : jobStatus) {
Cursor jobObject = deploymentsArray.addObject();
jobObject.setString("type", job.type().jobName());
jobObject.setBool("success", job.isSuccess());
job.lastTriggered().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastTriggered")));
job.lastCompleted().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastCompleted")));
job.firstFailing().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("firstFailing")));
job.lastSuccess().ifPresent(jobRun -> toSlime(jobRun, jobObject.setObject("lastSuccess")));
}
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().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);
});
object.setString("compileVersion", compileVersion(application.id()).toFullString());
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor globalRotationsArray = object.setArray("globalRotations");
instance.endpointsIn(controller.system())
.scope(Endpoint.Scope.global)
.legacy(false)
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
Set<RoutingPolicy> routingPolicies = controller.applications().routingPolicies().get(instance.id());
for (RoutingPolicy policy : routingPolicies) {
policy.rotationEndpointsIn(controller.system()).asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalRotationsArray::addString);
}
List<Deployment> deployments = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec())
.sortedDeployments(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 (!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());
}
}
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(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 endpointArray = response.setArray("endpoints");
for (var policy : controller.applications().routingPolicies().get(deploymentId)) {
Cursor endpointObject = endpointArray.addObject();
Endpoint endpoint = policy.endpointIn(controller.system());
endpointObject.setString("cluster", policy.cluster().value());
endpointObject.setBool("tls", endpoint.tls());
endpointObject.setString("url", endpoint.url().toString());
}
Cursor serviceUrlArray = response.setArray("serviceUrls");
controller.applications().getDeploymentEndpoints(deploymentId)
.forEach(endpoint -> serviceUrlArray.addString(endpoint.toString()));
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()));
controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId())).projectId()
.ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
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));
DeploymentCost appCost = new DeploymentCost(Map.of());
Cursor costObject = response.setObject("cost");
toSlime(appCost, costObject);
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"));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if ( ! revision.isPresent()) 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);
return controller.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 -> ! controller.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);
}
Inspector requestData = toSlime(request.getData()).get();
String reason = mandatory("reason", requestData).asString();
String agent = requireUserPrincipal(request).getName();
long timestamp = controller.clock().instant().getEpochSecond();
EndpointStatus.Status status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
EndpointStatus endpointStatus = new EndpointStatus(status, reason, agent, timestamp);
controller.applications().setGlobalRotationStatus(new DeploymentId(instance.id(), deployment.zone()),
endpointStatus);
return new MessageResponse(String.format("Successfully set %s in %s.%s %s service",
instance.id().toShortString(),
deployment.zone().environment().value(),
deployment.zone().region().value(),
inService ? "in" : "out of"));
}
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");
Map<RoutingEndpoint, EndpointStatus> status = controller.applications().globalRotationStatus(deploymentId);
for (RoutingEndpoint endpoint : status.keySet()) {
EndpointStatus currentStatus = status.get(endpoint);
array.addString(endpoint.upstreamName());
Cursor statusObject = array.addObject();
statusObject.setString("status", currentStatus.getStatus().name());
statusObject.setString("reason", currentStatus.getReason() == null ? "" : currentStatus.getReason());
statusObject.setString("agent", currentStatus.getAgent() == null ? "" : currentStatus.getAgent());
statusObject.setLong("timestamp", currentStatus.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();
MeteringInfo meteringInfo = controller.serviceRegistry().meteringService().getResourceSnapshots(tenant, application);
ResourceAllocation currentSnapshot = meteringInfo.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringInfo.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringInfo.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 = meteringInfo.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 tenant, String application, HttpRequest request) {
Application app = controller.applications().requireApplication(TenantAndApplicationId.from(tenant, application));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! app.change().isEmpty()) {
app.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
app.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", app.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) {
Map<?,?> result = controller.getServiceApiResponse(tenantName, applicationName, instanceName, environment, region, serviceName, restPath);
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(result, serviceName, restPath);
return response;
}
private HttpResponse createUser(HttpRequest request) {
String user = Optional.of(requireUserPrincipal(request))
.filter(AthenzPrincipal.class::isInstance)
.map(AthenzPrincipal.class::cast)
.map(AthenzPrincipal::getIdentity)
.filter(AthenzUser.class::isInstance)
.map(AthenzIdentity::getName)
.map(UserTenant::normalizeUser)
.orElseThrow(() -> new ForbiddenException("Not authenticated or not a user."));
UserTenant tenant = UserTenant.create(user);
try {
controller.tenants().createUser(tenant);
return new MessageResponse("Created user '" + user + "'");
} catch (AlreadyExistsException e) {
return new MessageResponse("User '" + user + "' already exists");
}
}
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);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest()));
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, boolean pin, HttpRequest request) {
request = controller.auditLogger().log(request);
String versionString = readToString(request.getData());
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(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 " + change + " for " + 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, HttpRequest request) {
controller.auditLogger().log(request);
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered " + change + " for " + 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 choice) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(id, application -> {
Change change = application.get().change();
if (change.isEmpty()) {
response.append("No deployment in progress for " + application + " at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '" + change + "' to '" +
controller.applications().requireApplication(id).change() + "' for " + application);
});
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) {
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(),
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);
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<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,
application.get().internal(),
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,
application.get().internal(),
applicationVersion.get()));
}
DeployOptions deployOptionsJsonClass = new DeployOptions(deployDirectly,
vespaVersion,
deployOptions.field("ignoreValidationErrors").asBool(),
deployOptions.field("deployCurrentVersion").asBool());
applicationPackage.ifPresent(aPackage -> controller.applications().verifyApplicationIdentityConfiguration(applicationId.tenant(),
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.isPresent())
return ErrorResponse.notFoundError("Could not delete tenant '" + tenantName + "': Tenant not found");
if (tenant.get().type() == Tenant.Type.user)
controller.tenants().deleteUser((UserTenant) tenant.get());
else
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);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(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);
Optional<Credentials> credentials = controller.tenants().require(id.tenant()).type() == Tenant.Type.user
? Optional.empty()
: Optional.of(accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest()));
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty())
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) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
DeploymentId deploymentId = new DeploymentId(instance.id(), ZoneId.from(environment, region));
controller.applications().deactivate(deploymentId.applicationId(), deploymentId.zoneId());
return new MessageResponse("Deactivated " + deploymentId);
}
private HttpResponse notifyJobCompletion(String tenant, String application, HttpRequest request) {
try {
DeploymentJobs.JobReport report = toJobReport(tenant, application, toSlime(request.getData()).get());
if ( report.jobType() == JobType.component
&& controller.applications().requireApplication(TenantAndApplicationId.from(report.applicationId())).internal())
throw new IllegalArgumentException(report.applicationId() + " is set up to be deployed from internally, and no " +
"longer accepts submissions from Screwdriver v3 jobs. If you need to revert " +
"to the old pipeline, please file a ticket at yo/vespa-support and request this.");
controller.applications().deploymentTrigger().notifyOfCompletion(report);
return new MessageResponse("ok");
} catch (IllegalStateException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
}
private HttpResponse testConfig(ApplicationId id, JobType type) {
Set<ZoneId> zones = controller.jobController().testedZoneAndProductionZones(id, type);
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.applications().clusterEndpoints(id, zones),
controller.applications().contentClustersByZone(id, zones)));
}
private static DeploymentJobs.JobReport toJobReport(String tenantName, String applicationName, Inspector report) {
Optional<DeploymentJobs.JobError> jobError = Optional.empty();
if (report.field("jobError").valid()) {
jobError = Optional.of(DeploymentJobs.JobError.valueOf(report.field("jobError").asString()));
}
ApplicationId id = ApplicationId.from(tenantName, applicationName, report.field("instance").asString());
JobType type = JobType.fromJobName(report.field("jobName").asString());
long buildNumber = report.field("buildNumber").asLong();
if (type == JobType.component)
return DeploymentJobs.JobReport.ofComponent(id,
report.field("projectId").asLong(),
buildNumber,
jobError,
toSourceRevision(report.field("sourceRevision")));
else
return DeploymentJobs.JobReport.ofJob(id, type, buildNumber, jobError);
}
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<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 user: 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 (Application application : applications)
for (Instance instance : application.instances().values())
if (recurseOverApplications(request))
toSlime(applicationArray.addObject(), instance, application, request);
else
toSlime(instance.id(), applicationArray.addObject(), request);
}
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 user: 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(JobStatus.JobRun jobRun, Cursor object) {
object.setLong("id", jobRun.id());
object.setString("version", jobRun.platform().toFullString());
if (!jobRun.application().isUnknown())
toSlime(jobRun.application(), object.setObject("revision"));
object.setString("reason", jobRun.reason());
object.setLong("at", jobRun.at().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));
}
public static void toSlime(DeploymentCost deploymentCost, Cursor object) {
object.setLong("tco", (long)deploymentCost.getTco());
object.setLong("waste", (long)deploymentCost.getWaste());
object.setDouble("utilization", deploymentCost.getUtilization());
Cursor clustersObject = object.setObject("cluster");
for (Map.Entry<String, ClusterCost> clusterEntry : deploymentCost.getCluster().entrySet())
toSlime(clusterEntry.getValue(), clustersObject.setObject(clusterEntry.getKey()));
}
private static void toSlime(ClusterCost clusterCost, Cursor object) {
object.setLong("count", clusterCost.getClusterInfo().getHostnames().size());
object.setString("resource", getResourceName(clusterCost.getResultUtilization()));
object.setDouble("utilization", clusterCost.getResultUtilization().getMaxUtilization());
object.setLong("tco", (int)clusterCost.getTco());
object.setLong("waste", (int)clusterCost.getWaste());
object.setString("flavor", clusterCost.getClusterInfo().getFlavor());
object.setDouble("flavorCost", clusterCost.getClusterInfo().getFlavorCost());
object.setDouble("flavorCpu", clusterCost.getClusterInfo().getFlavorCPU());
object.setDouble("flavorMem", clusterCost.getClusterInfo().getFlavorMem());
object.setDouble("flavorDisk", clusterCost.getClusterInfo().getFlavorDisk());
object.setString("type", clusterCost.getClusterInfo().getClusterType().name());
Cursor utilObject = object.setObject("util");
utilObject.setDouble("cpu", clusterCost.getResultUtilization().getCpu());
utilObject.setDouble("mem", clusterCost.getResultUtilization().getMemory());
utilObject.setDouble("disk", clusterCost.getResultUtilization().getDisk());
utilObject.setDouble("diskBusy", clusterCost.getResultUtilization().getDiskBusy());
Cursor usageObject = object.setObject("usage");
usageObject.setDouble("cpu", clusterCost.getSystemUtilization().getCpu());
usageObject.setDouble("mem", clusterCost.getSystemUtilization().getMemory());
usageObject.setDouble("disk", clusterCost.getSystemUtilization().getDisk());
usageObject.setDouble("diskBusy", clusterCost.getSystemUtilization().getDiskBusy());
Cursor hostnamesArray = object.setArray("hostnames");
for (String hostname : clusterCost.getClusterInfo().getHostnames())
hostnamesArray.addString(hostname);
}
private static String getResourceName(ClusterUtilization utilization) {
String name = "cpu";
double max = utilization.getMaxUtilization();
if (utilization.getMemory() == max) {
name = "mem";
} else if (utilization.getDisk() == max) {
name = "disk";
} else if (utilization.getDiskBusy() == max) {
name = "diskbusy";
}
return name;
}
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 String tenantType(Tenant tenant) {
switch (tenant.type()) {
case user: return "USER";
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();
SourceRevision sourceRevision = toSourceRevision(submitOptions);
String authorEmail = submitOptions.field("authorEmail").asString();
long projectId = Math.max(1, submitOptions.field("projectId").asLong());
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
if (DeploymentSpec.empty.equals(applicationPackage.deploymentSpec()))
throw new IllegalArgumentException("Missing required file 'deployment.xml'");
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
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";
}
} |
Update prefix of exception message too? "SAN DNS name" --> XYZ | private HttpResponse refreshInstance(HttpRequest request, String provider, String service, String instanceId) {
var instanceRefresh = deserializeRequest(request, InstanceSerializer::refreshFromSlime);
var instanceIdFromCsr = Certificates.instanceIdFrom(instanceRefresh.csr());
if (!instanceIdFromCsr.equals(instanceId)) {
throw new IllegalArgumentException("Mismatched instance ID and SAN DNS name [instanceId=" + instanceId +
",instanceIdFromCsr=" + instanceIdFromCsr + "]");
}
var certificate = certificates.create(instanceRefresh.csr(), caCertificate(), caPrivateKey());
var identity = new InstanceIdentity(provider, service, instanceIdFromCsr, Optional.of(certificate));
return new SlimeJsonResponse(InstanceSerializer.identityToSlime(identity));
} | ",instanceIdFromCsr=" + instanceIdFromCsr + "]"); | private HttpResponse refreshInstance(HttpRequest request, String provider, String service, String instanceId) {
var instanceRefresh = deserializeRequest(request, InstanceSerializer::refreshFromSlime);
var instanceIdFromCsr = Certificates.instanceIdFrom(instanceRefresh.csr());
if (!instanceIdFromCsr.equals(instanceId)) {
throw new IllegalArgumentException("Mismatch between instance ID in URL path and instance ID in CSR " +
"[instanceId=" + instanceId + ",instanceIdFromCsr=" + instanceIdFromCsr +
"]");
}
var certificate = certificates.create(instanceRefresh.csr(), caCertificate(), caPrivateKey());
var identity = new InstanceIdentity(provider, service, instanceIdFromCsr, Optional.of(certificate));
return new SlimeJsonResponse(InstanceSerializer.identityToSlime(identity));
} | class CertificateAuthorityApiHandler extends LoggingRequestHandler {
private final SecretStore secretStore;
private final Certificates certificates;
private final String caPrivateKeySecretName;
private final String caCertificateSecretName;
@Inject
public CertificateAuthorityApiHandler(Context ctx, SecretStore secretStore, AthenzProviderServiceConfig athenzProviderServiceConfig) {
this(ctx, secretStore, new Certificates(Clock.systemUTC()), athenzProviderServiceConfig);
}
CertificateAuthorityApiHandler(Context ctx, SecretStore secretStore, Certificates certificates, AthenzProviderServiceConfig athenzProviderServiceConfig) {
super(ctx);
this.secretStore = secretStore;
this.certificates = certificates;
this.caPrivateKeySecretName = athenzProviderServiceConfig.secretName();
this.caCertificateSecretName = athenzProviderServiceConfig.domain() + ".ca.cert";
}
@Override
public HttpResponse handle(HttpRequest request) {
try {
switch (request.getMethod()) {
case POST: return handlePost(request);
default: return ErrorResponse.methodNotAllowed("Method " + request.getMethod() + " is unsupported");
}
} catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(request.getMethod() + " " + request.getUri() + " failed: " + Exceptions.toMessageString(e));
} catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling " + request.getMethod() + " " + request.getUri(), e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handlePost(HttpRequest request) {
Path path = new Path(request.getUri());
if (path.matches("/ca/v1/instance/")) return registerInstance(request);
if (path.matches("/ca/v1/instance/{provider}/{domain}/{service}/{instanceId}")) return refreshInstance(request, path.get("provider"), path.get("service"), path.get("instanceId"));
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse registerInstance(HttpRequest request) {
var instanceRegistration = deserializeRequest(request, InstanceSerializer::registrationFromSlime);
var certificate = certificates.create(instanceRegistration.csr(), caCertificate(), caPrivateKey());
var instanceId = Certificates.instanceIdFrom(instanceRegistration.csr());
var identity = new InstanceIdentity(instanceRegistration.provider(), instanceRegistration.service(), instanceId,
Optional.of(certificate));
return new SlimeJsonResponse(InstanceSerializer.identityToSlime(identity));
}
/** Returns CA certificate from secret store */
private X509Certificate caCertificate() {
return X509CertificateUtils.fromPem(secretStore.getSecret(caCertificateSecretName));
}
/** Returns CA private key from secret store */
private PrivateKey caPrivateKey() {
return KeyUtils.fromPemEncodedPrivateKey(secretStore.getSecret(caPrivateKeySecretName));
}
private static <T> T deserializeRequest(HttpRequest request, Function<Slime, T> serializer) {
try {
var slime = SlimeUtils.jsonToSlime(request.getData().readAllBytes());
return serializer.apply(slime);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
} | class CertificateAuthorityApiHandler extends LoggingRequestHandler {
private final SecretStore secretStore;
private final Certificates certificates;
private final String caPrivateKeySecretName;
private final String caCertificateSecretName;
@Inject
public CertificateAuthorityApiHandler(Context ctx, SecretStore secretStore, AthenzProviderServiceConfig athenzProviderServiceConfig) {
this(ctx, secretStore, new Certificates(Clock.systemUTC()), athenzProviderServiceConfig);
}
CertificateAuthorityApiHandler(Context ctx, SecretStore secretStore, Certificates certificates, AthenzProviderServiceConfig athenzProviderServiceConfig) {
super(ctx);
this.secretStore = secretStore;
this.certificates = certificates;
this.caPrivateKeySecretName = athenzProviderServiceConfig.secretName();
this.caCertificateSecretName = athenzProviderServiceConfig.domain() + ".ca.cert";
}
@Override
public HttpResponse handle(HttpRequest request) {
try {
switch (request.getMethod()) {
case POST: return handlePost(request);
default: return ErrorResponse.methodNotAllowed("Method " + request.getMethod() + " is unsupported");
}
} catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(request.getMethod() + " " + request.getUri() + " failed: " + Exceptions.toMessageString(e));
} catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling " + request.getMethod() + " " + request.getUri(), e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handlePost(HttpRequest request) {
Path path = new Path(request.getUri());
if (path.matches("/ca/v1/instance/")) return registerInstance(request);
if (path.matches("/ca/v1/instance/{provider}/{domain}/{service}/{instanceId}")) return refreshInstance(request, path.get("provider"), path.get("service"), path.get("instanceId"));
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse registerInstance(HttpRequest request) {
var instanceRegistration = deserializeRequest(request, InstanceSerializer::registrationFromSlime);
var certificate = certificates.create(instanceRegistration.csr(), caCertificate(), caPrivateKey());
var instanceId = Certificates.instanceIdFrom(instanceRegistration.csr());
var identity = new InstanceIdentity(instanceRegistration.provider(), instanceRegistration.service(), instanceId,
Optional.of(certificate));
return new SlimeJsonResponse(InstanceSerializer.identityToSlime(identity));
}
/** Returns CA certificate from secret store */
private X509Certificate caCertificate() {
return X509CertificateUtils.fromPem(secretStore.getSecret(caCertificateSecretName));
}
/** Returns CA private key from secret store */
private PrivateKey caPrivateKey() {
return KeyUtils.fromPemEncodedPrivateKey(secretStore.getSecret(caPrivateKeySecretName));
}
private static <T> T deserializeRequest(HttpRequest request, Function<Slime, T> serializer) {
try {
var slime = SlimeUtils.jsonToSlime(request.getData().readAllBytes());
return serializer.apply(slime);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
} |
Ttwo have upgraded, so x3 + 1s should be enough to fail the rest, if I understand correctly? | public void test_nodes_failing_os_upgrade() {
var tester = new DeploymentTester();
var reporter = createReporter(tester.controller());
var zone = ZoneApiMock.fromId("prod.eu-west-1");
var cloud = CloudName.defaultName();
tester.controllerTester().zoneRegistry().setOsUpgradePolicy(cloud, UpgradePolicy.create().upgrade(zone));
var osUpgrader = new OsUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.controllerTester().curator()), CloudName.defaultName());;
var statusUpdater = new OsVersionStatusUpdater(tester.controller(), Duration.ofDays(1),
new JobControl(tester.controller().curator()));
tester.configServer().bootstrap(List.of(zone.getId()), SystemApplication.configServerHost, SystemApplication.tenantHost);
var version0 = Version.fromString("8.0");
tester.controller().upgradeOsIn(cloud, version0, false);
osUpgrader.maintain();
tester.configServer().setOsVersion(SystemApplication.tenantHost.id(), zone.getId(), version0);
tester.configServer().setOsVersion(SystemApplication.configServerHost.id(), zone.getId(), version0);
statusUpdater.maintain();
reporter.maintain();
assertEquals(0, getNodesFailingOsUpgrade());
for (var version : List.of(Version.fromString("8.1"), Version.fromString("8.2"))) {
tester.controller().upgradeOsIn(cloud, version, false);
osUpgrader.maintain();
statusUpdater.maintain();
reporter.maintain();
assertEquals(0, getNodesFailingOsUpgrade());
tester.clock().advance(Duration.ofMinutes(30));
statusUpdater.maintain();
reporter.maintain();
assertEquals(0, getNodesFailingOsUpgrade());
tester.configServer().setOsVersion(SystemApplication.tenantHost.id(), zone.getId(), version, 2);
tester.clock().advance(Duration.ofMinutes(30 * 4 /* time allowance * node count */).plus(Duration.ofSeconds(1)));
statusUpdater.maintain();
reporter.maintain();
assertEquals(4, getNodesFailingOsUpgrade());
tester.configServer().setOsVersion(SystemApplication.tenantHost.id(), zone.getId(), version);
tester.configServer().setOsVersion(SystemApplication.configServerHost.id(), zone.getId(), version, 2);
statusUpdater.maintain();
reporter.maintain();
assertEquals(1, getNodesFailingOsUpgrade());
tester.configServer().setOsVersion(SystemApplication.configServerHost.id(), zone.getId(), version);
statusUpdater.maintain();
reporter.maintain();
assertEquals(0, getNodesFailingOsUpgrade());
}
} | tester.clock().advance(Duration.ofMinutes(30 * 4 /* time allowance * node count */).plus(Duration.ofSeconds(1))); | public void test_nodes_failing_os_upgrade() {
var tester = new DeploymentTester();
var reporter = createReporter(tester.controller());
var zone = ZoneApiMock.fromId("prod.eu-west-1");
var cloud = CloudName.defaultName();
tester.controllerTester().zoneRegistry().setOsUpgradePolicy(cloud, UpgradePolicy.create().upgrade(zone));
var osUpgrader = new OsUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.controllerTester().curator()), CloudName.defaultName());;
var statusUpdater = new OsVersionStatusUpdater(tester.controller(), Duration.ofDays(1),
new JobControl(tester.controller().curator()));
tester.configServer().bootstrap(List.of(zone.getId()), SystemApplication.configServerHost, SystemApplication.tenantHost);
var version0 = Version.fromString("8.0");
tester.controller().upgradeOsIn(cloud, version0, false);
osUpgrader.maintain();
tester.configServer().setOsVersion(SystemApplication.tenantHost.id(), zone.getId(), version0);
tester.configServer().setOsVersion(SystemApplication.configServerHost.id(), zone.getId(), version0);
statusUpdater.maintain();
reporter.maintain();
assertEquals(0, getNodesFailingOsUpgrade());
for (var version : List.of(Version.fromString("8.1"), Version.fromString("8.2"))) {
tester.controller().upgradeOsIn(cloud, version, false);
osUpgrader.maintain();
statusUpdater.maintain();
reporter.maintain();
assertEquals(0, getNodesFailingOsUpgrade());
tester.clock().advance(Duration.ofMinutes(30));
statusUpdater.maintain();
reporter.maintain();
assertEquals(0, getNodesFailingOsUpgrade());
tester.configServer().setOsVersion(SystemApplication.tenantHost.id(), zone.getId(), version, 2);
tester.clock().advance(Duration.ofMinutes(30 * 3 /* time allowance * node count */).plus(Duration.ofSeconds(1)));
statusUpdater.maintain();
reporter.maintain();
assertEquals(4, getNodesFailingOsUpgrade());
tester.configServer().setOsVersion(SystemApplication.tenantHost.id(), zone.getId(), version);
tester.configServer().setOsVersion(SystemApplication.configServerHost.id(), zone.getId(), version, 2);
statusUpdater.maintain();
reporter.maintain();
assertEquals(1, getNodesFailingOsUpgrade());
tester.configServer().setOsVersion(SystemApplication.configServerHost.id(), zone.getId(), version);
statusUpdater.maintain();
reporter.maintain();
assertEquals(0, getNodesFailingOsUpgrade());
}
} | class MetricsReporterTest {
private final MetricsMock metrics = new MetricsMock();
@Test
public void test_deployment_fail_ratio() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter metricsReporter = createReporter(tester.controller());
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
Application app1 = tester.createApplication("app1", "tenant1", 1, 11L);
Application app2 = tester.createApplication("app2", "tenant1", 2, 22L);
Application app3 = tester.createApplication("app3", "tenant1", 3, 33L);
Application app4 = tester.createApplication("app4", "tenant1", 4, 44L);
tester.deployCompletely(app1, applicationPackage);
tester.deployCompletely(app2, applicationPackage);
tester.deployCompletely(app3, applicationPackage);
tester.deployCompletely(app4, applicationPackage);
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
tester.jobCompletion(component).application(app4).nextBuildNumber().uploadArtifact(applicationPackage).submit();
tester.deployAndNotify(app4.id().defaultInstance(), Optional.of(applicationPackage), false, systemTest);
metricsReporter.maintain();
assertEquals(25.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
}
@Test
public void test_deployment_average_duration() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application app = tester.createApplication("app1", "tenant1", 1, 11L);
tester.deployCompletely(app, applicationPackage);
reporter.maintain();
assertEquals(Duration.ZERO, getAverageDeploymentDuration(app.id().defaultInstance()));
tester.jobCompletion(component).application(app).nextBuildNumber().uploadArtifact(applicationPackage).submit();
tester.clock().advance(Duration.ofHours(1));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, systemTest);
tester.clock().advance(Duration.ofMinutes(30));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, stagingTest);
tester.clock().advance(Duration.ofMinutes(90));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, productionUsWest1);
reporter.maintain();
assertEquals(Duration.ofMinutes(80), getAverageDeploymentDuration(app.id().defaultInstance()));
tester.jobCompletion(component).application(app).nextBuildNumber(2).uploadArtifact(applicationPackage).submit();
tester.clock().advance(Duration.ofHours(12));
reporter.maintain();
assertEquals(Duration.ofHours(12)
.plus(Duration.ofHours(12))
.plus(Duration.ofMinutes(90))
.dividedBy(3),
getAverageDeploymentDuration(app.id().defaultInstance()));
}
@Test
public void test_deployments_failing_upgrade() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application app = tester.createApplication("app1", "tenant1", 1, 11L);
tester.deployCompletely(app, applicationPackage);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.jobCompletion(component).application(app).nextBuildNumber().uploadArtifact(applicationPackage).submit();
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, systemTest);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, systemTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, stagingTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, productionUsWest1);
assertFalse("Change deployed", tester.controller().applications().requireApplication(app.id()).change().hasTargets());
Version version = Version.fromString("7.1");
tester.upgradeSystem(version);
tester.upgrader().maintain();
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, systemTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, stagingTest);
reporter.maintain();
assertEquals(2, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, systemTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, stagingTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, productionUsWest1);
reporter.maintain();
assertEquals(1, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, productionUsWest1);
assertFalse("Upgrade deployed", tester.controller().applications().requireApplication(app.id()).change().hasTargets());
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
}
@Test
public void test_deployment_warnings_metric() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application application = tester.createApplication("app1", "tenant1", 1, 11L);
tester.configServer().generateWarnings(new DeploymentId(application.id().defaultInstance(), ZoneId.from("prod", "us-west-1")), 3);
tester.configServer().generateWarnings(new DeploymentId(application.id().defaultInstance(), ZoneId.from("prod", "us-east-3")), 4);
tester.deployCompletely(application, applicationPackage);
reporter.maintain();
assertEquals(4, getDeploymentWarnings(application.id().defaultInstance()));
}
@Test
public void test_build_time_reporting() {
InternalDeploymentTester tester = new InternalDeploymentTester();
ApplicationVersion version = tester.newSubmission();
tester.deployNewSubmission(version);
assertEquals(1000, version.buildTime().get().toEpochMilli());
MetricsReporter reporter = createReporter(tester.tester().controller());
reporter.maintain();
assertEquals(tester.clock().instant().getEpochSecond() - 1,
getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, tester.instance().id()));
}
@Test
public void test_name_service_queue_size_metric() {
DeploymentTester tester = new DeploymentTester(new ControllerTester(), false);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("default")
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application application = tester.createApplication("app1", "tenant1", 1, 11L);
reporter.maintain();
assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
tester.deployCompletely(application, applicationPackage);
reporter.maintain();
assertEquals("Deployment queues name services requests", 6, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
tester.flushDnsRequests();
reporter.maintain();
assertEquals("Queue consumed", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
}
@Test
public void test_nodes_failing_system_upgrade() {
var tester = new DeploymentTester();
var reporter = createReporter(tester.controller());
var zone1 = ZoneApiMock.fromId("prod.eu-west-1");
tester.controllerTester().zoneRegistry().setUpgradePolicy(UpgradePolicy.create().upgrade(zone1));
var systemUpgrader = new SystemUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.controllerTester().curator()));
tester.configServer().bootstrap(List.of(zone1.getId()), SystemApplication.configServer);
var version0 = Version.fromString("7.0");
tester.upgradeSystem(version0);
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
for (var version : List.of(Version.fromString("7.1"), Version.fromString("7.2"))) {
tester.upgradeController(version);
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
systemUpgrader.maintain();
tester.clock().advance(Duration.ofMinutes(30));
tester.computeVersionStatus();
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
tester.configServer().setVersion(SystemApplication.configServer.id(), zone1.getId(), version, 1);
tester.clock().advance(Duration.ofMinutes(30).plus(Duration.ofSeconds(1)));
tester.computeVersionStatus();
reporter.maintain();
assertEquals(2, getNodesFailingUpgrade());
tester.configServer().setVersion(SystemApplication.configServer.id(), zone1.getId(), version);
tester.computeVersionStatus();
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
assertEquals(version, tester.controller().systemVersion());
}
}
@Test
private Duration getAverageDeploymentDuration(ApplicationId id) {
return Duration.ofSeconds(getMetric(MetricsReporter.DEPLOYMENT_AVERAGE_DURATION, id).longValue());
}
private int getDeploymentsFailingUpgrade(ApplicationId id) {
return getMetric(MetricsReporter.DEPLOYMENT_FAILING_UPGRADES, id).intValue();
}
private int getDeploymentWarnings(ApplicationId id) {
return getMetric(MetricsReporter.DEPLOYMENT_WARNINGS, id).intValue();
}
private int getNodesFailingUpgrade() {
return metrics.getMetric(MetricsReporter.NODES_FAILING_SYSTEM_UPGRADE).intValue();
}
private int getNodesFailingOsUpgrade() {
return metrics.getMetric(MetricsReporter.NODES_FAILING_OS_UPGRADE).intValue();
}
private Number getMetric(String name, ApplicationId id) {
return metrics.getMetric((dimensions) -> id.tenant().value().equals(dimensions.get("tenant")) &&
appDimension(id).equals(dimensions.get("app")),
name)
.orElseThrow(() -> new RuntimeException("Expected metric to exist for " + id));
}
private MetricsReporter createReporter(Controller controller) {
return new MetricsReporter(controller, metrics, new JobControl(new MockCuratorDb()));
}
private static String appDimension(ApplicationId id) {
return id.application().value() + "." + id.instance().value();
}
} | class MetricsReporterTest {
private final MetricsMock metrics = new MetricsMock();
@Test
public void test_deployment_fail_ratio() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter metricsReporter = createReporter(tester.controller());
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
Application app1 = tester.createApplication("app1", "tenant1", 1, 11L);
Application app2 = tester.createApplication("app2", "tenant1", 2, 22L);
Application app3 = tester.createApplication("app3", "tenant1", 3, 33L);
Application app4 = tester.createApplication("app4", "tenant1", 4, 44L);
tester.deployCompletely(app1, applicationPackage);
tester.deployCompletely(app2, applicationPackage);
tester.deployCompletely(app3, applicationPackage);
tester.deployCompletely(app4, applicationPackage);
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
tester.jobCompletion(component).application(app4).nextBuildNumber().uploadArtifact(applicationPackage).submit();
tester.deployAndNotify(app4.id().defaultInstance(), Optional.of(applicationPackage), false, systemTest);
metricsReporter.maintain();
assertEquals(25.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
}
@Test
public void test_deployment_average_duration() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application app = tester.createApplication("app1", "tenant1", 1, 11L);
tester.deployCompletely(app, applicationPackage);
reporter.maintain();
assertEquals(Duration.ZERO, getAverageDeploymentDuration(app.id().defaultInstance()));
tester.jobCompletion(component).application(app).nextBuildNumber().uploadArtifact(applicationPackage).submit();
tester.clock().advance(Duration.ofHours(1));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, systemTest);
tester.clock().advance(Duration.ofMinutes(30));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, stagingTest);
tester.clock().advance(Duration.ofMinutes(90));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, productionUsWest1);
reporter.maintain();
assertEquals(Duration.ofMinutes(80), getAverageDeploymentDuration(app.id().defaultInstance()));
tester.jobCompletion(component).application(app).nextBuildNumber(2).uploadArtifact(applicationPackage).submit();
tester.clock().advance(Duration.ofHours(12));
reporter.maintain();
assertEquals(Duration.ofHours(12)
.plus(Duration.ofHours(12))
.plus(Duration.ofMinutes(90))
.dividedBy(3),
getAverageDeploymentDuration(app.id().defaultInstance()));
}
@Test
public void test_deployments_failing_upgrade() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application app = tester.createApplication("app1", "tenant1", 1, 11L);
tester.deployCompletely(app, applicationPackage);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.jobCompletion(component).application(app).nextBuildNumber().uploadArtifact(applicationPackage).submit();
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, systemTest);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, systemTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, stagingTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, productionUsWest1);
assertFalse("Change deployed", tester.controller().applications().requireApplication(app.id()).change().hasTargets());
Version version = Version.fromString("7.1");
tester.upgradeSystem(version);
tester.upgrader().maintain();
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, systemTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, stagingTest);
reporter.maintain();
assertEquals(2, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, systemTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, stagingTest);
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), false, productionUsWest1);
reporter.maintain();
assertEquals(1, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
tester.deployAndNotify(app.id().defaultInstance(), Optional.of(applicationPackage), true, productionUsWest1);
assertFalse("Upgrade deployed", tester.controller().applications().requireApplication(app.id()).change().hasTargets());
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(app.id().defaultInstance()));
}
@Test
public void test_deployment_warnings_metric() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application application = tester.createApplication("app1", "tenant1", 1, 11L);
tester.configServer().generateWarnings(new DeploymentId(application.id().defaultInstance(), ZoneId.from("prod", "us-west-1")), 3);
tester.configServer().generateWarnings(new DeploymentId(application.id().defaultInstance(), ZoneId.from("prod", "us-east-3")), 4);
tester.deployCompletely(application, applicationPackage);
reporter.maintain();
assertEquals(4, getDeploymentWarnings(application.id().defaultInstance()));
}
@Test
public void test_build_time_reporting() {
InternalDeploymentTester tester = new InternalDeploymentTester();
ApplicationVersion version = tester.newSubmission();
tester.deployNewSubmission(version);
assertEquals(1000, version.buildTime().get().toEpochMilli());
MetricsReporter reporter = createReporter(tester.tester().controller());
reporter.maintain();
assertEquals(tester.clock().instant().getEpochSecond() - 1,
getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, tester.instance().id()));
}
@Test
public void test_name_service_queue_size_metric() {
DeploymentTester tester = new DeploymentTester(new ControllerTester(), false);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("default")
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
Application application = tester.createApplication("app1", "tenant1", 1, 11L);
reporter.maintain();
assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
tester.deployCompletely(application, applicationPackage);
reporter.maintain();
assertEquals("Deployment queues name services requests", 6, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
tester.flushDnsRequests();
reporter.maintain();
assertEquals("Queue consumed", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
}
@Test
public void test_nodes_failing_system_upgrade() {
var tester = new DeploymentTester();
var reporter = createReporter(tester.controller());
var zone1 = ZoneApiMock.fromId("prod.eu-west-1");
tester.controllerTester().zoneRegistry().setUpgradePolicy(UpgradePolicy.create().upgrade(zone1));
var systemUpgrader = new SystemUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.controllerTester().curator()));
tester.configServer().bootstrap(List.of(zone1.getId()), SystemApplication.configServer);
var version0 = Version.fromString("7.0");
tester.upgradeSystem(version0);
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
for (var version : List.of(Version.fromString("7.1"), Version.fromString("7.2"))) {
tester.upgradeController(version);
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
systemUpgrader.maintain();
tester.clock().advance(Duration.ofMinutes(30));
tester.computeVersionStatus();
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
tester.configServer().setVersion(SystemApplication.configServer.id(), zone1.getId(), version, 1);
tester.clock().advance(Duration.ofMinutes(30).plus(Duration.ofSeconds(1)));
tester.computeVersionStatus();
reporter.maintain();
assertEquals(2, getNodesFailingUpgrade());
tester.configServer().setVersion(SystemApplication.configServer.id(), zone1.getId(), version);
tester.computeVersionStatus();
reporter.maintain();
assertEquals(0, getNodesFailingUpgrade());
assertEquals(version, tester.controller().systemVersion());
}
}
@Test
private Duration getAverageDeploymentDuration(ApplicationId id) {
return Duration.ofSeconds(getMetric(MetricsReporter.DEPLOYMENT_AVERAGE_DURATION, id).longValue());
}
private int getDeploymentsFailingUpgrade(ApplicationId id) {
return getMetric(MetricsReporter.DEPLOYMENT_FAILING_UPGRADES, id).intValue();
}
private int getDeploymentWarnings(ApplicationId id) {
return getMetric(MetricsReporter.DEPLOYMENT_WARNINGS, id).intValue();
}
private int getNodesFailingUpgrade() {
return metrics.getMetric(MetricsReporter.NODES_FAILING_SYSTEM_UPGRADE).intValue();
}
private int getNodesFailingOsUpgrade() {
return metrics.getMetric(MetricsReporter.NODES_FAILING_OS_UPGRADE).intValue();
}
private Number getMetric(String name, ApplicationId id) {
return metrics.getMetric((dimensions) -> id.tenant().value().equals(dimensions.get("tenant")) &&
appDimension(id).equals(dimensions.get("app")),
name)
.orElseThrow(() -> new RuntimeException("Expected metric to exist for " + id));
}
private MetricsReporter createReporter(Controller controller) {
return new MetricsReporter(controller, metrics, new JobControl(new MockCuratorDb()));
}
private static String appDimension(ApplicationId id) {
return id.application().value() + "." + id.instance().value();
}
} |
Missing indentation | public static ControllerHttpClient withKeyAndCertificate(URI endpoint, Path privateKeyFile, Path certificateFile) {
var privateKey = unchecked(() -> KeyUtils.fromPemEncodedPrivateKey(Files.readString(privateKeyFile, UTF_8)));
var certificates = unchecked(() -> X509CertificateUtils.certificateListFromPem(Files.readString(certificateFile, UTF_8)));
for (var certificate : certificates)
if ( Instant.now().isBefore(certificate.getNotBefore().toInstant())
|| Instant.now().isAfter(certificate.getNotAfter().toInstant()))
throw new IllegalStateException("Certificate at '" + certificateFile + "' is valid between " +
certificate.getNotBefore() + " and " + certificate.getNotAfter() + " — not now.");
return new MutualTlsControllerHttpClient(endpoint, privateKey, certificates);
} | if ( Instant.now().isBefore(certificate.getNotBefore().toInstant()) | public static ControllerHttpClient withKeyAndCertificate(URI endpoint, Path privateKeyFile, Path certificateFile) {
var privateKey = unchecked(() -> KeyUtils.fromPemEncodedPrivateKey(Files.readString(privateKeyFile, UTF_8)));
var certificates = unchecked(() -> X509CertificateUtils.certificateListFromPem(Files.readString(certificateFile, UTF_8)));
for (var certificate : certificates)
if ( Instant.now().isBefore(certificate.getNotBefore().toInstant())
|| Instant.now().isAfter(certificate.getNotAfter().toInstant()))
throw new IllegalStateException("Certificate at '" + certificateFile + "' is valid between " +
certificate.getNotBefore() + " and " + certificate.getNotAfter() + " — not now.");
return new MutualTlsControllerHttpClient(endpoint, privateKey, certificates);
} | class ControllerHttpClient {
private final HttpClient client;
private final URI endpoint;
/** Creates an HTTP client against the given endpoint, using the given HTTP client builder to create a client. */
protected ControllerHttpClient(URI endpoint, HttpClient.Builder client) {
this.endpoint = endpoint.resolve("/");
this.client = client.connectTimeout(Duration.ofSeconds(5))
.version(HttpClient.Version.HTTP_1_1)
.build();
}
/** Creates an HTTP client against the given endpoint, which uses the given key to authenticate as the given application. */
public static ControllerHttpClient withSignatureKey(URI endpoint, String privateKey, ApplicationId id) {
return new SigningControllerHttpClient(endpoint, privateKey, id);
}
/** Creates an HTTP client against the given endpoint, which uses the given key to authenticate as the given application. */
public static ControllerHttpClient withSignatureKey(URI endpoint, Path privateKeyFile, ApplicationId id) {
return new SigningControllerHttpClient(endpoint, privateKeyFile, id);
}
/** Creates an HTTP client against the given endpoint, which uses the given private key and certificate identity. */
/** Sends the given submission to the remote controller and returns the version of the accepted package, or throws if this fails. */
public String submit(Submission submission, TenantName tenant, ApplicationName application) {
return toMessage(send(request(HttpRequest.newBuilder(applicationPath(tenant, application).resolve("submit"))
.timeout(Duration.ofMinutes(30)),
POST,
new MultiPartStreamer().addJson("submitOptions", metaToJson(submission))
.addFile("applicationZip", submission.applicationZip())
.addFile("applicationTestZip", submission.applicationTestZip()))));
}
/** Sends the given deployment to the given application in the given zone, or throws if this fails. */
public DeploymentResult deploy(Deployment deployment, ApplicationId id, ZoneId zone) {
return toDeploymentResult(send(request(HttpRequest.newBuilder(deploymentJobPath(id, zone))
.timeout(Duration.ofMinutes(20)),
POST,
toDataStream(deployment))));
}
/** Deactivates the deployment of the given application in the given zone. */
public String deactivate(ApplicationId id, ZoneId zone) {
return toMessage(send(request(HttpRequest.newBuilder(deploymentPath(id, zone))
.timeout(Duration.ofMinutes(3)),
DELETE)));
}
/** Returns the default {@link ZoneId} for the given environment, if any. */
public ZoneId defaultZone(Environment environment) {
Inspector rootObject = toInspector(send(request(HttpRequest.newBuilder(defaultRegionPath(environment))
.timeout(Duration.ofSeconds(10)),
GET)));
return ZoneId.from("dev", rootObject.field("name").asString());
}
/** Returns the Vespa version to compile against, for a hosted Vespa application. This is its lowest runtime version. */
public String compileVersion(ApplicationId id) {
return toInspector(send(request(HttpRequest.newBuilder(applicationPath(id.tenant(), id.application()))
.timeout(Duration.ofSeconds(10)),
GET)))
.field("compileVersion").asString();
}
/** Returns the test config for functional and verification tests of the indicated Vespa deployment. */
public TestConfig testConfig(ApplicationId id, ZoneId zone) {
return TestConfig.fromJson(send(request(HttpRequest.newBuilder(testConfigPath(id, zone))
.timeout(Duration.ofSeconds(10)),
GET)).body());
}
/** Returns the sorted list of log entries after the given after from the deployment job of the given ids. */
public DeploymentLog deploymentLog(ApplicationId id, ZoneId zone, long run, long after) {
return toDeploymentLog(send(request(HttpRequest.newBuilder(runPath(id, zone, run, after))
.timeout(Duration.ofSeconds(10)),
GET)));
}
/** Returns the sorted list of log entries from the deployment job of the given ids. */
public DeploymentLog deploymentLog(ApplicationId id, ZoneId zone, long run) {
return deploymentLog(id, zone, run, -1);
}
/** Returns an authenticated request from the given input. Override this for, e.g., request signing. */
protected HttpRequest request(HttpRequest.Builder request, Method method, Supplier<InputStream> data) {
return request.method(method.name(), ofInputStream(data)).build();
}
private HttpRequest request(HttpRequest.Builder request, Method method) {
return request(request, method, InputStream::nullInputStream);
}
private HttpRequest request(HttpRequest.Builder request, Method method, byte[] data) {
return request(request, method, () -> new ByteArrayInputStream(data));
}
private HttpRequest request(HttpRequest.Builder request, Method method, MultiPartStreamer data) {
return request(request.setHeader("Content-Type", data.contentType()), method, data::data);
}
private URI applicationApiPath() {
return concatenated(endpoint, "application", "v4");
}
private URI tenantPath(TenantName tenant) {
return concatenated(applicationApiPath(), "tenant", tenant.value());
}
private URI applicationPath(TenantName tenant, ApplicationName application) {
return concatenated(tenantPath(tenant), "application", application.value());
}
private URI instancePath(ApplicationId id) {
return concatenated(applicationPath(id.tenant(), id.application()), "instance", id.instance().value());
}
private URI deploymentPath(ApplicationId id, ZoneId zone) {
return concatenated(instancePath(id),
"environment", zone.environment().value(),
"region", zone.region().value());
}
private URI deploymentJobPath(ApplicationId id, ZoneId zone) {
return concatenated(instancePath(id),
"deploy", jobNameOf(zone));
}
private URI jobPath(ApplicationId id, ZoneId zone) {
return concatenated(instancePath(id), "job", jobNameOf(zone));
}
private URI testConfigPath(ApplicationId id, ZoneId zone) {
return concatenated(jobPath(id, zone), "test-config");
}
private URI runPath(ApplicationId id, ZoneId zone, long run, long after) {
return withQuery(concatenated(jobPath(id, zone),
"run", Long.toString(run)),
"after", Long.toString(after));
}
private URI defaultRegionPath(Environment environment) {
return concatenated(endpoint, "zone", "v1", "environment", environment.value(), "default");
}
private static URI concatenated(URI base, String... parts) {
return base.resolve(Stream.of(parts).map(part -> URLEncoder.encode(part, UTF_8)).collect(joining("/")) + "/");
}
private static URI withQuery(URI base, String name, String value) {
return base.resolve( "?" + (base.getRawQuery() != null ? base.getRawQuery() + "&" : "")
+ URLEncoder.encode(name, UTF_8) + "=" + URLEncoder.encode(value, UTF_8));
}
private static String jobNameOf(ZoneId zone) {
return zone.environment().value() + "-" + zone.region().value();
}
/** Returns a response with a 2XX status code, with up to 10 attempts, or throws. */
private HttpResponse<byte[]> send(HttpRequest request) {
UncheckedIOException thrown = null;
for (int attempt = 1; attempt <= 10; attempt++) {
try {
HttpResponse<byte[]> response = client.send(request, ofByteArray());
if (response.statusCode() / 100 == 2)
return response;
Inspector rootObject = toSlime(response.body()).get();
String message = response.request() + " returned code " + response.statusCode() +
(rootObject.field("error-code").valid() ? " (" + rootObject.field("error-code").asString() + ")" : "") +
": " + rootObject.field("message").asString();
if (response.statusCode() / 100 == 4)
throw new IllegalArgumentException(message);
throw new IOException(message);
}
catch (IOException e) {
if (thrown == null)
thrown = new UncheckedIOException(e);
else
thrown.addSuppressed(e);
if (attempt < 10)
try {
Thread.sleep(100 << attempt);
}
catch (InterruptedException f) {
throw new RuntimeException(f);
}
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
throw thrown;
}
private static <T> T unchecked(Callable<T> callable) {
try {
return callable.call();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/** Returns a JSON representation of the deployment meta data. */
private static String metaToJson(Deployment deployment) {
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
deployment.version().ifPresent(version -> rootObject.setString("vespaVersion", version));
rootObject.setBool("deployDirectly", true);
return toJson(slime);
}
/** Returns a JSON representation of the submission meta data. */
private static String metaToJson(Submission submission) {
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("repository", submission.repository());
rootObject.setString("branch", submission.branch());
rootObject.setString("commit", submission.commit());
rootObject.setString("authorEmail", submission.authorEmail());
submission.projectId().ifPresent(projectId -> rootObject.setLong("projectId", projectId));
return toJson(slime);
}
/** Returns a multi part data stream with meta data and, if contained in the deployment, an application package. */
private static MultiPartStreamer toDataStream(Deployment deployment) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", metaToJson(deployment));
streamer.addFile("applicationZip", deployment.applicationZip());
return streamer;
}
/** Returns the response body as a String, or throws if the status code is non-2XX. */
private static String asString(HttpResponse<byte[]> response) {
return new String(response.body(), UTF_8);
}
/** Returns an {@link Inspector} for the assumed JSON formatted response. */
private static Inspector toInspector(HttpResponse<byte[]> response) {
return toSlime(response.body()).get();
}
/** Returns the "message" element contained in the JSON formatted response. */
private static String toMessage(HttpResponse<byte[]> response) {
return toInspector(response).field("message").asString();
}
private static DeploymentResult toDeploymentResult(HttpResponse<byte[]> response) {
Inspector rootObject = toInspector(response);
return new DeploymentResult(rootObject.field("message").asString(),
rootObject.field("run").asLong());
}
private static DeploymentLog toDeploymentLog(HttpResponse<byte[]> response) {
Inspector rootObject = toInspector(response);
List<DeploymentLog.Entry> entries = new ArrayList<>();
rootObject.field("log").traverse((ObjectTraverser) (step, entryArray) ->
entryArray.traverse((ArrayTraverser) (___, entryObject) -> {
entries.add(new DeploymentLog.Entry(Instant.ofEpochMilli(entryObject.field("at").asLong()),
DeploymentLog.Level.of(entryObject.field("type").asString()),
entryObject.field("message").asString(),
"copyVespaLogs".equals(step)));
}));
return new DeploymentLog(entries,
rootObject.field("active").asBool(),
valueOf(rootObject.field("status").asString()),
rootObject.field("lastId").valid() ? OptionalLong.of(rootObject.field("lastId").asLong())
: OptionalLong.empty());
}
private static Slime toSlime(byte[] data) {
return new JsonDecoder().decode(new Slime(), data);
}
private static String toJson(Slime slime) {
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
new JsonFormat(true).encode(buffer, slime);
return buffer.toString(UTF_8);
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** Client that signs requests with a private key whose public part is assigned to an application in the remote controller. */
private static class SigningControllerHttpClient extends ControllerHttpClient {
private final RequestSigner signer;
private SigningControllerHttpClient(URI endpoint, String privateKey, ApplicationId id) {
super(endpoint, HttpClient.newBuilder());
this.signer = new RequestSigner(privateKey, id.serializedForm());
}
private SigningControllerHttpClient(URI endpoint, Path privateKeyFile, ApplicationId id) {
this(endpoint, unchecked(() -> Files.readString(privateKeyFile, UTF_8)), id);
}
@Override
protected HttpRequest request(HttpRequest.Builder request, Method method, Supplier<InputStream> data) {
return signer.signed(request, method, data);
}
}
/** Client that uses a given key / certificate identity to authenticate to the remote controller. */
private static class MutualTlsControllerHttpClient extends ControllerHttpClient {
private MutualTlsControllerHttpClient(URI endpoint, PrivateKey privateKey, List<X509Certificate> certs) {
super(endpoint,
HttpClient.newBuilder()
.sslContext(new SslContextBuilder().withKeyStore(privateKey, certs).build()));
}
}
private static DeploymentLog.Status valueOf(String status) {
switch (status) {
case "running": return DeploymentLog.Status.running;
case "aborted": return DeploymentLog.Status.aborted;
case "error": return DeploymentLog.Status.error;
case "testFailure": return DeploymentLog.Status.testFailure;
case "outOfCapacity": return DeploymentLog.Status.outOfCapacity;
case "installationFailed": return DeploymentLog.Status.installationFailed;
case "deploymentFailed": return DeploymentLog.Status.deploymentFailed;
case "success": return DeploymentLog.Status.success;
default: throw new IllegalArgumentException("Unexpected status '" + status + "'");
}
}
} | class ControllerHttpClient {
private final HttpClient client;
private final URI endpoint;
/** Creates an HTTP client against the given endpoint, using the given HTTP client builder to create a client. */
protected ControllerHttpClient(URI endpoint, HttpClient.Builder client) {
this.endpoint = endpoint.resolve("/");
this.client = client.connectTimeout(Duration.ofSeconds(5))
.version(HttpClient.Version.HTTP_1_1)
.build();
}
/** Creates an HTTP client against the given endpoint, which uses the given key to authenticate as the given application. */
public static ControllerHttpClient withSignatureKey(URI endpoint, String privateKey, ApplicationId id) {
return new SigningControllerHttpClient(endpoint, privateKey, id);
}
/** Creates an HTTP client against the given endpoint, which uses the given key to authenticate as the given application. */
public static ControllerHttpClient withSignatureKey(URI endpoint, Path privateKeyFile, ApplicationId id) {
return new SigningControllerHttpClient(endpoint, privateKeyFile, id);
}
/** Creates an HTTP client against the given endpoint, which uses the given private key and certificate identity. */
/** Sends the given submission to the remote controller and returns the version of the accepted package, or throws if this fails. */
public String submit(Submission submission, TenantName tenant, ApplicationName application) {
return toMessage(send(request(HttpRequest.newBuilder(applicationPath(tenant, application).resolve("submit"))
.timeout(Duration.ofMinutes(30)),
POST,
new MultiPartStreamer().addJson("submitOptions", metaToJson(submission))
.addFile("applicationZip", submission.applicationZip())
.addFile("applicationTestZip", submission.applicationTestZip()))));
}
/** Sends the given deployment to the given application in the given zone, or throws if this fails. */
public DeploymentResult deploy(Deployment deployment, ApplicationId id, ZoneId zone) {
return toDeploymentResult(send(request(HttpRequest.newBuilder(deploymentJobPath(id, zone))
.timeout(Duration.ofMinutes(20)),
POST,
toDataStream(deployment))));
}
/** Deactivates the deployment of the given application in the given zone. */
public String deactivate(ApplicationId id, ZoneId zone) {
return toMessage(send(request(HttpRequest.newBuilder(deploymentPath(id, zone))
.timeout(Duration.ofMinutes(3)),
DELETE)));
}
/** Returns the default {@link ZoneId} for the given environment, if any. */
public ZoneId defaultZone(Environment environment) {
Inspector rootObject = toInspector(send(request(HttpRequest.newBuilder(defaultRegionPath(environment))
.timeout(Duration.ofSeconds(10)),
GET)));
return ZoneId.from("dev", rootObject.field("name").asString());
}
/** Returns the Vespa version to compile against, for a hosted Vespa application. This is its lowest runtime version. */
public String compileVersion(ApplicationId id) {
return toInspector(send(request(HttpRequest.newBuilder(applicationPath(id.tenant(), id.application()))
.timeout(Duration.ofSeconds(10)),
GET)))
.field("compileVersion").asString();
}
/** Returns the test config for functional and verification tests of the indicated Vespa deployment. */
public TestConfig testConfig(ApplicationId id, ZoneId zone) {
return TestConfig.fromJson(send(request(HttpRequest.newBuilder(testConfigPath(id, zone))
.timeout(Duration.ofSeconds(10)),
GET)).body());
}
/** Returns the sorted list of log entries after the given after from the deployment job of the given ids. */
public DeploymentLog deploymentLog(ApplicationId id, ZoneId zone, long run, long after) {
return toDeploymentLog(send(request(HttpRequest.newBuilder(runPath(id, zone, run, after))
.timeout(Duration.ofSeconds(10)),
GET)));
}
/** Returns the sorted list of log entries from the deployment job of the given ids. */
public DeploymentLog deploymentLog(ApplicationId id, ZoneId zone, long run) {
return deploymentLog(id, zone, run, -1);
}
/** Returns an authenticated request from the given input. Override this for, e.g., request signing. */
protected HttpRequest request(HttpRequest.Builder request, Method method, Supplier<InputStream> data) {
return request.method(method.name(), ofInputStream(data)).build();
}
private HttpRequest request(HttpRequest.Builder request, Method method) {
return request(request, method, InputStream::nullInputStream);
}
private HttpRequest request(HttpRequest.Builder request, Method method, byte[] data) {
return request(request, method, () -> new ByteArrayInputStream(data));
}
private HttpRequest request(HttpRequest.Builder request, Method method, MultiPartStreamer data) {
return request(request.setHeader("Content-Type", data.contentType()), method, data::data);
}
private URI applicationApiPath() {
return concatenated(endpoint, "application", "v4");
}
private URI tenantPath(TenantName tenant) {
return concatenated(applicationApiPath(), "tenant", tenant.value());
}
private URI applicationPath(TenantName tenant, ApplicationName application) {
return concatenated(tenantPath(tenant), "application", application.value());
}
private URI instancePath(ApplicationId id) {
return concatenated(applicationPath(id.tenant(), id.application()), "instance", id.instance().value());
}
private URI deploymentPath(ApplicationId id, ZoneId zone) {
return concatenated(instancePath(id),
"environment", zone.environment().value(),
"region", zone.region().value());
}
private URI deploymentJobPath(ApplicationId id, ZoneId zone) {
return concatenated(instancePath(id),
"deploy", jobNameOf(zone));
}
private URI jobPath(ApplicationId id, ZoneId zone) {
return concatenated(instancePath(id), "job", jobNameOf(zone));
}
private URI testConfigPath(ApplicationId id, ZoneId zone) {
return concatenated(jobPath(id, zone), "test-config");
}
private URI runPath(ApplicationId id, ZoneId zone, long run, long after) {
return withQuery(concatenated(jobPath(id, zone),
"run", Long.toString(run)),
"after", Long.toString(after));
}
private URI defaultRegionPath(Environment environment) {
return concatenated(endpoint, "zone", "v1", "environment", environment.value(), "default");
}
private static URI concatenated(URI base, String... parts) {
return base.resolve(Stream.of(parts).map(part -> URLEncoder.encode(part, UTF_8)).collect(joining("/")) + "/");
}
private static URI withQuery(URI base, String name, String value) {
return base.resolve( "?" + (base.getRawQuery() != null ? base.getRawQuery() + "&" : "")
+ URLEncoder.encode(name, UTF_8) + "=" + URLEncoder.encode(value, UTF_8));
}
private static String jobNameOf(ZoneId zone) {
return zone.environment().value() + "-" + zone.region().value();
}
/** Returns a response with a 2XX status code, with up to 10 attempts, or throws. */
private HttpResponse<byte[]> send(HttpRequest request) {
UncheckedIOException thrown = null;
for (int attempt = 1; attempt <= 10; attempt++) {
try {
HttpResponse<byte[]> response = client.send(request, ofByteArray());
if (response.statusCode() / 100 == 2)
return response;
Inspector rootObject = toSlime(response.body()).get();
String message = response.request() + " returned code " + response.statusCode() +
(rootObject.field("error-code").valid() ? " (" + rootObject.field("error-code").asString() + ")" : "") +
": " + rootObject.field("message").asString();
if (response.statusCode() / 100 == 4)
throw new IllegalArgumentException(message);
throw new IOException(message);
}
catch (IOException e) {
if (thrown == null)
thrown = new UncheckedIOException(e);
else
thrown.addSuppressed(e);
if (attempt < 10)
try {
Thread.sleep(100 << attempt);
}
catch (InterruptedException f) {
throw new RuntimeException(f);
}
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
throw thrown;
}
private static <T> T unchecked(Callable<T> callable) {
try {
return callable.call();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/** Returns a JSON representation of the deployment meta data. */
private static String metaToJson(Deployment deployment) {
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
deployment.version().ifPresent(version -> rootObject.setString("vespaVersion", version));
rootObject.setBool("deployDirectly", true);
return toJson(slime);
}
/** Returns a JSON representation of the submission meta data. */
private static String metaToJson(Submission submission) {
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("repository", submission.repository());
rootObject.setString("branch", submission.branch());
rootObject.setString("commit", submission.commit());
rootObject.setString("authorEmail", submission.authorEmail());
submission.projectId().ifPresent(projectId -> rootObject.setLong("projectId", projectId));
return toJson(slime);
}
/** Returns a multi part data stream with meta data and, if contained in the deployment, an application package. */
private static MultiPartStreamer toDataStream(Deployment deployment) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", metaToJson(deployment));
streamer.addFile("applicationZip", deployment.applicationZip());
return streamer;
}
/** Returns the response body as a String, or throws if the status code is non-2XX. */
private static String asString(HttpResponse<byte[]> response) {
return new String(response.body(), UTF_8);
}
/** Returns an {@link Inspector} for the assumed JSON formatted response. */
private static Inspector toInspector(HttpResponse<byte[]> response) {
return toSlime(response.body()).get();
}
/** Returns the "message" element contained in the JSON formatted response. */
private static String toMessage(HttpResponse<byte[]> response) {
return toInspector(response).field("message").asString();
}
private static DeploymentResult toDeploymentResult(HttpResponse<byte[]> response) {
Inspector rootObject = toInspector(response);
return new DeploymentResult(rootObject.field("message").asString(),
rootObject.field("run").asLong());
}
private static DeploymentLog toDeploymentLog(HttpResponse<byte[]> response) {
Inspector rootObject = toInspector(response);
List<DeploymentLog.Entry> entries = new ArrayList<>();
rootObject.field("log").traverse((ObjectTraverser) (step, entryArray) ->
entryArray.traverse((ArrayTraverser) (___, entryObject) -> {
entries.add(new DeploymentLog.Entry(Instant.ofEpochMilli(entryObject.field("at").asLong()),
DeploymentLog.Level.of(entryObject.field("type").asString()),
entryObject.field("message").asString(),
"copyVespaLogs".equals(step)));
}));
return new DeploymentLog(entries,
rootObject.field("active").asBool(),
valueOf(rootObject.field("status").asString()),
rootObject.field("lastId").valid() ? OptionalLong.of(rootObject.field("lastId").asLong())
: OptionalLong.empty());
}
private static Slime toSlime(byte[] data) {
return new JsonDecoder().decode(new Slime(), data);
}
private static String toJson(Slime slime) {
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
new JsonFormat(true).encode(buffer, slime);
return buffer.toString(UTF_8);
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** Client that signs requests with a private key whose public part is assigned to an application in the remote controller. */
private static class SigningControllerHttpClient extends ControllerHttpClient {
private final RequestSigner signer;
private SigningControllerHttpClient(URI endpoint, String privateKey, ApplicationId id) {
super(endpoint, HttpClient.newBuilder());
this.signer = new RequestSigner(privateKey, id.serializedForm());
}
private SigningControllerHttpClient(URI endpoint, Path privateKeyFile, ApplicationId id) {
this(endpoint, unchecked(() -> Files.readString(privateKeyFile, UTF_8)), id);
}
@Override
protected HttpRequest request(HttpRequest.Builder request, Method method, Supplier<InputStream> data) {
return signer.signed(request, method, data);
}
}
/** Client that uses a given key / certificate identity to authenticate to the remote controller. */
private static class MutualTlsControllerHttpClient extends ControllerHttpClient {
private MutualTlsControllerHttpClient(URI endpoint, PrivateKey privateKey, List<X509Certificate> certs) {
super(endpoint,
HttpClient.newBuilder()
.sslContext(new SslContextBuilder().withKeyStore(privateKey, certs).build()));
}
}
private static DeploymentLog.Status valueOf(String status) {
switch (status) {
case "running": return DeploymentLog.Status.running;
case "aborted": return DeploymentLog.Status.aborted;
case "error": return DeploymentLog.Status.error;
case "testFailure": return DeploymentLog.Status.testFailure;
case "outOfCapacity": return DeploymentLog.Status.outOfCapacity;
case "installationFailed": return DeploymentLog.Status.installationFailed;
case "deploymentFailed": return DeploymentLog.Status.deploymentFailed;
case "success": return DeploymentLog.Status.success;
default: throw new IllegalArgumentException("Unexpected status '" + status + "'");
}
}
} |
It should not be necessary to set the same value as the default in the def file. We should instead avoid setting the wrong values at higher levels in the model. The handling of `getMemoryPercentage` in `ContainerCluster.getConfig(QrStartConfig)` should be moved to the `ApplicationContainerCluster` class. Only those clusters are created by `ContainerModelBuilder`, and that's the only place where we set `memoryPercentage`. `ContainerCluster.set/getMemoryPercentage` should also be moved to `ApplicationContainerCluster`. | public void getConfig(QrStartConfig.Builder builder) {
builder.jvm.heapsize(512);
builder.jvm.heapSizeAsPercentageOfPhysicalMemory(0);
builder.jvm.availableProcessors(2);
builder.jvm.verbosegc(false);
} | builder.jvm.heapSizeAsPercentageOfPhysicalMemory(0); | public void getConfig(QrStartConfig.Builder builder) {
builder.jvm
.verbosegc(false)
.availableProcessors(2)
.heapsize(512)
.heapSizeAsPercentageOfPhysicalMemory(0);
} | class ClusterControllerContainer extends Container implements
BundlesConfig.Producer,
ZookeeperServerConfig.Producer,
QrStartConfig.Producer
{
private static final ComponentSpecification CLUSTERCONTROLLER_BUNDLE = new ComponentSpecification("clustercontroller-apps");
private static final ComponentSpecification ZKFACADE_BUNDLE = new ComponentSpecification("zkfacade");
private final Set<String> bundles = new TreeSet<>();
public ClusterControllerContainer(AbstractConfigProducer parent, int index, boolean runStandaloneZooKeeper, boolean isHosted) {
super(parent, "" + index, index);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-status"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StatusHandler"),
CLUSTERCONTROLLER_BUNDLE))), "clustercontroller-status/*"
);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-state-restapi-v2"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StateRestApiV2Handler"),
CLUSTERCONTROLLER_BUNDLE))), "cluster/v2/*"
);
if (runStandaloneZooKeeper) {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkrunner"),
new ComponentSpecification("com.yahoo.vespa.zookeeper.ZooKeeperServer"), ZKFACADE_BUNDLE))));
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StandaloneZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
} else {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.DummyZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
}
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apps-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apputil-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-core-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-utils-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/zkfacade-jar-with-dependencies.jar"));
log.log(LogLevel.DEBUG, "Adding access log for cluster controller ...");
addComponent(new AccessLogComponent(AccessLogComponent.AccessLogType.jsonAccessLog, "controller", isHosted));
}
@Override
public int getWantedPort() {
return 19050;
}
@Override
public boolean requiresWantedPort() {
return index() == 0;
}
@Override
public ContainerServiceType myServiceType() {
return ContainerServiceType.CLUSTERCONTROLLER_CONTAINER;
}
private void addHandler(Handler h, String binding) {
h.addServerBindings("http:
super.addHandler(h);
}
public void addBundle(String bundlePath) {
bundles.add(bundlePath);
}
@Override
public void getConfig(BundlesConfig.Builder builder) {
for (String bundle : bundles) {
builder.bundle(bundle);
}
}
@Override
public void getConfig(ZookeeperServerConfig.Builder builder) {
builder.myid(index());
}
@Override
} | class ClusterControllerContainer extends Container implements
BundlesConfig.Producer,
ZookeeperServerConfig.Producer,
QrStartConfig.Producer
{
private static final ComponentSpecification CLUSTERCONTROLLER_BUNDLE = new ComponentSpecification("clustercontroller-apps");
private static final ComponentSpecification ZKFACADE_BUNDLE = new ComponentSpecification("zkfacade");
private final Set<String> bundles = new TreeSet<>();
public ClusterControllerContainer(AbstractConfigProducer parent, int index, boolean runStandaloneZooKeeper, boolean isHosted) {
super(parent, "" + index, index);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-status"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StatusHandler"),
CLUSTERCONTROLLER_BUNDLE))), "clustercontroller-status/*"
);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-state-restapi-v2"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StateRestApiV2Handler"),
CLUSTERCONTROLLER_BUNDLE))), "cluster/v2/*"
);
if (runStandaloneZooKeeper) {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkrunner"),
new ComponentSpecification("com.yahoo.vespa.zookeeper.ZooKeeperServer"), ZKFACADE_BUNDLE))));
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StandaloneZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
} else {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.DummyZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
}
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apps-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apputil-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-core-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-utils-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/zkfacade-jar-with-dependencies.jar"));
log.log(LogLevel.DEBUG, "Adding access log for cluster controller ...");
addComponent(new AccessLogComponent(AccessLogComponent.AccessLogType.jsonAccessLog, "controller", isHosted));
}
@Override
public int getWantedPort() {
return 19050;
}
@Override
public boolean requiresWantedPort() {
return index() == 0;
}
@Override
public ContainerServiceType myServiceType() {
return ContainerServiceType.CLUSTERCONTROLLER_CONTAINER;
}
private void addHandler(Handler h, String binding) {
h.addServerBindings("http:
super.addHandler(h);
}
public void addBundle(String bundlePath) {
bundles.add(bundlePath);
}
@Override
public void getConfig(BundlesConfig.Builder builder) {
for (String bundle : bundles) {
builder.bundle(bundle);
}
}
@Override
public void getConfig(ZookeeperServerConfig.Builder builder) {
builder.myid(index());
}
@Override
} |
Note that the builder setters return the builder itself, so it's not necessary to repeate `builder.` for every setting. | public void getConfig(QrStartConfig.Builder builder) {
builder.jvm.heapsize(512);
builder.jvm.heapSizeAsPercentageOfPhysicalMemory(0);
builder.jvm.availableProcessors(2);
builder.jvm.verbosegc(false);
} | builder.jvm.availableProcessors(2); | public void getConfig(QrStartConfig.Builder builder) {
builder.jvm
.verbosegc(false)
.availableProcessors(2)
.heapsize(512)
.heapSizeAsPercentageOfPhysicalMemory(0);
} | class ClusterControllerContainer extends Container implements
BundlesConfig.Producer,
ZookeeperServerConfig.Producer,
QrStartConfig.Producer
{
private static final ComponentSpecification CLUSTERCONTROLLER_BUNDLE = new ComponentSpecification("clustercontroller-apps");
private static final ComponentSpecification ZKFACADE_BUNDLE = new ComponentSpecification("zkfacade");
private final Set<String> bundles = new TreeSet<>();
public ClusterControllerContainer(AbstractConfigProducer parent, int index, boolean runStandaloneZooKeeper, boolean isHosted) {
super(parent, "" + index, index);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-status"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StatusHandler"),
CLUSTERCONTROLLER_BUNDLE))), "clustercontroller-status/*"
);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-state-restapi-v2"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StateRestApiV2Handler"),
CLUSTERCONTROLLER_BUNDLE))), "cluster/v2/*"
);
if (runStandaloneZooKeeper) {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkrunner"),
new ComponentSpecification("com.yahoo.vespa.zookeeper.ZooKeeperServer"), ZKFACADE_BUNDLE))));
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StandaloneZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
} else {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.DummyZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
}
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apps-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apputil-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-core-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-utils-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/zkfacade-jar-with-dependencies.jar"));
log.log(LogLevel.DEBUG, "Adding access log for cluster controller ...");
addComponent(new AccessLogComponent(AccessLogComponent.AccessLogType.jsonAccessLog, "controller", isHosted));
}
@Override
public int getWantedPort() {
return 19050;
}
@Override
public boolean requiresWantedPort() {
return index() == 0;
}
@Override
public ContainerServiceType myServiceType() {
return ContainerServiceType.CLUSTERCONTROLLER_CONTAINER;
}
private void addHandler(Handler h, String binding) {
h.addServerBindings("http:
super.addHandler(h);
}
public void addBundle(String bundlePath) {
bundles.add(bundlePath);
}
@Override
public void getConfig(BundlesConfig.Builder builder) {
for (String bundle : bundles) {
builder.bundle(bundle);
}
}
@Override
public void getConfig(ZookeeperServerConfig.Builder builder) {
builder.myid(index());
}
@Override
} | class ClusterControllerContainer extends Container implements
BundlesConfig.Producer,
ZookeeperServerConfig.Producer,
QrStartConfig.Producer
{
private static final ComponentSpecification CLUSTERCONTROLLER_BUNDLE = new ComponentSpecification("clustercontroller-apps");
private static final ComponentSpecification ZKFACADE_BUNDLE = new ComponentSpecification("zkfacade");
private final Set<String> bundles = new TreeSet<>();
public ClusterControllerContainer(AbstractConfigProducer parent, int index, boolean runStandaloneZooKeeper, boolean isHosted) {
super(parent, "" + index, index);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-status"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StatusHandler"),
CLUSTERCONTROLLER_BUNDLE))), "clustercontroller-status/*"
);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-state-restapi-v2"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StateRestApiV2Handler"),
CLUSTERCONTROLLER_BUNDLE))), "cluster/v2/*"
);
if (runStandaloneZooKeeper) {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkrunner"),
new ComponentSpecification("com.yahoo.vespa.zookeeper.ZooKeeperServer"), ZKFACADE_BUNDLE))));
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StandaloneZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
} else {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.DummyZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
}
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apps-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apputil-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-core-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-utils-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/zkfacade-jar-with-dependencies.jar"));
log.log(LogLevel.DEBUG, "Adding access log for cluster controller ...");
addComponent(new AccessLogComponent(AccessLogComponent.AccessLogType.jsonAccessLog, "controller", isHosted));
}
@Override
public int getWantedPort() {
return 19050;
}
@Override
public boolean requiresWantedPort() {
return index() == 0;
}
@Override
public ContainerServiceType myServiceType() {
return ContainerServiceType.CLUSTERCONTROLLER_CONTAINER;
}
private void addHandler(Handler h, String binding) {
h.addServerBindings("http:
super.addHandler(h);
}
public void addBundle(String bundlePath) {
bundles.add(bundlePath);
}
@Override
public void getConfig(BundlesConfig.Builder builder) {
for (String bundle : bundles) {
builder.bundle(bundle);
}
}
@Override
public void getConfig(ZookeeperServerConfig.Builder builder) {
builder.myid(index());
}
@Override
} |
Fixed | public void getConfig(QrStartConfig.Builder builder) {
builder.jvm.heapsize(512);
builder.jvm.heapSizeAsPercentageOfPhysicalMemory(0);
builder.jvm.availableProcessors(2);
builder.jvm.verbosegc(false);
} | builder.jvm.availableProcessors(2); | public void getConfig(QrStartConfig.Builder builder) {
builder.jvm
.verbosegc(false)
.availableProcessors(2)
.heapsize(512)
.heapSizeAsPercentageOfPhysicalMemory(0);
} | class ClusterControllerContainer extends Container implements
BundlesConfig.Producer,
ZookeeperServerConfig.Producer,
QrStartConfig.Producer
{
private static final ComponentSpecification CLUSTERCONTROLLER_BUNDLE = new ComponentSpecification("clustercontroller-apps");
private static final ComponentSpecification ZKFACADE_BUNDLE = new ComponentSpecification("zkfacade");
private final Set<String> bundles = new TreeSet<>();
public ClusterControllerContainer(AbstractConfigProducer parent, int index, boolean runStandaloneZooKeeper, boolean isHosted) {
super(parent, "" + index, index);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-status"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StatusHandler"),
CLUSTERCONTROLLER_BUNDLE))), "clustercontroller-status/*"
);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-state-restapi-v2"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StateRestApiV2Handler"),
CLUSTERCONTROLLER_BUNDLE))), "cluster/v2/*"
);
if (runStandaloneZooKeeper) {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkrunner"),
new ComponentSpecification("com.yahoo.vespa.zookeeper.ZooKeeperServer"), ZKFACADE_BUNDLE))));
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StandaloneZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
} else {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.DummyZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
}
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apps-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apputil-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-core-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-utils-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/zkfacade-jar-with-dependencies.jar"));
log.log(LogLevel.DEBUG, "Adding access log for cluster controller ...");
addComponent(new AccessLogComponent(AccessLogComponent.AccessLogType.jsonAccessLog, "controller", isHosted));
}
@Override
public int getWantedPort() {
return 19050;
}
@Override
public boolean requiresWantedPort() {
return index() == 0;
}
@Override
public ContainerServiceType myServiceType() {
return ContainerServiceType.CLUSTERCONTROLLER_CONTAINER;
}
private void addHandler(Handler h, String binding) {
h.addServerBindings("http:
super.addHandler(h);
}
public void addBundle(String bundlePath) {
bundles.add(bundlePath);
}
@Override
public void getConfig(BundlesConfig.Builder builder) {
for (String bundle : bundles) {
builder.bundle(bundle);
}
}
@Override
public void getConfig(ZookeeperServerConfig.Builder builder) {
builder.myid(index());
}
@Override
} | class ClusterControllerContainer extends Container implements
BundlesConfig.Producer,
ZookeeperServerConfig.Producer,
QrStartConfig.Producer
{
private static final ComponentSpecification CLUSTERCONTROLLER_BUNDLE = new ComponentSpecification("clustercontroller-apps");
private static final ComponentSpecification ZKFACADE_BUNDLE = new ComponentSpecification("zkfacade");
private final Set<String> bundles = new TreeSet<>();
public ClusterControllerContainer(AbstractConfigProducer parent, int index, boolean runStandaloneZooKeeper, boolean isHosted) {
super(parent, "" + index, index);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-status"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StatusHandler"),
CLUSTERCONTROLLER_BUNDLE))), "clustercontroller-status/*"
);
addHandler(
new Handler(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-state-restapi-v2"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StateRestApiV2Handler"),
CLUSTERCONTROLLER_BUNDLE))), "cluster/v2/*"
);
if (runStandaloneZooKeeper) {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkrunner"),
new ComponentSpecification("com.yahoo.vespa.zookeeper.ZooKeeperServer"), ZKFACADE_BUNDLE))));
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.StandaloneZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
} else {
addComponent(new Component<>(new ComponentModel(new BundleInstantiationSpecification(
new ComponentSpecification("clustercontroller-zkprovider"),
new ComponentSpecification("com.yahoo.vespa.clustercontroller.apps.clustercontroller.DummyZooKeeperProvider"), CLUSTERCONTROLLER_BUNDLE))));
}
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apps-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-apputil-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-core-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/clustercontroller-utils-jar-with-dependencies.jar"));
addBundle("file:" + getDefaults().underVespaHome("lib/jars/zkfacade-jar-with-dependencies.jar"));
log.log(LogLevel.DEBUG, "Adding access log for cluster controller ...");
addComponent(new AccessLogComponent(AccessLogComponent.AccessLogType.jsonAccessLog, "controller", isHosted));
}
@Override
public int getWantedPort() {
return 19050;
}
@Override
public boolean requiresWantedPort() {
return index() == 0;
}
@Override
public ContainerServiceType myServiceType() {
return ContainerServiceType.CLUSTERCONTROLLER_CONTAINER;
}
private void addHandler(Handler h, String binding) {
h.addServerBindings("http:
super.addHandler(h);
}
public void addBundle(String bundlePath) {
bundles.add(bundlePath);
}
@Override
public void getConfig(BundlesConfig.Builder builder) {
for (String bundle : bundles) {
builder.bundle(bundle);
}
}
@Override
public void getConfig(ZookeeperServerConfig.Builder builder) {
builder.myid(index());
}
@Override
} |
Is `stop` called from the same thread as `start`? | public void stop() {
registration.unregister();
registration = null;
} | registration.unregister(); | public void stop() {
registration.unregister();
registration = null;
} | class BundleCollisionHook implements CollisionHook, EventHook {
private ServiceRegistration<?> registration;
private Map<Bundle, BsnVersion> allowedDuplicates = new HashMap<>(5);
public void start(BundleContext context) {
if (registration != null) {
throw new IllegalStateException();
}
registration = context.registerService(new String[]{CollisionHook.class.getName(), EventHook.class.getName()},
this, null);
}
/**
* Adds a collection of bundles to the allowed duplicates.
*/
synchronized void allowDuplicateBundles(Collection<Bundle> bundles) {
for (var bundle : bundles) {
allowedDuplicates.put(bundle, new BsnVersion(bundle.getSymbolicName(), bundle.getVersion()));
}
}
/**
* Cleans up the allowed duplicates when a bundle is uninstalled.
*/
@Override
public void event(BundleEvent event, Collection<BundleContext> contexts) {
if (event.getType() != BundleEvent.UNINSTALLED) return;
synchronized (this) {
allowedDuplicates.remove(event.getBundle());
}
}
@Override
public synchronized void filterCollisions(int operationType, Bundle target, Collection<Bundle> collisionCandidates) {
Set<Bundle> whitelistedCandidates = new HashSet<>();
for (var bundle : collisionCandidates) {
var bsnVersion = new BsnVersion(bundle.getSymbolicName(), bundle.getVersion());
if (allowedDuplicates.containsValue(bsnVersion)) {
whitelistedCandidates.add(bundle);
}
}
collisionCandidates.removeAll(whitelistedCandidates);
}
static class BsnVersion {
private final String symbolicName;
private final Version version;
BsnVersion(String symbolicName, Version version) {
this.symbolicName = symbolicName;
this.version = version;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BsnVersion that = (BsnVersion) o;
return Objects.equals(symbolicName, that.symbolicName) &&
version.equals(that.version);
}
@Override
public int hashCode() {
return Objects.hash(symbolicName, version);
}
}
} | class BundleCollisionHook implements CollisionHook, EventHook, FindHook {
private ServiceRegistration<?> registration;
private Map<Bundle, BsnVersion> allowedDuplicates = new HashMap<>(5);
public void start(BundleContext context) {
if (registration != null) {
throw new IllegalStateException();
}
String[] serviceClasses = {CollisionHook.class.getName(), EventHook.class.getName(), FindHook.class.getName()};
registration = context.registerService(serviceClasses, this, null);
}
/**
* Adds a collection of bundles to the allowed duplicates.
*/
synchronized void allowDuplicateBundles(Collection<Bundle> bundles) {
for (var bundle : bundles) {
allowedDuplicates.put(bundle, new BsnVersion(bundle));
}
}
/**
* Cleans up the allowed duplicates when a bundle is uninstalled.
*/
@Override
public void event(BundleEvent event, Collection<BundleContext> contexts) {
if (event.getType() != BundleEvent.UNINSTALLED) return;
synchronized (this) {
allowedDuplicates.remove(event.getBundle());
}
}
/**
* Removes duplicates of the allowed duplicate bundles from the given collision candidates.
*/
@Override
public synchronized void filterCollisions(int operationType, Bundle target, Collection<Bundle> collisionCandidates) {
Set<Bundle> whitelistedCandidates = new HashSet<>();
for (var bundle : collisionCandidates) {
if (allowedDuplicates.containsValue(new BsnVersion(bundle))) {
whitelistedCandidates.add(bundle);
}
}
collisionCandidates.removeAll(whitelistedCandidates);
}
/**
* Filters out the set of bundles that should not be visible to the bundle associated with the given context.
* If the given context represents one of the allowed duplicates, this method filters out all bundles
* that are duplicates of the allowed duplicates. Otherwise this method filters out the allowed duplicates,
* so they are not visible to other bundles.
*
* NOTE: This hook method is added for a consistent view of the installed bundles, but is not actively
* used by jdisc. The OSGi framework does not use FindHooks when calculating bundle wiring.
*/
@Override
public synchronized void find(BundleContext context, Collection<Bundle> bundles) {
Set<Bundle> bundlesToHide = new HashSet<>();
if (allowedDuplicates.containsKey(context.getBundle())) {
for (var bundle : bundles) {
if (isDuplicateOfAllowedDuplicates(bundle)) {
bundlesToHide.add(bundle);
}
}
} else {
for (var bundle : bundles) {
if (allowedDuplicates.containsKey(bundle)) {
bundlesToHide.add(bundle);
}
}
}
bundles.removeAll(bundlesToHide);
}
private boolean isDuplicateOfAllowedDuplicates(Bundle bundle) {
return ! allowedDuplicates.containsKey(bundle) && allowedDuplicates.containsValue(new BsnVersion(bundle));
}
static class BsnVersion {
private final String symbolicName;
private final Version version;
BsnVersion(Bundle bundle) {
this.symbolicName = bundle.getSymbolicName();
this.version = bundle.getVersion();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BsnVersion that = (BsnVersion) o;
return Objects.equals(symbolicName, that.symbolicName) &&
version.equals(that.version);
}
@Override
public int hashCode() {
return Objects.hash(symbolicName, version);
}
}
} |
Why is that important? start/stop are only called when Felix starts and stops (container startup and shutdown), and they only use the `registration` object. This follows a pattern from other jdisc_core services like `LogHandler`. This could just as well have been done in FelixFramework start/stop, but pulling it out to the service class keeps the code tidier. | public void stop() {
registration.unregister();
registration = null;
} | registration.unregister(); | public void stop() {
registration.unregister();
registration = null;
} | class BundleCollisionHook implements CollisionHook, EventHook {
private ServiceRegistration<?> registration;
private Map<Bundle, BsnVersion> allowedDuplicates = new HashMap<>(5);
public void start(BundleContext context) {
if (registration != null) {
throw new IllegalStateException();
}
registration = context.registerService(new String[]{CollisionHook.class.getName(), EventHook.class.getName()},
this, null);
}
/**
* Adds a collection of bundles to the allowed duplicates.
*/
synchronized void allowDuplicateBundles(Collection<Bundle> bundles) {
for (var bundle : bundles) {
allowedDuplicates.put(bundle, new BsnVersion(bundle.getSymbolicName(), bundle.getVersion()));
}
}
/**
* Cleans up the allowed duplicates when a bundle is uninstalled.
*/
@Override
public void event(BundleEvent event, Collection<BundleContext> contexts) {
if (event.getType() != BundleEvent.UNINSTALLED) return;
synchronized (this) {
allowedDuplicates.remove(event.getBundle());
}
}
@Override
public synchronized void filterCollisions(int operationType, Bundle target, Collection<Bundle> collisionCandidates) {
Set<Bundle> whitelistedCandidates = new HashSet<>();
for (var bundle : collisionCandidates) {
var bsnVersion = new BsnVersion(bundle.getSymbolicName(), bundle.getVersion());
if (allowedDuplicates.containsValue(bsnVersion)) {
whitelistedCandidates.add(bundle);
}
}
collisionCandidates.removeAll(whitelistedCandidates);
}
static class BsnVersion {
private final String symbolicName;
private final Version version;
BsnVersion(String symbolicName, Version version) {
this.symbolicName = symbolicName;
this.version = version;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BsnVersion that = (BsnVersion) o;
return Objects.equals(symbolicName, that.symbolicName) &&
version.equals(that.version);
}
@Override
public int hashCode() {
return Objects.hash(symbolicName, version);
}
}
} | class BundleCollisionHook implements CollisionHook, EventHook, FindHook {
private ServiceRegistration<?> registration;
private Map<Bundle, BsnVersion> allowedDuplicates = new HashMap<>(5);
public void start(BundleContext context) {
if (registration != null) {
throw new IllegalStateException();
}
String[] serviceClasses = {CollisionHook.class.getName(), EventHook.class.getName(), FindHook.class.getName()};
registration = context.registerService(serviceClasses, this, null);
}
/**
* Adds a collection of bundles to the allowed duplicates.
*/
synchronized void allowDuplicateBundles(Collection<Bundle> bundles) {
for (var bundle : bundles) {
allowedDuplicates.put(bundle, new BsnVersion(bundle));
}
}
/**
* Cleans up the allowed duplicates when a bundle is uninstalled.
*/
@Override
public void event(BundleEvent event, Collection<BundleContext> contexts) {
if (event.getType() != BundleEvent.UNINSTALLED) return;
synchronized (this) {
allowedDuplicates.remove(event.getBundle());
}
}
/**
* Removes duplicates of the allowed duplicate bundles from the given collision candidates.
*/
@Override
public synchronized void filterCollisions(int operationType, Bundle target, Collection<Bundle> collisionCandidates) {
Set<Bundle> whitelistedCandidates = new HashSet<>();
for (var bundle : collisionCandidates) {
if (allowedDuplicates.containsValue(new BsnVersion(bundle))) {
whitelistedCandidates.add(bundle);
}
}
collisionCandidates.removeAll(whitelistedCandidates);
}
/**
* Filters out the set of bundles that should not be visible to the bundle associated with the given context.
* If the given context represents one of the allowed duplicates, this method filters out all bundles
* that are duplicates of the allowed duplicates. Otherwise this method filters out the allowed duplicates,
* so they are not visible to other bundles.
*
* NOTE: This hook method is added for a consistent view of the installed bundles, but is not actively
* used by jdisc. The OSGi framework does not use FindHooks when calculating bundle wiring.
*/
@Override
public synchronized void find(BundleContext context, Collection<Bundle> bundles) {
Set<Bundle> bundlesToHide = new HashSet<>();
if (allowedDuplicates.containsKey(context.getBundle())) {
for (var bundle : bundles) {
if (isDuplicateOfAllowedDuplicates(bundle)) {
bundlesToHide.add(bundle);
}
}
} else {
for (var bundle : bundles) {
if (allowedDuplicates.containsKey(bundle)) {
bundlesToHide.add(bundle);
}
}
}
bundles.removeAll(bundlesToHide);
}
private boolean isDuplicateOfAllowedDuplicates(Bundle bundle) {
return ! allowedDuplicates.containsKey(bundle) && allowedDuplicates.containsValue(new BsnVersion(bundle));
}
static class BsnVersion {
private final String symbolicName;
private final Version version;
BsnVersion(Bundle bundle) {
this.symbolicName = bundle.getSymbolicName();
this.version = bundle.getVersion();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BsnVersion that = (BsnVersion) o;
return Objects.equals(symbolicName, that.symbolicName) &&
version.equals(that.version);
}
@Override
public int hashCode() {
return Objects.hash(symbolicName, version);
}
}
} |
The access to the `registration` field must be synchronized if Felix may invoke `start` and `stop` from different threads. | public void stop() {
registration.unregister();
registration = null;
} | registration.unregister(); | public void stop() {
registration.unregister();
registration = null;
} | class BundleCollisionHook implements CollisionHook, EventHook {
private ServiceRegistration<?> registration;
private Map<Bundle, BsnVersion> allowedDuplicates = new HashMap<>(5);
public void start(BundleContext context) {
if (registration != null) {
throw new IllegalStateException();
}
registration = context.registerService(new String[]{CollisionHook.class.getName(), EventHook.class.getName()},
this, null);
}
/**
* Adds a collection of bundles to the allowed duplicates.
*/
synchronized void allowDuplicateBundles(Collection<Bundle> bundles) {
for (var bundle : bundles) {
allowedDuplicates.put(bundle, new BsnVersion(bundle.getSymbolicName(), bundle.getVersion()));
}
}
/**
* Cleans up the allowed duplicates when a bundle is uninstalled.
*/
@Override
public void event(BundleEvent event, Collection<BundleContext> contexts) {
if (event.getType() != BundleEvent.UNINSTALLED) return;
synchronized (this) {
allowedDuplicates.remove(event.getBundle());
}
}
@Override
public synchronized void filterCollisions(int operationType, Bundle target, Collection<Bundle> collisionCandidates) {
Set<Bundle> whitelistedCandidates = new HashSet<>();
for (var bundle : collisionCandidates) {
var bsnVersion = new BsnVersion(bundle.getSymbolicName(), bundle.getVersion());
if (allowedDuplicates.containsValue(bsnVersion)) {
whitelistedCandidates.add(bundle);
}
}
collisionCandidates.removeAll(whitelistedCandidates);
}
static class BsnVersion {
private final String symbolicName;
private final Version version;
BsnVersion(String symbolicName, Version version) {
this.symbolicName = symbolicName;
this.version = version;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BsnVersion that = (BsnVersion) o;
return Objects.equals(symbolicName, that.symbolicName) &&
version.equals(that.version);
}
@Override
public int hashCode() {
return Objects.hash(symbolicName, version);
}
}
} | class BundleCollisionHook implements CollisionHook, EventHook, FindHook {
private ServiceRegistration<?> registration;
private Map<Bundle, BsnVersion> allowedDuplicates = new HashMap<>(5);
public void start(BundleContext context) {
if (registration != null) {
throw new IllegalStateException();
}
String[] serviceClasses = {CollisionHook.class.getName(), EventHook.class.getName(), FindHook.class.getName()};
registration = context.registerService(serviceClasses, this, null);
}
/**
* Adds a collection of bundles to the allowed duplicates.
*/
synchronized void allowDuplicateBundles(Collection<Bundle> bundles) {
for (var bundle : bundles) {
allowedDuplicates.put(bundle, new BsnVersion(bundle));
}
}
/**
* Cleans up the allowed duplicates when a bundle is uninstalled.
*/
@Override
public void event(BundleEvent event, Collection<BundleContext> contexts) {
if (event.getType() != BundleEvent.UNINSTALLED) return;
synchronized (this) {
allowedDuplicates.remove(event.getBundle());
}
}
/**
* Removes duplicates of the allowed duplicate bundles from the given collision candidates.
*/
@Override
public synchronized void filterCollisions(int operationType, Bundle target, Collection<Bundle> collisionCandidates) {
Set<Bundle> whitelistedCandidates = new HashSet<>();
for (var bundle : collisionCandidates) {
if (allowedDuplicates.containsValue(new BsnVersion(bundle))) {
whitelistedCandidates.add(bundle);
}
}
collisionCandidates.removeAll(whitelistedCandidates);
}
/**
* Filters out the set of bundles that should not be visible to the bundle associated with the given context.
* If the given context represents one of the allowed duplicates, this method filters out all bundles
* that are duplicates of the allowed duplicates. Otherwise this method filters out the allowed duplicates,
* so they are not visible to other bundles.
*
* NOTE: This hook method is added for a consistent view of the installed bundles, but is not actively
* used by jdisc. The OSGi framework does not use FindHooks when calculating bundle wiring.
*/
@Override
public synchronized void find(BundleContext context, Collection<Bundle> bundles) {
Set<Bundle> bundlesToHide = new HashSet<>();
if (allowedDuplicates.containsKey(context.getBundle())) {
for (var bundle : bundles) {
if (isDuplicateOfAllowedDuplicates(bundle)) {
bundlesToHide.add(bundle);
}
}
} else {
for (var bundle : bundles) {
if (allowedDuplicates.containsKey(bundle)) {
bundlesToHide.add(bundle);
}
}
}
bundles.removeAll(bundlesToHide);
}
private boolean isDuplicateOfAllowedDuplicates(Bundle bundle) {
return ! allowedDuplicates.containsKey(bundle) && allowedDuplicates.containsValue(new BsnVersion(bundle));
}
static class BsnVersion {
private final String symbolicName;
private final Version version;
BsnVersion(Bundle bundle) {
this.symbolicName = bundle.getSymbolicName();
this.version = bundle.getVersion();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BsnVersion that = (BsnVersion) o;
return Objects.equals(symbolicName, that.symbolicName) &&
version.equals(that.version);
}
@Override
public int hashCode() {
return Objects.hash(symbolicName, version);
}
}
} |
Good catch, thanks! That thing with "ALLOCATABLE_HOST_STATES" is a bit ugly, we should separate hosts and nodes one of these days. (I don't think just active will do as that won't allow us to automatically improve balance by adding some new hosts.) | private Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.state(Node.State.active).asList()) {
for (Node toHost : allNodes.nodeType(NodeType.host).asList()) {
if (node.parentHostname().isEmpty()) continue;
if (toHost.hostname().equals(node.parentHostname().get())) continue;
if ( ! capacity.freeCapacityOf(toHost).satisfies(node.flavor().resources())) continue;
double skewReductionAtFromHost = skewReductionByRemoving(node, allNodes.parentOf(node).get(), capacity);
double skewReductionAtToHost = skewReductionByAdding(node, toHost, capacity);
double netSkewReduction = skewReductionAtFromHost + skewReductionAtToHost;
if (netSkewReduction > bestMove.netSkewReduction)
bestMove = new Move(node, netSkewReduction);
}
}
return bestMove;
} | for (Node toHost : allNodes.nodeType(NodeType.host).asList()) { | private Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.state(NodePrioritizer.ALLOCATABLE_HOST_STATES).nodeType(NodeType.host)) {
if (toHost.hostname().equals(node.parentHostname().get())) continue;
if ( ! capacity.freeCapacityOf(toHost).satisfies(node.flavor().resources())) continue;
double skewReductionAtFromHost = skewReductionByRemoving(node, allNodes.parentOf(node).get(), capacity);
double skewReductionAtToHost = skewReductionByAdding(node, toHost, capacity);
double netSkewReduction = skewReductionAtFromHost + skewReductionAtToHost;
if (netSkewReduction > bestMove.netSkewReduction)
bestMove = new Move(node, netSkewReduction);
}
}
return bestMove;
} | class Rebalancer extends Maintainer {
private final HostResourcesCalculator hostResourcesCalculator;
private final Clock clock;
public Rebalancer(NodeRepository nodeRepository, HostResourcesCalculator hostResourcesCalculator, Clock clock, Duration interval) {
super(nodeRepository, interval);
this.hostResourcesCalculator = hostResourcesCalculator;
this.clock = clock;
}
@Override
protected void maintain() {
NodeList allNodes = nodeRepository().list();
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
markWantToRetire(bestMove.node);
}
private boolean zoneIsStable(NodeList allNodes) {
List<Node> active = allNodes.state(Node.State.active).asList();
if (active.stream().anyMatch(node -> node.allocation().get().membership().retired())) return false;
if (active.stream().anyMatch(node -> node.status().wantToRetire())) return false;
return true;
}
/**
* Find the best move to reduce allocation skew and returns it.
* Returns Move.none if no moves can be made to reduce skew.
*/
private void markWantToRetire(Node node) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return;
if (nodeToMove.get().state() != Node.State.active) return;
nodeRepository().write(nodeToMove.get().withWantToRetire(true, Agent.system, clock.instant()), lock);
log.info("Marked " + nodeToMove.get() + " as want to retire to reduce allocation skew");
}
}
private double skewReductionByRemoving(Node node, Node fromHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(fromHost);
double skewBefore = Node.skew(fromHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(fromHost.flavor().resources(), freeHostCapacity.add(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private double skewReductionByAdding(Node node, Node toHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(toHost);
double skewBefore = Node.skew(toHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(toHost.flavor().resources(), freeHostCapacity.subtract(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, 0);
final Node node;
final double netSkewReduction;
Move(Node node, double netSkewReduction) {
this.node = node;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move: " +
( node == null ? "none" : node.hostname() + ", skew reduction " + netSkewReduction );
}
}
} | class Rebalancer extends Maintainer {
private final HostResourcesCalculator hostResourcesCalculator;
private final Clock clock;
public Rebalancer(NodeRepository nodeRepository, HostResourcesCalculator hostResourcesCalculator, Clock clock, Duration interval) {
super(nodeRepository, interval);
this.hostResourcesCalculator = hostResourcesCalculator;
this.clock = clock;
}
@Override
protected void maintain() {
NodeList allNodes = nodeRepository().list();
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
markWantToRetire(bestMove.node);
}
private boolean zoneIsStable(NodeList allNodes) {
NodeList active = allNodes.state(Node.State.active);
if (active.stream().anyMatch(node -> node.allocation().get().membership().retired())) return false;
if (active.stream().anyMatch(node -> node.status().wantToRetire())) return false;
return true;
}
/**
* Find the best move to reduce allocation skew and returns it.
* Returns Move.none if no moves can be made to reduce skew.
*/
private void markWantToRetire(Node node) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return;
if (nodeToMove.get().state() != Node.State.active) return;
nodeRepository().write(nodeToMove.get().withWantToRetire(true, Agent.system, clock.instant()), lock);
log.info("Marked " + nodeToMove.get() + " as want to retire to reduce allocation skew");
}
}
private double skewReductionByRemoving(Node node, Node fromHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(fromHost);
double skewBefore = Node.skew(fromHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(fromHost.flavor().resources(), freeHostCapacity.add(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private double skewReductionByAdding(Node node, Node toHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(toHost);
double skewBefore = Node.skew(toHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(toHost.flavor().resources(), freeHostCapacity.subtract(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, 0);
final Node node;
final double netSkewReduction;
Move(Node node, double netSkewReduction) {
this.node = node;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move: " +
( node == null ? "none" : node.hostname() + ", skew reduction " + netSkewReduction );
}
}
} |
Could be simplified to ``` ( ! hasIndexedCluster() || ! getIndexed().hasDocumentDB(type.getFullName().getName())) ``` | public List<NewDocumentType> getDocumentTypesWithStoreOnly() {
List<NewDocumentType> indexedDocTypes = new ArrayList<>();
for (NewDocumentType type : documentDefinitions.values()) {
if (findStreamingCluster(type.getFullName().getName()).isEmpty() &&
(hasIndexedCluster() && !getIndexed().hasDocumentDB(type.getFullName().getName()) ||
!hasIndexedCluster())) {
indexedDocTypes.add(type);
}
}
return indexedDocTypes;
} | !hasIndexedCluster())) { | public List<NewDocumentType> getDocumentTypesWithStoreOnly() { return documentTypes(this::hasIndexingModeStoreOnly); } | class Builder extends VespaDomBuilder.DomConfigProducerBuilder<ContentSearchCluster> {
private final Map<String, NewDocumentType> documentDefinitions;
private final Set<NewDocumentType> globallyDistributedDocuments;
private final boolean combined;
public Builder(Map<String, NewDocumentType> documentDefinitions,
Set<NewDocumentType> globallyDistributedDocuments,
boolean combined) {
this.documentDefinitions = documentDefinitions;
this.globallyDistributedDocuments = globallyDistributedDocuments;
this.combined = combined;
}
@Override
protected ContentSearchCluster doBuild(DeployState deployState, AbstractConfigProducer ancestor, Element producerSpec) {
ModelElement clusterElem = new ModelElement(producerSpec);
String clusterName = ContentCluster.getClusterId(clusterElem);
Boolean flushOnShutdownElem = clusterElem.childAsBoolean("engine.proton.flush-on-shutdown");
ContentSearchCluster search = new ContentSearchCluster(ancestor,
clusterName,
deployState.getProperties(),
documentDefinitions,
globallyDistributedDocuments,
getFlushOnShutdown(flushOnShutdownElem, deployState),
combined);
ModelElement tuning = clusterElem.childByPath("engine.proton.tuning");
if (tuning != null) {
search.setTuning(new DomSearchTuningBuilder().build(deployState, search, tuning.getXml()));
}
ModelElement protonElem = clusterElem.childByPath("engine.proton");
if (protonElem != null) {
search.setResourceLimits(DomResourceLimitsBuilder.build(protonElem));
}
buildAllStreamingSearchClusters(deployState, clusterElem, clusterName, search);
buildIndexedSearchCluster(deployState, clusterElem, clusterName, search);
return search;
}
private boolean getFlushOnShutdown(Boolean flushOnShutdownElem, DeployState deployState) {
if (flushOnShutdownElem != null) {
return flushOnShutdownElem;
}
return ! stateIsHosted(deployState);
}
private Double getQueryTimeout(ModelElement clusterElem) {
return clusterElem.childAsDouble("engine.proton.query-timeout");
}
private void buildAllStreamingSearchClusters(DeployState deployState, ModelElement clusterElem, String clusterName, ContentSearchCluster search) {
ModelElement docElem = clusterElem.child("documents");
if (docElem == null) {
return;
}
for (ModelElement docType : docElem.subElements("document")) {
String mode = docType.stringAttribute("mode");
if ("streaming".equals(mode)) {
buildStreamingSearchCluster(deployState, clusterElem, clusterName, search, docType);
}
}
}
private void buildStreamingSearchCluster(DeployState deployState, ModelElement clusterElem, String clusterName,
ContentSearchCluster search, ModelElement docType) {
String docTypeName = docType.stringAttribute("type");
StreamingSearchCluster cluster = new StreamingSearchCluster(search, clusterName + "." + docTypeName, 0, docTypeName, clusterName);
search.addSearchCluster(deployState, cluster, getQueryTimeout(clusterElem), Arrays.asList(docType));
}
private void buildIndexedSearchCluster(DeployState deployState, ModelElement clusterElem,
String clusterName, ContentSearchCluster search) {
List<ModelElement> indexedDefs = getIndexedSchemas(clusterElem);
if (!indexedDefs.isEmpty()) {
IndexedSearchCluster isc = new IndexedSearchCluster(search, clusterName, 0, deployState);
isc.setRoutingSelector(clusterElem.childAsString("documents.selection"));
Double visibilityDelay = clusterElem.childAsDouble("engine.proton.visibility-delay");
if (visibilityDelay != null) {
search.setVisibilityDelay(visibilityDelay);
}
search.addSearchCluster(deployState, isc, getQueryTimeout(clusterElem), indexedDefs);
}
}
private List<ModelElement> getIndexedSchemas(ModelElement clusterElem) {
List<ModelElement> indexedDefs = new ArrayList<>();
ModelElement docElem = clusterElem.child("documents");
if (docElem == null) {
return indexedDefs;
}
for (ModelElement docType : docElem.subElements("document")) {
String mode = docType.stringAttribute("mode");
if ("index".equals(mode)) {
indexedDefs.add(docType);
}
}
return indexedDefs;
}
} | class Builder extends VespaDomBuilder.DomConfigProducerBuilder<ContentSearchCluster> {
private final Map<String, NewDocumentType> documentDefinitions;
private final Set<NewDocumentType> globallyDistributedDocuments;
private final boolean combined;
public Builder(Map<String, NewDocumentType> documentDefinitions,
Set<NewDocumentType> globallyDistributedDocuments,
boolean combined) {
this.documentDefinitions = documentDefinitions;
this.globallyDistributedDocuments = globallyDistributedDocuments;
this.combined = combined;
}
@Override
protected ContentSearchCluster doBuild(DeployState deployState, AbstractConfigProducer ancestor, Element producerSpec) {
ModelElement clusterElem = new ModelElement(producerSpec);
String clusterName = ContentCluster.getClusterId(clusterElem);
Boolean flushOnShutdownElem = clusterElem.childAsBoolean("engine.proton.flush-on-shutdown");
ContentSearchCluster search = new ContentSearchCluster(ancestor,
clusterName,
deployState.getProperties(),
documentDefinitions,
globallyDistributedDocuments,
getFlushOnShutdown(flushOnShutdownElem, deployState),
combined);
ModelElement tuning = clusterElem.childByPath("engine.proton.tuning");
if (tuning != null) {
search.setTuning(new DomSearchTuningBuilder().build(deployState, search, tuning.getXml()));
}
ModelElement protonElem = clusterElem.childByPath("engine.proton");
if (protonElem != null) {
search.setResourceLimits(DomResourceLimitsBuilder.build(protonElem));
}
buildAllStreamingSearchClusters(deployState, clusterElem, clusterName, search);
buildIndexedSearchCluster(deployState, clusterElem, clusterName, search);
return search;
}
private boolean getFlushOnShutdown(Boolean flushOnShutdownElem, DeployState deployState) {
if (flushOnShutdownElem != null) {
return flushOnShutdownElem;
}
return ! stateIsHosted(deployState);
}
private Double getQueryTimeout(ModelElement clusterElem) {
return clusterElem.childAsDouble("engine.proton.query-timeout");
}
private void buildAllStreamingSearchClusters(DeployState deployState, ModelElement clusterElem, String clusterName, ContentSearchCluster search) {
ModelElement docElem = clusterElem.child("documents");
if (docElem == null) {
return;
}
for (ModelElement docType : docElem.subElements("document")) {
String mode = docType.stringAttribute("mode");
if ("streaming".equals(mode)) {
buildStreamingSearchCluster(deployState, clusterElem, clusterName, search, docType);
}
}
}
private void buildStreamingSearchCluster(DeployState deployState, ModelElement clusterElem, String clusterName,
ContentSearchCluster search, ModelElement docType) {
String docTypeName = docType.stringAttribute("type");
StreamingSearchCluster cluster = new StreamingSearchCluster(search, clusterName + "." + docTypeName, 0, docTypeName, clusterName);
search.addSearchCluster(deployState, cluster, getQueryTimeout(clusterElem), Arrays.asList(docType));
}
private void buildIndexedSearchCluster(DeployState deployState, ModelElement clusterElem,
String clusterName, ContentSearchCluster search) {
List<ModelElement> indexedDefs = getIndexedSchemas(clusterElem);
if (!indexedDefs.isEmpty()) {
IndexedSearchCluster isc = new IndexedSearchCluster(search, clusterName, 0, deployState);
isc.setRoutingSelector(clusterElem.childAsString("documents.selection"));
Double visibilityDelay = clusterElem.childAsDouble("engine.proton.visibility-delay");
if (visibilityDelay != null) {
search.setVisibilityDelay(visibilityDelay);
}
search.addSearchCluster(deployState, isc, getQueryTimeout(clusterElem), indexedDefs);
}
}
private List<ModelElement> getIndexedSchemas(ModelElement clusterElem) {
List<ModelElement> indexedDefs = new ArrayList<>();
ModelElement docElem = clusterElem.child("documents");
if (docElem == null) {
return indexedDefs;
}
for (ModelElement docType : docElem.subElements("document")) {
String mode = docType.stringAttribute("mode");
if ("index".equals(mode)) {
indexedDefs.add(docType);
}
}
return indexedDefs;
}
} |
Remove? Shuffle and then sort... | private void assertOrder(List<PrioritizableNode> expected) {
List<PrioritizableNode> copy = new ArrayList<>(expected);
Collections.shuffle(copy);
Collections.sort(copy);
assertEquals(expected, copy);
} | Collections.shuffle(copy); | private void assertOrder(List<PrioritizableNode> expected) {
List<PrioritizableNode> copy = new ArrayList<>(expected);
Collections.shuffle(copy);
Collections.sort(copy);
assertEquals(expected, copy);
} | class PrioritizableNodeTest {
@Test
public void test_order() {
List<PrioritizableNode> expected = List.of(
new PrioritizableNode(node("01", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.empty(), false, true, false),
new PrioritizableNode(node("02", Node.State.active), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, false),
new PrioritizableNode(node("03", Node.State.inactive), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, false),
new PrioritizableNode(node("04", Node.State.reserved), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, false),
new PrioritizableNode(node("05", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.active)), true, false, true),
new PrioritizableNode(node("06", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.ready)), true, false, true),
new PrioritizableNode(node("07", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.provisioned)), true, false, true),
new PrioritizableNode(node("08", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.failed)), true, false, true),
new PrioritizableNode(node("09", Node.State.ready), new NodeResources(1, 1, 1, 1), Optional.empty(), true, false, true),
new PrioritizableNode(node("10", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, true),
new PrioritizableNode(node("11", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, true)
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew1() {
List<PrioritizableNode> expected = List.of(
node("1", node(4, 4), host(20, 20), host(40, 40)),
node("2", node(4, 4), host(21, 20), host(40, 40)),
node("3", node(4, 4), host(22, 20), host(40, 40)),
node("4", node(4, 4), host(21, 22), host(40, 40)),
node("5", node(4, 4), host(21, 21), host(40, 80))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew2() {
List<PrioritizableNode> expected = List.of(
node("4", node(4, 4), host(19, 18), host(40, 40)),
node("3", node(4, 4), host(18, 20), host(40, 40)),
node("2", node(4, 4), host(19, 20), host(40, 40)),
node("1", node(4, 4), host(20, 20), host(40, 40)),
node("5", node(4, 4), host(19, 19), host(40, 80))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew3() {
List<PrioritizableNode> expected = List.of(
node("1", node(4, 2), host(20, 20), host(40, 40)),
node("2", node(4, 2), host(21, 20), host(40, 40)),
node("4", node(4, 2), host(21, 22), host(40, 40)),
node("3", node(4, 2), host(22, 20), host(40, 40)),
node("5", node(4, 2), host(21, 21), host(40, 80))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew4() {
List<PrioritizableNode> expected = List.of(
node("5", node(2, 10), host(21, 21), host(40, 80)),
node("3", node(2, 10), host(22, 20), host(40, 40)),
node("2", node(2, 10), host(21, 20), host(40, 40)),
node("1", node(2, 10), host(20, 20), host(40, 40)),
node("4", node(2, 10), host(21, 22), host(40, 40))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew5() {
List<PrioritizableNode> expected = List.of(
node("1", node(1, 5), host(21, 10), host(40, 40)),
node("2", node(1, 5), host(21, 20), host(40, 40)),
node("3", node(1, 5), host(20, 20), host(40, 40)),
node("4", node(1, 5), host(20, 22), host(40, 40))
);
assertOrder(expected);
}
private static NodeResources node(double vcpu, double mem) {
return new NodeResources(vcpu, mem, 0, 0);
}
private static NodeResources host(double vcpu, double mem) {
return new NodeResources(vcpu, mem, 10, 10);
}
private static Node node(String hostname, Node.State state) {
return new Node(hostname, new IP.Config(Set.of("::1"), Set.of()), hostname, Optional.empty(), new Flavor(new NodeResources(2, 2, 2, 2)),
Status.initial(), state, Optional.empty(), History.empty(), NodeType.tenant, new Reports(), Optional.empty());
}
private static PrioritizableNode node(String hostname,
NodeResources nodeResources,
NodeResources allocatedHostResources,
NodeResources totalHostResources) {
Node node = new Node(hostname, new IP.Config(Set.of("::1"), Set.of()), hostname, Optional.of(hostname + "parent"), new Flavor(nodeResources),
Status.initial(), Node.State.ready, Optional.empty(), History.empty(), NodeType.tenant, new Reports(), Optional.empty());
Node parent = new Node(hostname + "parent", new IP.Config(Set.of("::1"), Set.of()), hostname, Optional.empty(), new Flavor(totalHostResources),
Status.initial(), Node.State.ready, Optional.empty(), History.empty(), NodeType.host, new Reports(), Optional.empty());
return new PrioritizableNode(node, totalHostResources.subtract(allocatedHostResources), Optional.of(parent), false, false, true);
}
private void printSkew(List<PrioritizableNode> nodes) {
for (var node : nodes)
System.out.println("Skew of " + node.node.id() +
": diff: " + (node.skewWithThis()-node.skewWithoutThis()) +
", with: " + node.skewWithThis() +
", without: " + node.skewWithoutThis());
}
} | class PrioritizableNodeTest {
@Test
public void test_order() {
List<PrioritizableNode> expected = List.of(
new PrioritizableNode(node("01", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.empty(), false, true, false),
new PrioritizableNode(node("02", Node.State.active), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, false),
new PrioritizableNode(node("03", Node.State.inactive), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, false),
new PrioritizableNode(node("04", Node.State.reserved), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, false),
new PrioritizableNode(node("05", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.active)), true, false, true),
new PrioritizableNode(node("06", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.ready)), true, false, true),
new PrioritizableNode(node("07", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.provisioned)), true, false, true),
new PrioritizableNode(node("08", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.failed)), true, false, true),
new PrioritizableNode(node("09", Node.State.ready), new NodeResources(1, 1, 1, 1), Optional.empty(), true, false, true),
new PrioritizableNode(node("10", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, true),
new PrioritizableNode(node("11", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, true)
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew1() {
List<PrioritizableNode> expected = List.of(
node("1", node(4, 4), host(20, 20), host(40, 40)),
node("2", node(4, 4), host(21, 20), host(40, 40)),
node("3", node(4, 4), host(22, 20), host(40, 40)),
node("4", node(4, 4), host(21, 22), host(40, 40)),
node("5", node(4, 4), host(21, 21), host(40, 80))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew2() {
List<PrioritizableNode> expected = List.of(
node("4", node(4, 4), host(19, 18), host(40, 40)),
node("3", node(4, 4), host(18, 20), host(40, 40)),
node("2", node(4, 4), host(19, 20), host(40, 40)),
node("1", node(4, 4), host(20, 20), host(40, 40)),
node("5", node(4, 4), host(19, 19), host(40, 80))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew3() {
List<PrioritizableNode> expected = List.of(
node("1", node(4, 2), host(20, 20), host(40, 40)),
node("2", node(4, 2), host(21, 20), host(40, 40)),
node("4", node(4, 2), host(21, 22), host(40, 40)),
node("3", node(4, 2), host(22, 20), host(40, 40)),
node("5", node(4, 2), host(21, 21), host(40, 80))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew4() {
List<PrioritizableNode> expected = List.of(
node("5", node(2, 10), host(21, 21), host(40, 80)),
node("3", node(2, 10), host(22, 20), host(40, 40)),
node("2", node(2, 10), host(21, 20), host(40, 40)),
node("1", node(2, 10), host(20, 20), host(40, 40)),
node("4", node(2, 10), host(21, 22), host(40, 40))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew5() {
List<PrioritizableNode> expected = List.of(
node("1", node(1, 5), host(21, 10), host(40, 40)),
node("2", node(1, 5), host(21, 20), host(40, 40)),
node("3", node(1, 5), host(20, 20), host(40, 40)),
node("4", node(1, 5), host(20, 22), host(40, 40))
);
assertOrder(expected);
}
private static NodeResources node(double vcpu, double mem) {
return new NodeResources(vcpu, mem, 0, 0);
}
private static NodeResources host(double vcpu, double mem) {
return new NodeResources(vcpu, mem, 10, 10);
}
private static Node node(String hostname, Node.State state) {
return new Node(hostname, new IP.Config(Set.of("::1"), Set.of()), hostname, Optional.empty(), new Flavor(new NodeResources(2, 2, 2, 2)),
Status.initial(), state, Optional.empty(), History.empty(), NodeType.tenant, new Reports(), Optional.empty());
}
private static PrioritizableNode node(String hostname,
NodeResources nodeResources,
NodeResources allocatedHostResources,
NodeResources totalHostResources) {
Node node = new Node(hostname, new IP.Config(Set.of("::1"), Set.of()), hostname, Optional.of(hostname + "parent"), new Flavor(nodeResources),
Status.initial(), Node.State.ready, Optional.empty(), History.empty(), NodeType.tenant, new Reports(), Optional.empty());
Node parent = new Node(hostname + "parent", new IP.Config(Set.of("::1"), Set.of()), hostname, Optional.empty(), new Flavor(totalHostResources),
Status.initial(), Node.State.ready, Optional.empty(), History.empty(), NodeType.host, new Reports(), Optional.empty());
return new PrioritizableNode(node, totalHostResources.subtract(allocatedHostResources), Optional.of(parent), false, false, true);
}
private void printSkew(List<PrioritizableNode> nodes) {
for (var node : nodes)
System.out.println("Skew of " + node.node.id() +
": diff: " + (node.skewWithThis()-node.skewWithoutThis()) +
", with: " + node.skewWithThis() +
", without: " + node.skewWithoutThis());
}
} |
It's to test the order resulting from sort. Before shuffle it is already sorted correctly. | private void assertOrder(List<PrioritizableNode> expected) {
List<PrioritizableNode> copy = new ArrayList<>(expected);
Collections.shuffle(copy);
Collections.sort(copy);
assertEquals(expected, copy);
} | Collections.shuffle(copy); | private void assertOrder(List<PrioritizableNode> expected) {
List<PrioritizableNode> copy = new ArrayList<>(expected);
Collections.shuffle(copy);
Collections.sort(copy);
assertEquals(expected, copy);
} | class PrioritizableNodeTest {
@Test
public void test_order() {
List<PrioritizableNode> expected = List.of(
new PrioritizableNode(node("01", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.empty(), false, true, false),
new PrioritizableNode(node("02", Node.State.active), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, false),
new PrioritizableNode(node("03", Node.State.inactive), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, false),
new PrioritizableNode(node("04", Node.State.reserved), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, false),
new PrioritizableNode(node("05", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.active)), true, false, true),
new PrioritizableNode(node("06", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.ready)), true, false, true),
new PrioritizableNode(node("07", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.provisioned)), true, false, true),
new PrioritizableNode(node("08", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.failed)), true, false, true),
new PrioritizableNode(node("09", Node.State.ready), new NodeResources(1, 1, 1, 1), Optional.empty(), true, false, true),
new PrioritizableNode(node("10", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, true),
new PrioritizableNode(node("11", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, true)
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew1() {
List<PrioritizableNode> expected = List.of(
node("1", node(4, 4), host(20, 20), host(40, 40)),
node("2", node(4, 4), host(21, 20), host(40, 40)),
node("3", node(4, 4), host(22, 20), host(40, 40)),
node("4", node(4, 4), host(21, 22), host(40, 40)),
node("5", node(4, 4), host(21, 21), host(40, 80))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew2() {
List<PrioritizableNode> expected = List.of(
node("4", node(4, 4), host(19, 18), host(40, 40)),
node("3", node(4, 4), host(18, 20), host(40, 40)),
node("2", node(4, 4), host(19, 20), host(40, 40)),
node("1", node(4, 4), host(20, 20), host(40, 40)),
node("5", node(4, 4), host(19, 19), host(40, 80))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew3() {
List<PrioritizableNode> expected = List.of(
node("1", node(4, 2), host(20, 20), host(40, 40)),
node("2", node(4, 2), host(21, 20), host(40, 40)),
node("4", node(4, 2), host(21, 22), host(40, 40)),
node("3", node(4, 2), host(22, 20), host(40, 40)),
node("5", node(4, 2), host(21, 21), host(40, 80))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew4() {
List<PrioritizableNode> expected = List.of(
node("5", node(2, 10), host(21, 21), host(40, 80)),
node("3", node(2, 10), host(22, 20), host(40, 40)),
node("2", node(2, 10), host(21, 20), host(40, 40)),
node("1", node(2, 10), host(20, 20), host(40, 40)),
node("4", node(2, 10), host(21, 22), host(40, 40))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew5() {
List<PrioritizableNode> expected = List.of(
node("1", node(1, 5), host(21, 10), host(40, 40)),
node("2", node(1, 5), host(21, 20), host(40, 40)),
node("3", node(1, 5), host(20, 20), host(40, 40)),
node("4", node(1, 5), host(20, 22), host(40, 40))
);
assertOrder(expected);
}
private static NodeResources node(double vcpu, double mem) {
return new NodeResources(vcpu, mem, 0, 0);
}
private static NodeResources host(double vcpu, double mem) {
return new NodeResources(vcpu, mem, 10, 10);
}
private static Node node(String hostname, Node.State state) {
return new Node(hostname, new IP.Config(Set.of("::1"), Set.of()), hostname, Optional.empty(), new Flavor(new NodeResources(2, 2, 2, 2)),
Status.initial(), state, Optional.empty(), History.empty(), NodeType.tenant, new Reports(), Optional.empty());
}
private static PrioritizableNode node(String hostname,
NodeResources nodeResources,
NodeResources allocatedHostResources,
NodeResources totalHostResources) {
Node node = new Node(hostname, new IP.Config(Set.of("::1"), Set.of()), hostname, Optional.of(hostname + "parent"), new Flavor(nodeResources),
Status.initial(), Node.State.ready, Optional.empty(), History.empty(), NodeType.tenant, new Reports(), Optional.empty());
Node parent = new Node(hostname + "parent", new IP.Config(Set.of("::1"), Set.of()), hostname, Optional.empty(), new Flavor(totalHostResources),
Status.initial(), Node.State.ready, Optional.empty(), History.empty(), NodeType.host, new Reports(), Optional.empty());
return new PrioritizableNode(node, totalHostResources.subtract(allocatedHostResources), Optional.of(parent), false, false, true);
}
private void printSkew(List<PrioritizableNode> nodes) {
for (var node : nodes)
System.out.println("Skew of " + node.node.id() +
": diff: " + (node.skewWithThis()-node.skewWithoutThis()) +
", with: " + node.skewWithThis() +
", without: " + node.skewWithoutThis());
}
} | class PrioritizableNodeTest {
@Test
public void test_order() {
List<PrioritizableNode> expected = List.of(
new PrioritizableNode(node("01", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.empty(), false, true, false),
new PrioritizableNode(node("02", Node.State.active), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, false),
new PrioritizableNode(node("03", Node.State.inactive), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, false),
new PrioritizableNode(node("04", Node.State.reserved), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, false),
new PrioritizableNode(node("05", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.active)), true, false, true),
new PrioritizableNode(node("06", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.ready)), true, false, true),
new PrioritizableNode(node("07", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.provisioned)), true, false, true),
new PrioritizableNode(node("08", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.of(node("host1", Node.State.failed)), true, false, true),
new PrioritizableNode(node("09", Node.State.ready), new NodeResources(1, 1, 1, 1), Optional.empty(), true, false, true),
new PrioritizableNode(node("10", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, true),
new PrioritizableNode(node("11", Node.State.ready), new NodeResources(2, 2, 2, 2), Optional.empty(), true, false, true)
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew1() {
List<PrioritizableNode> expected = List.of(
node("1", node(4, 4), host(20, 20), host(40, 40)),
node("2", node(4, 4), host(21, 20), host(40, 40)),
node("3", node(4, 4), host(22, 20), host(40, 40)),
node("4", node(4, 4), host(21, 22), host(40, 40)),
node("5", node(4, 4), host(21, 21), host(40, 80))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew2() {
List<PrioritizableNode> expected = List.of(
node("4", node(4, 4), host(19, 18), host(40, 40)),
node("3", node(4, 4), host(18, 20), host(40, 40)),
node("2", node(4, 4), host(19, 20), host(40, 40)),
node("1", node(4, 4), host(20, 20), host(40, 40)),
node("5", node(4, 4), host(19, 19), host(40, 80))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew3() {
List<PrioritizableNode> expected = List.of(
node("1", node(4, 2), host(20, 20), host(40, 40)),
node("2", node(4, 2), host(21, 20), host(40, 40)),
node("4", node(4, 2), host(21, 22), host(40, 40)),
node("3", node(4, 2), host(22, 20), host(40, 40)),
node("5", node(4, 2), host(21, 21), host(40, 80))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew4() {
List<PrioritizableNode> expected = List.of(
node("5", node(2, 10), host(21, 21), host(40, 80)),
node("3", node(2, 10), host(22, 20), host(40, 40)),
node("2", node(2, 10), host(21, 20), host(40, 40)),
node("1", node(2, 10), host(20, 20), host(40, 40)),
node("4", node(2, 10), host(21, 22), host(40, 40))
);
assertOrder(expected);
}
@Test
public void testOrderingByAllocationSkew5() {
List<PrioritizableNode> expected = List.of(
node("1", node(1, 5), host(21, 10), host(40, 40)),
node("2", node(1, 5), host(21, 20), host(40, 40)),
node("3", node(1, 5), host(20, 20), host(40, 40)),
node("4", node(1, 5), host(20, 22), host(40, 40))
);
assertOrder(expected);
}
private static NodeResources node(double vcpu, double mem) {
return new NodeResources(vcpu, mem, 0, 0);
}
private static NodeResources host(double vcpu, double mem) {
return new NodeResources(vcpu, mem, 10, 10);
}
private static Node node(String hostname, Node.State state) {
return new Node(hostname, new IP.Config(Set.of("::1"), Set.of()), hostname, Optional.empty(), new Flavor(new NodeResources(2, 2, 2, 2)),
Status.initial(), state, Optional.empty(), History.empty(), NodeType.tenant, new Reports(), Optional.empty());
}
private static PrioritizableNode node(String hostname,
NodeResources nodeResources,
NodeResources allocatedHostResources,
NodeResources totalHostResources) {
Node node = new Node(hostname, new IP.Config(Set.of("::1"), Set.of()), hostname, Optional.of(hostname + "parent"), new Flavor(nodeResources),
Status.initial(), Node.State.ready, Optional.empty(), History.empty(), NodeType.tenant, new Reports(), Optional.empty());
Node parent = new Node(hostname + "parent", new IP.Config(Set.of("::1"), Set.of()), hostname, Optional.empty(), new Flavor(totalHostResources),
Status.initial(), Node.State.ready, Optional.empty(), History.empty(), NodeType.host, new Reports(), Optional.empty());
return new PrioritizableNode(node, totalHostResources.subtract(allocatedHostResources), Optional.of(parent), false, false, true);
}
private void printSkew(List<PrioritizableNode> nodes) {
for (var node : nodes)
System.out.println("Skew of " + node.node.id() +
": diff: " + (node.skewWithThis()-node.skewWithoutThis()) +
", with: " + node.skewWithThis() +
", without: " + node.skewWithoutThis());
}
} |
If we mistakenly retire a wrong node, it would take long time to redeploy the app to undo when we un-wantToRetire it with this change. | public Node withWantToRetire(boolean wantToRetire, Agent agent, Instant at) {
if (wantToRetire == status.wantToRetire()) return this;
Node node = this.with(status.withWantToRetire(wantToRetire));
if (wantToRetire)
node = node.with(history.with(new History.Event(History.Event.Type.wantToRetire, agent, at)));
return node;
} | if (wantToRetire) | public Node withWantToRetire(boolean wantToRetire, Agent agent, Instant at) {
if (wantToRetire == status.wantToRetire()) return this;
Node node = this.with(status.withWantToRetire(wantToRetire));
if (wantToRetire)
node = node.with(history.with(new History.Event(History.Event.Type.wantToRetire, agent, at)));
return node;
} | class Node {
private final String hostname;
private final IP.Config ipConfig;
private final String id;
private final Optional<String> parentHostname;
private final Flavor flavor;
private final Status status;
private final State state;
private final NodeType type;
private final Reports reports;
private final Optional<String> modelName;
/** Record of the last event of each type happening to this node */
private final History history;
/** The current allocation of this node, if any */
private final Optional<Allocation> allocation;
/** Creates a node in the initial state (reserved) */
public static Node createDockerNode(Set<String> ipAddresses, String hostname, String parentHostname, NodeResources resources, NodeType type) {
return new Node("fake-" + hostname, new IP.Config(ipAddresses, Set.of()), hostname, Optional.of(parentHostname), new Flavor(resources), Status.initial(), State.reserved,
Optional.empty(), History.empty(), type, new Reports(), Optional.empty());
}
/** Creates a node in the initial state (provisioned) */
public static Node create(String openStackId, IP.Config ipConfig, String hostname, Optional<String> parentHostname, Optional<String> modelName, Flavor flavor, NodeType type) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, Status.initial(), State.provisioned,
Optional.empty(), History.empty(), type, new Reports(), modelName);
}
/** Creates a node. See also the {@code create} helper methods. */
public Node(String id, IP.Config ipConfig, String hostname, Optional<String> parentHostname,
Flavor flavor, Status status, State state, Optional<Allocation> allocation, History history, NodeType type,
Reports reports, Optional<String> modelName) {
Objects.requireNonNull(id, "A node must have an ID");
requireNonEmptyString(hostname, "A node must have a hostname");
Objects.requireNonNull(ipConfig, "A node must a have an IP config");
requireNonEmptyString(parentHostname, "A parent host name must be a proper value");
Objects.requireNonNull(flavor, "A node must have a flavor");
Objects.requireNonNull(status, "A node must have a status");
Objects.requireNonNull(state, "A null node state is not permitted");
Objects.requireNonNull(allocation, "A null node allocation is not permitted");
Objects.requireNonNull(history, "A null node history is not permitted");
Objects.requireNonNull(type, "A null node type is not permitted");
Objects.requireNonNull(reports, "A null reports is not permitted");
Objects.requireNonNull(modelName, "A null modelName is not permitted");
if (state == State.active)
requireNonEmpty(ipConfig.primary(), "An active node must have at least one valid IP address");
if (parentHostname.isPresent()) {
if (!ipConfig.pool().asSet().isEmpty()) throw new IllegalArgumentException("A child node cannot have an IP address pool");
if (modelName.isPresent()) throw new IllegalArgumentException("A child node cannot have model name set");
}
this.hostname = hostname;
this.ipConfig = ipConfig;
this.parentHostname = parentHostname;
this.id = id;
this.flavor = flavor;
this.status = status;
this.state = state;
this.allocation = allocation;
this.history = history;
this.type = type;
this.reports = reports;
this.modelName = modelName;
}
/** Returns the IP addresses of this node */
public Set<String> ipAddresses() { return ipConfig.primary(); }
/** Returns the IP address pool available on this node. These IP addresses are available for use by containers
* running on this node */
public IP.Pool ipAddressPool() { return ipConfig.pool(); }
/** Returns the IP config of this node */
public IP.Config ipConfig() { return ipConfig; }
/** Returns the host name of this node */
public String hostname() { return hostname; }
/**
* Unique identifier for this node. Code should not depend on this as its main purpose is to aid human operators in
* mapping a node to the corresponding cloud instance. No particular format is enforced.
*
* Formats used vary between the underlying cloud providers:
*
* - OpenStack: UUID
* - AWS: Instance ID
* - Docker containers: fake-[hostname]
*/
public String id() { return id; }
/** Returns the parent hostname for this node if this node is a docker container or a VM (i.e. it has a parent host). Otherwise, empty **/
public Optional<String> parentHostname() { return parentHostname; }
/** Returns the flavor of this node */
public Flavor flavor() { return flavor; }
/** Returns the known information about the node's ephemeral status */
public Status status() { return status; }
/** Returns the current state of this node (in the node state machine) */
public State state() { return state; }
/** Returns the type of this node */
public NodeType type() { return type; }
/** Returns the current allocation of this, if any */
public Optional<Allocation> allocation() { return allocation; }
/** Returns the current allocation when it must exist, or throw exception there is not allocation. */
private Allocation requireAllocation(String message) {
final Optional<Allocation> allocation = this.allocation;
if ( ! allocation.isPresent())
throw new IllegalStateException(message + " for " + hostname() + ": The node is unallocated");
return allocation.get();
}
/** Returns a history of the last events happening to this node */
public History history() { return history; }
/** Returns all the reports on this node. */
public Reports reports() { return reports; }
/** Returns the hardware model of this node */
public Optional<String> modelName() { return modelName; }
/**
* Returns a copy of this node with wantToRetire set to the given value and updated history.
* If given wantToRetire is equal to the current, the method is no-op.
*/
/**
* Returns a copy of this node which is retired.
* If the node was already retired it is returned as-is.
*/
public Node retire(Agent agent, Instant retiredAt) {
Allocation allocation = requireAllocation("Cannot retire");
if (allocation.membership().retired()) return this;
return with(allocation.retire())
.with(history.with(new History.Event(History.Event.Type.retired, agent, retiredAt)));
}
/** Returns a copy of this node which is retired */
public Node retire(Instant retiredAt) {
if (status.wantToRetire())
return retire(Agent.system, retiredAt);
else
return retire(Agent.application, retiredAt);
}
/** Returns a copy of this node which is not retired */
public Node unretire() {
return with(requireAllocation("Cannot unretire").unretire());
}
/** Returns a copy of this with the restart generation set to generation */
public Node withRestart(Generation generation) {
Allocation allocation = requireAllocation("Cannot set restart generation");
return with(allocation.withRestart(generation));
}
/** Returns a node with the status assigned to the given value */
public Node with(Status status) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the type assigned to the given value */
public Node with(NodeType type) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the flavor assigned to the given value */
public Node with(Flavor flavor) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the reboot generation set to generation */
public Node withReboot(Generation generation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status.withReboot(generation), state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the openStackId set */
public Node withOpenStackId(String openStackId) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with model name set to given value */
public Node withModelName(String modelName) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.of(modelName));
}
/** Returns a copy of this with model name cleared */
public Node withoutModelName() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.empty());
}
/** Returns a copy of this with a history record saying it was detected to be down at this instant */
public Node downAt(Instant instant) {
return with(history.with(new History.Event(History.Event.Type.down, Agent.system, instant)));
}
/** Returns a copy of this with any history record saying it has been detected down removed */
public Node up() {
return with(history.without(History.Event.Type.down));
}
/** Returns a copy of this with allocation set as specified. <code>node.state</code> is *not* changed. */
public Node allocate(ApplicationId owner, ClusterMembership membership, Instant at) {
return this.with(new Allocation(owner, membership, new Generation(0, 0), false))
.with(history.with(new History.Event(History.Event.Type.reserved, Agent.application, at)));
}
/**
* Returns a copy of this node with the allocation assigned to the given allocation.
* Do not use this to allocate a node.
*/
public Node with(Allocation allocation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.of(allocation), history, type, reports, modelName);
}
/** Returns a new Node without an allocation. */
public Node withoutAllocation() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.empty(), history, type, reports, modelName);
}
/** Returns a copy of this node with IP config set to the given value. */
public Node with(IP.Config ipConfig) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the parent hostname assigned to the given value. */
public Node withParentHostname(String parentHostname) {
return new Node(id, ipConfig, hostname, Optional.of(parentHostname), flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the current reboot generation set to the given number at the given instant */
public Node withCurrentRebootGeneration(long generation, Instant instant) {
Status newStatus = status().withReboot(status().reboot().withCurrent(generation));
History newHistory = history();
if (generation > status().reboot().current())
newHistory = history.with(new History.Event(History.Event.Type.rebooted, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the current OS version set to the given version at the given instant */
public Node withCurrentOsVersion(Version version, Instant instant) {
var newStatus = status.withOsVersion(version);
var newHistory = history();
if (status.osVersion().isEmpty() || !status.osVersion().get().equals(version)) {
newHistory = history.with(new History.Event(History.Event.Type.osUpgraded, Agent.system, instant));
}
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with firmware verified at the given instant */
public Node withFirmwareVerifiedAt(Instant instant) {
var newStatus = status.withFirmwareVerifiedAt(instant);
var newHistory = history.with(new History.Event(History.Event.Type.firmwareVerified, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the given history. */
public Node with(History history) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
public Node with(Reports reports) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
private static void requireNonEmptyString(Optional<String> value, String message) {
Objects.requireNonNull(value, message);
value.ifPresent(v -> requireNonEmptyString(v, message));
}
private static void requireNonEmptyString(String value, String message) {
Objects.requireNonNull(value, message);
if (value.trim().isEmpty())
throw new IllegalArgumentException(message + ", but was '" + value + "'");
}
private static void requireNonEmpty(Set<String> values, String message) {
if (values == null || values.isEmpty()) {
throw new IllegalArgumentException(message);
}
}
/** Computes the allocation skew of a host node */
public static double skew(NodeResources totalHostCapacity, NodeResources freeHostCapacity) {
NodeResources all = totalHostCapacity.anySpeed();
NodeResources allocated = all.subtract(freeHostCapacity.anySpeed());
return new Mean(allocated.vcpu() / all.vcpu(),
allocated.memoryGb() / all.memoryGb(),
allocated.diskGb() / all.diskGb())
.deviation();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return hostname.equals(node.hostname);
}
@Override
public int hashCode() {
return Objects.hash(hostname);
}
@Override
public String toString() {
return state + " node " +
hostname +
(allocation.map(allocation1 -> " " + allocation1).orElse("")) +
(parentHostname.map(parent -> " [on: " + parent + "]").orElse(""));
}
public enum State {
/** This node has been requested (from OpenStack) but is not yet ready for use */
provisioned,
/** This node is free and ready for use */
ready,
/** This node has been reserved by an application but is not yet used by it */
reserved,
/** This node is in active use by an application */
active,
/** This node has been used by an application, is still allocated to it and retains the data needed for its allocated role */
inactive,
/** This node is not allocated to an application but may contain data which must be cleaned before it is ready */
dirty,
/** This node has failed and must be repaired or removed. The node retains any allocation data for diagnosis. */
failed,
/**
* This node should not currently be used.
* This state follows the same rules as failed except that it will never be automatically moved out of
* this state.
*/
parked;
/** Returns whether this is a state where the node is assigned to an application */
public boolean isAllocated() {
return this == reserved || this == active || this == inactive || this == failed || this == parked;
}
}
/** The mean and mean deviation (squared difference) of a bunch of numbers */
private static class Mean {
private final double mean;
private final double deviation;
private Mean(double ... numbers) {
mean = Arrays.stream(numbers).sum() / numbers.length;
deviation = Arrays.stream(numbers).map(n -> Math.pow(mean - n, 2)).sum() / numbers.length;
}
public double deviation() { return deviation; }
}
} | class Node {
private final String hostname;
private final IP.Config ipConfig;
private final String id;
private final Optional<String> parentHostname;
private final Flavor flavor;
private final Status status;
private final State state;
private final NodeType type;
private final Reports reports;
private final Optional<String> modelName;
/** Record of the last event of each type happening to this node */
private final History history;
/** The current allocation of this node, if any */
private final Optional<Allocation> allocation;
/** Creates a node in the initial state (reserved) */
public static Node createDockerNode(Set<String> ipAddresses, String hostname, String parentHostname, NodeResources resources, NodeType type) {
return new Node("fake-" + hostname, new IP.Config(ipAddresses, Set.of()), hostname, Optional.of(parentHostname), new Flavor(resources), Status.initial(), State.reserved,
Optional.empty(), History.empty(), type, new Reports(), Optional.empty());
}
/** Creates a node in the initial state (provisioned) */
public static Node create(String openStackId, IP.Config ipConfig, String hostname, Optional<String> parentHostname, Optional<String> modelName, Flavor flavor, NodeType type) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, Status.initial(), State.provisioned,
Optional.empty(), History.empty(), type, new Reports(), modelName);
}
/** Creates a node. See also the {@code create} helper methods. */
public Node(String id, IP.Config ipConfig, String hostname, Optional<String> parentHostname,
Flavor flavor, Status status, State state, Optional<Allocation> allocation, History history, NodeType type,
Reports reports, Optional<String> modelName) {
Objects.requireNonNull(id, "A node must have an ID");
requireNonEmptyString(hostname, "A node must have a hostname");
Objects.requireNonNull(ipConfig, "A node must a have an IP config");
requireNonEmptyString(parentHostname, "A parent host name must be a proper value");
Objects.requireNonNull(flavor, "A node must have a flavor");
Objects.requireNonNull(status, "A node must have a status");
Objects.requireNonNull(state, "A null node state is not permitted");
Objects.requireNonNull(allocation, "A null node allocation is not permitted");
Objects.requireNonNull(history, "A null node history is not permitted");
Objects.requireNonNull(type, "A null node type is not permitted");
Objects.requireNonNull(reports, "A null reports is not permitted");
Objects.requireNonNull(modelName, "A null modelName is not permitted");
if (state == State.active)
requireNonEmpty(ipConfig.primary(), "An active node must have at least one valid IP address");
if (parentHostname.isPresent()) {
if (!ipConfig.pool().asSet().isEmpty()) throw new IllegalArgumentException("A child node cannot have an IP address pool");
if (modelName.isPresent()) throw new IllegalArgumentException("A child node cannot have model name set");
}
this.hostname = hostname;
this.ipConfig = ipConfig;
this.parentHostname = parentHostname;
this.id = id;
this.flavor = flavor;
this.status = status;
this.state = state;
this.allocation = allocation;
this.history = history;
this.type = type;
this.reports = reports;
this.modelName = modelName;
}
/** Returns the IP addresses of this node */
public Set<String> ipAddresses() { return ipConfig.primary(); }
/** Returns the IP address pool available on this node. These IP addresses are available for use by containers
* running on this node */
public IP.Pool ipAddressPool() { return ipConfig.pool(); }
/** Returns the IP config of this node */
public IP.Config ipConfig() { return ipConfig; }
/** Returns the host name of this node */
public String hostname() { return hostname; }
/**
* Unique identifier for this node. Code should not depend on this as its main purpose is to aid human operators in
* mapping a node to the corresponding cloud instance. No particular format is enforced.
*
* Formats used vary between the underlying cloud providers:
*
* - OpenStack: UUID
* - AWS: Instance ID
* - Docker containers: fake-[hostname]
*/
public String id() { return id; }
/** Returns the parent hostname for this node if this node is a docker container or a VM (i.e. it has a parent host). Otherwise, empty **/
public Optional<String> parentHostname() { return parentHostname; }
/** Returns the flavor of this node */
public Flavor flavor() { return flavor; }
/** Returns the known information about the node's ephemeral status */
public Status status() { return status; }
/** Returns the current state of this node (in the node state machine) */
public State state() { return state; }
/** Returns the type of this node */
public NodeType type() { return type; }
/** Returns the current allocation of this, if any */
public Optional<Allocation> allocation() { return allocation; }
/** Returns the current allocation when it must exist, or throw exception there is not allocation. */
private Allocation requireAllocation(String message) {
final Optional<Allocation> allocation = this.allocation;
if ( ! allocation.isPresent())
throw new IllegalStateException(message + " for " + hostname() + ": The node is unallocated");
return allocation.get();
}
/** Returns a history of the last events happening to this node */
public History history() { return history; }
/** Returns all the reports on this node. */
public Reports reports() { return reports; }
/** Returns the hardware model of this node */
public Optional<String> modelName() { return modelName; }
/**
* Returns a copy of this node with wantToRetire set to the given value and updated history.
* If given wantToRetire is equal to the current, the method is no-op.
*/
/**
* Returns a copy of this node which is retired.
* If the node was already retired it is returned as-is.
*/
public Node retire(Agent agent, Instant retiredAt) {
Allocation allocation = requireAllocation("Cannot retire");
if (allocation.membership().retired()) return this;
return with(allocation.retire())
.with(history.with(new History.Event(History.Event.Type.retired, agent, retiredAt)));
}
/** Returns a copy of this node which is retired */
public Node retire(Instant retiredAt) {
if (status.wantToRetire())
return retire(Agent.system, retiredAt);
else
return retire(Agent.application, retiredAt);
}
/** Returns a copy of this node which is not retired */
public Node unretire() {
return with(requireAllocation("Cannot unretire").unretire());
}
/** Returns a copy of this with the restart generation set to generation */
public Node withRestart(Generation generation) {
Allocation allocation = requireAllocation("Cannot set restart generation");
return with(allocation.withRestart(generation));
}
/** Returns a node with the status assigned to the given value */
public Node with(Status status) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the type assigned to the given value */
public Node with(NodeType type) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the flavor assigned to the given value */
public Node with(Flavor flavor) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the reboot generation set to generation */
public Node withReboot(Generation generation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status.withReboot(generation), state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the openStackId set */
public Node withOpenStackId(String openStackId) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with model name set to given value */
public Node withModelName(String modelName) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.of(modelName));
}
/** Returns a copy of this with model name cleared */
public Node withoutModelName() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.empty());
}
/** Returns a copy of this with a history record saying it was detected to be down at this instant */
public Node downAt(Instant instant) {
return with(history.with(new History.Event(History.Event.Type.down, Agent.system, instant)));
}
/** Returns a copy of this with any history record saying it has been detected down removed */
public Node up() {
return with(history.without(History.Event.Type.down));
}
/** Returns a copy of this with allocation set as specified. <code>node.state</code> is *not* changed. */
public Node allocate(ApplicationId owner, ClusterMembership membership, Instant at) {
return this.with(new Allocation(owner, membership, new Generation(0, 0), false))
.with(history.with(new History.Event(History.Event.Type.reserved, Agent.application, at)));
}
/**
* Returns a copy of this node with the allocation assigned to the given allocation.
* Do not use this to allocate a node.
*/
public Node with(Allocation allocation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.of(allocation), history, type, reports, modelName);
}
/** Returns a new Node without an allocation. */
public Node withoutAllocation() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.empty(), history, type, reports, modelName);
}
/** Returns a copy of this node with IP config set to the given value. */
public Node with(IP.Config ipConfig) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the parent hostname assigned to the given value. */
public Node withParentHostname(String parentHostname) {
return new Node(id, ipConfig, hostname, Optional.of(parentHostname), flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the current reboot generation set to the given number at the given instant */
public Node withCurrentRebootGeneration(long generation, Instant instant) {
Status newStatus = status().withReboot(status().reboot().withCurrent(generation));
History newHistory = history();
if (generation > status().reboot().current())
newHistory = history.with(new History.Event(History.Event.Type.rebooted, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the current OS version set to the given version at the given instant */
public Node withCurrentOsVersion(Version version, Instant instant) {
var newStatus = status.withOsVersion(version);
var newHistory = history();
if (status.osVersion().isEmpty() || !status.osVersion().get().equals(version)) {
newHistory = history.with(new History.Event(History.Event.Type.osUpgraded, Agent.system, instant));
}
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with firmware verified at the given instant */
public Node withFirmwareVerifiedAt(Instant instant) {
var newStatus = status.withFirmwareVerifiedAt(instant);
var newHistory = history.with(new History.Event(History.Event.Type.firmwareVerified, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the given history. */
public Node with(History history) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
public Node with(Reports reports) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
private static void requireNonEmptyString(Optional<String> value, String message) {
Objects.requireNonNull(value, message);
value.ifPresent(v -> requireNonEmptyString(v, message));
}
private static void requireNonEmptyString(String value, String message) {
Objects.requireNonNull(value, message);
if (value.trim().isEmpty())
throw new IllegalArgumentException(message + ", but was '" + value + "'");
}
private static void requireNonEmpty(Set<String> values, String message) {
if (values == null || values.isEmpty()) {
throw new IllegalArgumentException(message);
}
}
/** Computes the allocation skew of a host node */
public static double skew(NodeResources totalHostCapacity, NodeResources freeHostCapacity) {
NodeResources all = totalHostCapacity.anySpeed();
NodeResources allocated = all.subtract(freeHostCapacity.anySpeed());
return new Mean(allocated.vcpu() / all.vcpu(),
allocated.memoryGb() / all.memoryGb(),
allocated.diskGb() / all.diskGb())
.deviation();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return hostname.equals(node.hostname);
}
@Override
public int hashCode() {
return Objects.hash(hostname);
}
@Override
public String toString() {
return state + " node " +
hostname +
(allocation.map(allocation1 -> " " + allocation1).orElse("")) +
(parentHostname.map(parent -> " [on: " + parent + "]").orElse(""));
}
public enum State {
/** This node has been requested (from OpenStack) but is not yet ready for use */
provisioned,
/** This node is free and ready for use */
ready,
/** This node has been reserved by an application but is not yet used by it */
reserved,
/** This node is in active use by an application */
active,
/** This node has been used by an application, is still allocated to it and retains the data needed for its allocated role */
inactive,
/** This node is not allocated to an application but may contain data which must be cleaned before it is ready */
dirty,
/** This node has failed and must be repaired or removed. The node retains any allocation data for diagnosis. */
failed,
/**
* This node should not currently be used.
* This state follows the same rules as failed except that it will never be automatically moved out of
* this state.
*/
parked;
/** Returns whether this is a state where the node is assigned to an application */
public boolean isAllocated() {
return this == reserved || this == active || this == inactive || this == failed || this == parked;
}
}
/** The mean and mean deviation (squared difference) of a bunch of numbers */
private static class Mean {
private final double mean;
private final double deviation;
private Mean(double ... numbers) {
mean = Arrays.stream(numbers).sum() / numbers.length;
deviation = Arrays.stream(numbers).map(n -> Math.pow(mean - n, 2)).sum() / numbers.length;
}
public double deviation() { return deviation; }
}
} |
Nit: Wrong indentation level | public static double skew(NodeResources totalHostCapacity, NodeResources freeHostCapacity) {
NodeResources all = totalHostCapacity.anySpeed();
NodeResources allocated = all.subtract(freeHostCapacity.anySpeed());
return new Mean(allocated.vcpu() / all.vcpu(),
allocated.memoryGb() / all.memoryGb(),
allocated.diskGb() / all.diskGb())
.deviation();
} | allocated.memoryGb() / all.memoryGb(), | public static double skew(NodeResources totalHostCapacity, NodeResources freeHostCapacity) {
NodeResources all = totalHostCapacity.anySpeed();
NodeResources allocated = all.subtract(freeHostCapacity.anySpeed());
return new Mean(allocated.vcpu() / all.vcpu(),
allocated.memoryGb() / all.memoryGb(),
allocated.diskGb() / all.diskGb())
.deviation();
} | class Node {
private final String hostname;
private final IP.Config ipConfig;
private final String id;
private final Optional<String> parentHostname;
private final Flavor flavor;
private final Status status;
private final State state;
private final NodeType type;
private final Reports reports;
private final Optional<String> modelName;
/** Record of the last event of each type happening to this node */
private final History history;
/** The current allocation of this node, if any */
private final Optional<Allocation> allocation;
/** Creates a node in the initial state (reserved) */
public static Node createDockerNode(Set<String> ipAddresses, String hostname, String parentHostname, NodeResources resources, NodeType type) {
return new Node("fake-" + hostname, new IP.Config(ipAddresses, Set.of()), hostname, Optional.of(parentHostname), new Flavor(resources), Status.initial(), State.reserved,
Optional.empty(), History.empty(), type, new Reports(), Optional.empty());
}
/** Creates a node in the initial state (provisioned) */
public static Node create(String openStackId, IP.Config ipConfig, String hostname, Optional<String> parentHostname, Optional<String> modelName, Flavor flavor, NodeType type) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, Status.initial(), State.provisioned,
Optional.empty(), History.empty(), type, new Reports(), modelName);
}
/** Creates a node. See also the {@code create} helper methods. */
public Node(String id, IP.Config ipConfig, String hostname, Optional<String> parentHostname,
Flavor flavor, Status status, State state, Optional<Allocation> allocation, History history, NodeType type,
Reports reports, Optional<String> modelName) {
Objects.requireNonNull(id, "A node must have an ID");
requireNonEmptyString(hostname, "A node must have a hostname");
Objects.requireNonNull(ipConfig, "A node must a have an IP config");
requireNonEmptyString(parentHostname, "A parent host name must be a proper value");
Objects.requireNonNull(flavor, "A node must have a flavor");
Objects.requireNonNull(status, "A node must have a status");
Objects.requireNonNull(state, "A null node state is not permitted");
Objects.requireNonNull(allocation, "A null node allocation is not permitted");
Objects.requireNonNull(history, "A null node history is not permitted");
Objects.requireNonNull(type, "A null node type is not permitted");
Objects.requireNonNull(reports, "A null reports is not permitted");
Objects.requireNonNull(modelName, "A null modelName is not permitted");
if (state == State.active)
requireNonEmpty(ipConfig.primary(), "An active node must have at least one valid IP address");
if (parentHostname.isPresent()) {
if (!ipConfig.pool().asSet().isEmpty()) throw new IllegalArgumentException("A child node cannot have an IP address pool");
if (modelName.isPresent()) throw new IllegalArgumentException("A child node cannot have model name set");
}
this.hostname = hostname;
this.ipConfig = ipConfig;
this.parentHostname = parentHostname;
this.id = id;
this.flavor = flavor;
this.status = status;
this.state = state;
this.allocation = allocation;
this.history = history;
this.type = type;
this.reports = reports;
this.modelName = modelName;
}
/** Returns the IP addresses of this node */
public Set<String> ipAddresses() { return ipConfig.primary(); }
/** Returns the IP address pool available on this node. These IP addresses are available for use by containers
* running on this node */
public IP.Pool ipAddressPool() { return ipConfig.pool(); }
/** Returns the IP config of this node */
public IP.Config ipConfig() { return ipConfig; }
/** Returns the host name of this node */
public String hostname() { return hostname; }
/**
* Unique identifier for this node. Code should not depend on this as its main purpose is to aid human operators in
* mapping a node to the corresponding cloud instance. No particular format is enforced.
*
* Formats used vary between the underlying cloud providers:
*
* - OpenStack: UUID
* - AWS: Instance ID
* - Docker containers: fake-[hostname]
*/
public String id() { return id; }
/** Returns the parent hostname for this node if this node is a docker container or a VM (i.e. it has a parent host). Otherwise, empty **/
public Optional<String> parentHostname() { return parentHostname; }
/** Returns the flavor of this node */
public Flavor flavor() { return flavor; }
/** Returns the known information about the node's ephemeral status */
public Status status() { return status; }
/** Returns the current state of this node (in the node state machine) */
public State state() { return state; }
/** Returns the type of this node */
public NodeType type() { return type; }
/** Returns the current allocation of this, if any */
public Optional<Allocation> allocation() { return allocation; }
/** Returns the current allocation when it must exist, or throw exception there is not allocation. */
private Allocation requireAllocation(String message) {
final Optional<Allocation> allocation = this.allocation;
if ( ! allocation.isPresent())
throw new IllegalStateException(message + " for " + hostname() + ": The node is unallocated");
return allocation.get();
}
/** Returns a history of the last events happening to this node */
public History history() { return history; }
/** Returns all the reports on this node. */
public Reports reports() { return reports; }
/** Returns the hardware model of this node */
public Optional<String> modelName() { return modelName; }
/**
* Returns a copy of this node with wantToRetire set to the given value and updated history.
* If given wantToRetire is equal to the current, the method is no-op.
*/
public Node withWantToRetire(boolean wantToRetire, Agent agent, Instant at) {
if (wantToRetire == status.wantToRetire()) return this;
Node node = this.with(status.withWantToRetire(wantToRetire));
if (wantToRetire)
node = node.with(history.with(new History.Event(History.Event.Type.wantToRetire, agent, at)));
return node;
}
/**
* Returns a copy of this node which is retired.
* If the node was already retired it is returned as-is.
*/
public Node retire(Agent agent, Instant retiredAt) {
Allocation allocation = requireAllocation("Cannot retire");
if (allocation.membership().retired()) return this;
return with(allocation.retire())
.with(history.with(new History.Event(History.Event.Type.retired, agent, retiredAt)));
}
/** Returns a copy of this node which is retired */
public Node retire(Instant retiredAt) {
if (status.wantToRetire())
return retire(Agent.system, retiredAt);
else
return retire(Agent.application, retiredAt);
}
/** Returns a copy of this node which is not retired */
public Node unretire() {
return with(requireAllocation("Cannot unretire").unretire());
}
/** Returns a copy of this with the restart generation set to generation */
public Node withRestart(Generation generation) {
Allocation allocation = requireAllocation("Cannot set restart generation");
return with(allocation.withRestart(generation));
}
/** Returns a node with the status assigned to the given value */
public Node with(Status status) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the type assigned to the given value */
public Node with(NodeType type) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the flavor assigned to the given value */
public Node with(Flavor flavor) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the reboot generation set to generation */
public Node withReboot(Generation generation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status.withReboot(generation), state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the openStackId set */
public Node withOpenStackId(String openStackId) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with model name set to given value */
public Node withModelName(String modelName) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.of(modelName));
}
/** Returns a copy of this with model name cleared */
public Node withoutModelName() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.empty());
}
/** Returns a copy of this with a history record saying it was detected to be down at this instant */
public Node downAt(Instant instant) {
return with(history.with(new History.Event(History.Event.Type.down, Agent.system, instant)));
}
/** Returns a copy of this with any history record saying it has been detected down removed */
public Node up() {
return with(history.without(History.Event.Type.down));
}
/** Returns a copy of this with allocation set as specified. <code>node.state</code> is *not* changed. */
public Node allocate(ApplicationId owner, ClusterMembership membership, Instant at) {
return this.with(new Allocation(owner, membership, new Generation(0, 0), false))
.with(history.with(new History.Event(History.Event.Type.reserved, Agent.application, at)));
}
/**
* Returns a copy of this node with the allocation assigned to the given allocation.
* Do not use this to allocate a node.
*/
public Node with(Allocation allocation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.of(allocation), history, type, reports, modelName);
}
/** Returns a new Node without an allocation. */
public Node withoutAllocation() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.empty(), history, type, reports, modelName);
}
/** Returns a copy of this node with IP config set to the given value. */
public Node with(IP.Config ipConfig) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the parent hostname assigned to the given value. */
public Node withParentHostname(String parentHostname) {
return new Node(id, ipConfig, hostname, Optional.of(parentHostname), flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the current reboot generation set to the given number at the given instant */
public Node withCurrentRebootGeneration(long generation, Instant instant) {
Status newStatus = status().withReboot(status().reboot().withCurrent(generation));
History newHistory = history();
if (generation > status().reboot().current())
newHistory = history.with(new History.Event(History.Event.Type.rebooted, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the current OS version set to the given version at the given instant */
public Node withCurrentOsVersion(Version version, Instant instant) {
var newStatus = status.withOsVersion(version);
var newHistory = history();
if (status.osVersion().isEmpty() || !status.osVersion().get().equals(version)) {
newHistory = history.with(new History.Event(History.Event.Type.osUpgraded, Agent.system, instant));
}
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with firmware verified at the given instant */
public Node withFirmwareVerifiedAt(Instant instant) {
var newStatus = status.withFirmwareVerifiedAt(instant);
var newHistory = history.with(new History.Event(History.Event.Type.firmwareVerified, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the given history. */
public Node with(History history) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
public Node with(Reports reports) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
private static void requireNonEmptyString(Optional<String> value, String message) {
Objects.requireNonNull(value, message);
value.ifPresent(v -> requireNonEmptyString(v, message));
}
private static void requireNonEmptyString(String value, String message) {
Objects.requireNonNull(value, message);
if (value.trim().isEmpty())
throw new IllegalArgumentException(message + ", but was '" + value + "'");
}
private static void requireNonEmpty(Set<String> values, String message) {
if (values == null || values.isEmpty()) {
throw new IllegalArgumentException(message);
}
}
/** Computes the allocation skew of a host node */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return hostname.equals(node.hostname);
}
@Override
public int hashCode() {
return Objects.hash(hostname);
}
@Override
public String toString() {
return state + " node " +
hostname +
(allocation.map(allocation1 -> " " + allocation1).orElse("")) +
(parentHostname.map(parent -> " [on: " + parent + "]").orElse(""));
}
public enum State {
/** This node has been requested (from OpenStack) but is not yet ready for use */
provisioned,
/** This node is free and ready for use */
ready,
/** This node has been reserved by an application but is not yet used by it */
reserved,
/** This node is in active use by an application */
active,
/** This node has been used by an application, is still allocated to it and retains the data needed for its allocated role */
inactive,
/** This node is not allocated to an application but may contain data which must be cleaned before it is ready */
dirty,
/** This node has failed and must be repaired or removed. The node retains any allocation data for diagnosis. */
failed,
/**
* This node should not currently be used.
* This state follows the same rules as failed except that it will never be automatically moved out of
* this state.
*/
parked;
/** Returns whether this is a state where the node is assigned to an application */
public boolean isAllocated() {
return this == reserved || this == active || this == inactive || this == failed || this == parked;
}
}
/** The mean and mean deviation (squared difference) of a bunch of numbers */
private static class Mean {
private final double mean;
private final double deviation;
private Mean(double ... numbers) {
mean = Arrays.stream(numbers).sum() / numbers.length;
deviation = Arrays.stream(numbers).map(n -> Math.pow(mean - n, 2)).sum() / numbers.length;
}
public double deviation() { return deviation; }
}
} | class Node {
private final String hostname;
private final IP.Config ipConfig;
private final String id;
private final Optional<String> parentHostname;
private final Flavor flavor;
private final Status status;
private final State state;
private final NodeType type;
private final Reports reports;
private final Optional<String> modelName;
/** Record of the last event of each type happening to this node */
private final History history;
/** The current allocation of this node, if any */
private final Optional<Allocation> allocation;
/** Creates a node in the initial state (reserved) */
public static Node createDockerNode(Set<String> ipAddresses, String hostname, String parentHostname, NodeResources resources, NodeType type) {
return new Node("fake-" + hostname, new IP.Config(ipAddresses, Set.of()), hostname, Optional.of(parentHostname), new Flavor(resources), Status.initial(), State.reserved,
Optional.empty(), History.empty(), type, new Reports(), Optional.empty());
}
/** Creates a node in the initial state (provisioned) */
public static Node create(String openStackId, IP.Config ipConfig, String hostname, Optional<String> parentHostname, Optional<String> modelName, Flavor flavor, NodeType type) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, Status.initial(), State.provisioned,
Optional.empty(), History.empty(), type, new Reports(), modelName);
}
/** Creates a node. See also the {@code create} helper methods. */
public Node(String id, IP.Config ipConfig, String hostname, Optional<String> parentHostname,
Flavor flavor, Status status, State state, Optional<Allocation> allocation, History history, NodeType type,
Reports reports, Optional<String> modelName) {
Objects.requireNonNull(id, "A node must have an ID");
requireNonEmptyString(hostname, "A node must have a hostname");
Objects.requireNonNull(ipConfig, "A node must a have an IP config");
requireNonEmptyString(parentHostname, "A parent host name must be a proper value");
Objects.requireNonNull(flavor, "A node must have a flavor");
Objects.requireNonNull(status, "A node must have a status");
Objects.requireNonNull(state, "A null node state is not permitted");
Objects.requireNonNull(allocation, "A null node allocation is not permitted");
Objects.requireNonNull(history, "A null node history is not permitted");
Objects.requireNonNull(type, "A null node type is not permitted");
Objects.requireNonNull(reports, "A null reports is not permitted");
Objects.requireNonNull(modelName, "A null modelName is not permitted");
if (state == State.active)
requireNonEmpty(ipConfig.primary(), "An active node must have at least one valid IP address");
if (parentHostname.isPresent()) {
if (!ipConfig.pool().asSet().isEmpty()) throw new IllegalArgumentException("A child node cannot have an IP address pool");
if (modelName.isPresent()) throw new IllegalArgumentException("A child node cannot have model name set");
}
this.hostname = hostname;
this.ipConfig = ipConfig;
this.parentHostname = parentHostname;
this.id = id;
this.flavor = flavor;
this.status = status;
this.state = state;
this.allocation = allocation;
this.history = history;
this.type = type;
this.reports = reports;
this.modelName = modelName;
}
/** Returns the IP addresses of this node */
public Set<String> ipAddresses() { return ipConfig.primary(); }
/** Returns the IP address pool available on this node. These IP addresses are available for use by containers
* running on this node */
public IP.Pool ipAddressPool() { return ipConfig.pool(); }
/** Returns the IP config of this node */
public IP.Config ipConfig() { return ipConfig; }
/** Returns the host name of this node */
public String hostname() { return hostname; }
/**
* Unique identifier for this node. Code should not depend on this as its main purpose is to aid human operators in
* mapping a node to the corresponding cloud instance. No particular format is enforced.
*
* Formats used vary between the underlying cloud providers:
*
* - OpenStack: UUID
* - AWS: Instance ID
* - Docker containers: fake-[hostname]
*/
public String id() { return id; }
/** Returns the parent hostname for this node if this node is a docker container or a VM (i.e. it has a parent host). Otherwise, empty **/
public Optional<String> parentHostname() { return parentHostname; }
/** Returns the flavor of this node */
public Flavor flavor() { return flavor; }
/** Returns the known information about the node's ephemeral status */
public Status status() { return status; }
/** Returns the current state of this node (in the node state machine) */
public State state() { return state; }
/** Returns the type of this node */
public NodeType type() { return type; }
/** Returns the current allocation of this, if any */
public Optional<Allocation> allocation() { return allocation; }
/** Returns the current allocation when it must exist, or throw exception there is not allocation. */
private Allocation requireAllocation(String message) {
final Optional<Allocation> allocation = this.allocation;
if ( ! allocation.isPresent())
throw new IllegalStateException(message + " for " + hostname() + ": The node is unallocated");
return allocation.get();
}
/** Returns a history of the last events happening to this node */
public History history() { return history; }
/** Returns all the reports on this node. */
public Reports reports() { return reports; }
/** Returns the hardware model of this node */
public Optional<String> modelName() { return modelName; }
/**
* Returns a copy of this node with wantToRetire set to the given value and updated history.
* If given wantToRetire is equal to the current, the method is no-op.
*/
public Node withWantToRetire(boolean wantToRetire, Agent agent, Instant at) {
if (wantToRetire == status.wantToRetire()) return this;
Node node = this.with(status.withWantToRetire(wantToRetire));
if (wantToRetire)
node = node.with(history.with(new History.Event(History.Event.Type.wantToRetire, agent, at)));
return node;
}
/**
* Returns a copy of this node which is retired.
* If the node was already retired it is returned as-is.
*/
public Node retire(Agent agent, Instant retiredAt) {
Allocation allocation = requireAllocation("Cannot retire");
if (allocation.membership().retired()) return this;
return with(allocation.retire())
.with(history.with(new History.Event(History.Event.Type.retired, agent, retiredAt)));
}
/** Returns a copy of this node which is retired */
public Node retire(Instant retiredAt) {
if (status.wantToRetire())
return retire(Agent.system, retiredAt);
else
return retire(Agent.application, retiredAt);
}
/** Returns a copy of this node which is not retired */
public Node unretire() {
return with(requireAllocation("Cannot unretire").unretire());
}
/** Returns a copy of this with the restart generation set to generation */
public Node withRestart(Generation generation) {
Allocation allocation = requireAllocation("Cannot set restart generation");
return with(allocation.withRestart(generation));
}
/** Returns a node with the status assigned to the given value */
public Node with(Status status) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the type assigned to the given value */
public Node with(NodeType type) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the flavor assigned to the given value */
public Node with(Flavor flavor) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the reboot generation set to generation */
public Node withReboot(Generation generation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status.withReboot(generation), state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the openStackId set */
public Node withOpenStackId(String openStackId) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with model name set to given value */
public Node withModelName(String modelName) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.of(modelName));
}
/** Returns a copy of this with model name cleared */
public Node withoutModelName() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.empty());
}
/** Returns a copy of this with a history record saying it was detected to be down at this instant */
public Node downAt(Instant instant) {
return with(history.with(new History.Event(History.Event.Type.down, Agent.system, instant)));
}
/** Returns a copy of this with any history record saying it has been detected down removed */
public Node up() {
return with(history.without(History.Event.Type.down));
}
/** Returns a copy of this with allocation set as specified. <code>node.state</code> is *not* changed. */
public Node allocate(ApplicationId owner, ClusterMembership membership, Instant at) {
return this.with(new Allocation(owner, membership, new Generation(0, 0), false))
.with(history.with(new History.Event(History.Event.Type.reserved, Agent.application, at)));
}
/**
* Returns a copy of this node with the allocation assigned to the given allocation.
* Do not use this to allocate a node.
*/
public Node with(Allocation allocation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.of(allocation), history, type, reports, modelName);
}
/** Returns a new Node without an allocation. */
public Node withoutAllocation() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.empty(), history, type, reports, modelName);
}
/** Returns a copy of this node with IP config set to the given value. */
public Node with(IP.Config ipConfig) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the parent hostname assigned to the given value. */
public Node withParentHostname(String parentHostname) {
return new Node(id, ipConfig, hostname, Optional.of(parentHostname), flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the current reboot generation set to the given number at the given instant */
public Node withCurrentRebootGeneration(long generation, Instant instant) {
Status newStatus = status().withReboot(status().reboot().withCurrent(generation));
History newHistory = history();
if (generation > status().reboot().current())
newHistory = history.with(new History.Event(History.Event.Type.rebooted, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the current OS version set to the given version at the given instant */
public Node withCurrentOsVersion(Version version, Instant instant) {
var newStatus = status.withOsVersion(version);
var newHistory = history();
if (status.osVersion().isEmpty() || !status.osVersion().get().equals(version)) {
newHistory = history.with(new History.Event(History.Event.Type.osUpgraded, Agent.system, instant));
}
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with firmware verified at the given instant */
public Node withFirmwareVerifiedAt(Instant instant) {
var newStatus = status.withFirmwareVerifiedAt(instant);
var newHistory = history.with(new History.Event(History.Event.Type.firmwareVerified, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the given history. */
public Node with(History history) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
public Node with(Reports reports) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
private static void requireNonEmptyString(Optional<String> value, String message) {
Objects.requireNonNull(value, message);
value.ifPresent(v -> requireNonEmptyString(v, message));
}
private static void requireNonEmptyString(String value, String message) {
Objects.requireNonNull(value, message);
if (value.trim().isEmpty())
throw new IllegalArgumentException(message + ", but was '" + value + "'");
}
private static void requireNonEmpty(Set<String> values, String message) {
if (values == null || values.isEmpty()) {
throw new IllegalArgumentException(message);
}
}
/** Computes the allocation skew of a host node */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return hostname.equals(node.hostname);
}
@Override
public int hashCode() {
return Objects.hash(hostname);
}
@Override
public String toString() {
return state + " node " +
hostname +
(allocation.map(allocation1 -> " " + allocation1).orElse("")) +
(parentHostname.map(parent -> " [on: " + parent + "]").orElse(""));
}
public enum State {
/** This node has been requested (from OpenStack) but is not yet ready for use */
provisioned,
/** This node is free and ready for use */
ready,
/** This node has been reserved by an application but is not yet used by it */
reserved,
/** This node is in active use by an application */
active,
/** This node has been used by an application, is still allocated to it and retains the data needed for its allocated role */
inactive,
/** This node is not allocated to an application but may contain data which must be cleaned before it is ready */
dirty,
/** This node has failed and must be repaired or removed. The node retains any allocation data for diagnosis. */
failed,
/**
* This node should not currently be used.
* This state follows the same rules as failed except that it will never be automatically moved out of
* this state.
*/
parked;
/** Returns whether this is a state where the node is assigned to an application */
public boolean isAllocated() {
return this == reserved || this == active || this == inactive || this == failed || this == parked;
}
}
/** The mean and mean deviation (squared difference) of a bunch of numbers */
private static class Mean {
private final double mean;
private final double deviation;
private Mean(double ... numbers) {
mean = Arrays.stream(numbers).sum() / numbers.length;
deviation = Arrays.stream(numbers).map(n -> Math.pow(mean - n, 2)).sum() / numbers.length;
}
public double deviation() { return deviation; }
}
} |
Limit this to `tenant` nodes, then you can also drop the second `if`. The first if should be under this `for` and not the inner `for`. Btw, `NodeList` implements `Iterable`, so you don't need the `.asList()` | private Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.state(Node.State.active).asList()) {
for (Node toHost : allNodes.nodeType(NodeType.host).asList()) {
if (node.parentHostname().isEmpty()) continue;
if (toHost.hostname().equals(node.parentHostname().get())) continue;
if ( ! capacity.freeCapacityOf(toHost).satisfies(node.flavor().resources())) continue;
double skewReductionAtFromHost = skewReductionByRemoving(node, allNodes.parentOf(node).get(), capacity);
double skewReductionAtToHost = skewReductionByAdding(node, toHost, capacity);
double netSkewReduction = skewReductionAtFromHost + skewReductionAtToHost;
if (netSkewReduction > bestMove.netSkewReduction)
bestMove = new Move(node, netSkewReduction);
}
}
return bestMove;
} | for (Node node : allNodes.state(Node.State.active).asList()) { | private Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.state(NodePrioritizer.ALLOCATABLE_HOST_STATES).nodeType(NodeType.host)) {
if (toHost.hostname().equals(node.parentHostname().get())) continue;
if ( ! capacity.freeCapacityOf(toHost).satisfies(node.flavor().resources())) continue;
double skewReductionAtFromHost = skewReductionByRemoving(node, allNodes.parentOf(node).get(), capacity);
double skewReductionAtToHost = skewReductionByAdding(node, toHost, capacity);
double netSkewReduction = skewReductionAtFromHost + skewReductionAtToHost;
if (netSkewReduction > bestMove.netSkewReduction)
bestMove = new Move(node, netSkewReduction);
}
}
return bestMove;
} | class Rebalancer extends Maintainer {
private final HostResourcesCalculator hostResourcesCalculator;
private final Clock clock;
public Rebalancer(NodeRepository nodeRepository, HostResourcesCalculator hostResourcesCalculator, Clock clock, Duration interval) {
super(nodeRepository, interval);
this.hostResourcesCalculator = hostResourcesCalculator;
this.clock = clock;
}
@Override
protected void maintain() {
NodeList allNodes = nodeRepository().list();
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
markWantToRetire(bestMove.node);
}
private boolean zoneIsStable(NodeList allNodes) {
List<Node> active = allNodes.state(Node.State.active).asList();
if (active.stream().anyMatch(node -> node.allocation().get().membership().retired())) return false;
if (active.stream().anyMatch(node -> node.status().wantToRetire())) return false;
return true;
}
/**
* Find the best move to reduce allocation skew and returns it.
* Returns Move.none if no moves can be made to reduce skew.
*/
private void markWantToRetire(Node node) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return;
if (nodeToMove.get().state() != Node.State.active) return;
nodeRepository().write(nodeToMove.get().withWantToRetire(true, Agent.system, clock.instant()), lock);
log.info("Marked " + nodeToMove.get() + " as want to retire to reduce allocation skew");
}
}
private double skewReductionByRemoving(Node node, Node fromHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(fromHost);
double skewBefore = Node.skew(fromHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(fromHost.flavor().resources(), freeHostCapacity.add(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private double skewReductionByAdding(Node node, Node toHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(toHost);
double skewBefore = Node.skew(toHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(toHost.flavor().resources(), freeHostCapacity.subtract(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, 0);
final Node node;
final double netSkewReduction;
Move(Node node, double netSkewReduction) {
this.node = node;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move: " +
( node == null ? "none" : node.hostname() + ", skew reduction " + netSkewReduction );
}
}
} | class Rebalancer extends Maintainer {
private final HostResourcesCalculator hostResourcesCalculator;
private final Clock clock;
public Rebalancer(NodeRepository nodeRepository, HostResourcesCalculator hostResourcesCalculator, Clock clock, Duration interval) {
super(nodeRepository, interval);
this.hostResourcesCalculator = hostResourcesCalculator;
this.clock = clock;
}
@Override
protected void maintain() {
NodeList allNodes = nodeRepository().list();
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
markWantToRetire(bestMove.node);
}
private boolean zoneIsStable(NodeList allNodes) {
NodeList active = allNodes.state(Node.State.active);
if (active.stream().anyMatch(node -> node.allocation().get().membership().retired())) return false;
if (active.stream().anyMatch(node -> node.status().wantToRetire())) return false;
return true;
}
/**
* Find the best move to reduce allocation skew and returns it.
* Returns Move.none if no moves can be made to reduce skew.
*/
private void markWantToRetire(Node node) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return;
if (nodeToMove.get().state() != Node.State.active) return;
nodeRepository().write(nodeToMove.get().withWantToRetire(true, Agent.system, clock.instant()), lock);
log.info("Marked " + nodeToMove.get() + " as want to retire to reduce allocation skew");
}
}
private double skewReductionByRemoving(Node node, Node fromHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(fromHost);
double skewBefore = Node.skew(fromHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(fromHost.flavor().resources(), freeHostCapacity.add(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private double skewReductionByAdding(Node node, Node toHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(toHost);
double skewBefore = Node.skew(toHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(toHost.flavor().resources(), freeHostCapacity.subtract(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, 0);
final Node node;
final double netSkewReduction;
Move(Node node, double netSkewReduction) {
this.node = node;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move: " +
( node == null ? "none" : node.hostname() + ", skew reduction " + netSkewReduction );
}
}
} |
This should be limited to allocatable host states https://github.com/vespa-engine/vespa/blob/3a69fa445420a96eb305b2a1a9e7372ff88acaa3/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/NodePrioritizer.java#L34 or just `active` to keep it simple. | private Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.state(Node.State.active).asList()) {
for (Node toHost : allNodes.nodeType(NodeType.host).asList()) {
if (node.parentHostname().isEmpty()) continue;
if (toHost.hostname().equals(node.parentHostname().get())) continue;
if ( ! capacity.freeCapacityOf(toHost).satisfies(node.flavor().resources())) continue;
double skewReductionAtFromHost = skewReductionByRemoving(node, allNodes.parentOf(node).get(), capacity);
double skewReductionAtToHost = skewReductionByAdding(node, toHost, capacity);
double netSkewReduction = skewReductionAtFromHost + skewReductionAtToHost;
if (netSkewReduction > bestMove.netSkewReduction)
bestMove = new Move(node, netSkewReduction);
}
}
return bestMove;
} | for (Node toHost : allNodes.nodeType(NodeType.host).asList()) { | private Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.state(NodePrioritizer.ALLOCATABLE_HOST_STATES).nodeType(NodeType.host)) {
if (toHost.hostname().equals(node.parentHostname().get())) continue;
if ( ! capacity.freeCapacityOf(toHost).satisfies(node.flavor().resources())) continue;
double skewReductionAtFromHost = skewReductionByRemoving(node, allNodes.parentOf(node).get(), capacity);
double skewReductionAtToHost = skewReductionByAdding(node, toHost, capacity);
double netSkewReduction = skewReductionAtFromHost + skewReductionAtToHost;
if (netSkewReduction > bestMove.netSkewReduction)
bestMove = new Move(node, netSkewReduction);
}
}
return bestMove;
} | class Rebalancer extends Maintainer {
private final HostResourcesCalculator hostResourcesCalculator;
private final Clock clock;
public Rebalancer(NodeRepository nodeRepository, HostResourcesCalculator hostResourcesCalculator, Clock clock, Duration interval) {
super(nodeRepository, interval);
this.hostResourcesCalculator = hostResourcesCalculator;
this.clock = clock;
}
@Override
protected void maintain() {
NodeList allNodes = nodeRepository().list();
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
markWantToRetire(bestMove.node);
}
private boolean zoneIsStable(NodeList allNodes) {
List<Node> active = allNodes.state(Node.State.active).asList();
if (active.stream().anyMatch(node -> node.allocation().get().membership().retired())) return false;
if (active.stream().anyMatch(node -> node.status().wantToRetire())) return false;
return true;
}
/**
* Find the best move to reduce allocation skew and returns it.
* Returns Move.none if no moves can be made to reduce skew.
*/
private void markWantToRetire(Node node) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return;
if (nodeToMove.get().state() != Node.State.active) return;
nodeRepository().write(nodeToMove.get().withWantToRetire(true, Agent.system, clock.instant()), lock);
log.info("Marked " + nodeToMove.get() + " as want to retire to reduce allocation skew");
}
}
private double skewReductionByRemoving(Node node, Node fromHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(fromHost);
double skewBefore = Node.skew(fromHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(fromHost.flavor().resources(), freeHostCapacity.add(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private double skewReductionByAdding(Node node, Node toHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(toHost);
double skewBefore = Node.skew(toHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(toHost.flavor().resources(), freeHostCapacity.subtract(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, 0);
final Node node;
final double netSkewReduction;
Move(Node node, double netSkewReduction) {
this.node = node;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move: " +
( node == null ? "none" : node.hostname() + ", skew reduction " + netSkewReduction );
}
}
} | class Rebalancer extends Maintainer {
private final HostResourcesCalculator hostResourcesCalculator;
private final Clock clock;
public Rebalancer(NodeRepository nodeRepository, HostResourcesCalculator hostResourcesCalculator, Clock clock, Duration interval) {
super(nodeRepository, interval);
this.hostResourcesCalculator = hostResourcesCalculator;
this.clock = clock;
}
@Override
protected void maintain() {
NodeList allNodes = nodeRepository().list();
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
markWantToRetire(bestMove.node);
}
private boolean zoneIsStable(NodeList allNodes) {
NodeList active = allNodes.state(Node.State.active);
if (active.stream().anyMatch(node -> node.allocation().get().membership().retired())) return false;
if (active.stream().anyMatch(node -> node.status().wantToRetire())) return false;
return true;
}
/**
* Find the best move to reduce allocation skew and returns it.
* Returns Move.none if no moves can be made to reduce skew.
*/
private void markWantToRetire(Node node) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return;
if (nodeToMove.get().state() != Node.State.active) return;
nodeRepository().write(nodeToMove.get().withWantToRetire(true, Agent.system, clock.instant()), lock);
log.info("Marked " + nodeToMove.get() + " as want to retire to reduce allocation skew");
}
}
private double skewReductionByRemoving(Node node, Node fromHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(fromHost);
double skewBefore = Node.skew(fromHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(fromHost.flavor().resources(), freeHostCapacity.add(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private double skewReductionByAdding(Node node, Node toHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(toHost);
double skewBefore = Node.skew(toHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(toHost.flavor().resources(), freeHostCapacity.subtract(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, 0);
final Node node;
final double netSkewReduction;
Move(Node node, double netSkewReduction) {
this.node = node;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move: " +
( node == null ? "none" : node.hostname() + ", skew reduction " + netSkewReduction );
}
}
} |
Fixed, thanks. | public static double skew(NodeResources totalHostCapacity, NodeResources freeHostCapacity) {
NodeResources all = totalHostCapacity.anySpeed();
NodeResources allocated = all.subtract(freeHostCapacity.anySpeed());
return new Mean(allocated.vcpu() / all.vcpu(),
allocated.memoryGb() / all.memoryGb(),
allocated.diskGb() / all.diskGb())
.deviation();
} | allocated.memoryGb() / all.memoryGb(), | public static double skew(NodeResources totalHostCapacity, NodeResources freeHostCapacity) {
NodeResources all = totalHostCapacity.anySpeed();
NodeResources allocated = all.subtract(freeHostCapacity.anySpeed());
return new Mean(allocated.vcpu() / all.vcpu(),
allocated.memoryGb() / all.memoryGb(),
allocated.diskGb() / all.diskGb())
.deviation();
} | class Node {
private final String hostname;
private final IP.Config ipConfig;
private final String id;
private final Optional<String> parentHostname;
private final Flavor flavor;
private final Status status;
private final State state;
private final NodeType type;
private final Reports reports;
private final Optional<String> modelName;
/** Record of the last event of each type happening to this node */
private final History history;
/** The current allocation of this node, if any */
private final Optional<Allocation> allocation;
/** Creates a node in the initial state (reserved) */
public static Node createDockerNode(Set<String> ipAddresses, String hostname, String parentHostname, NodeResources resources, NodeType type) {
return new Node("fake-" + hostname, new IP.Config(ipAddresses, Set.of()), hostname, Optional.of(parentHostname), new Flavor(resources), Status.initial(), State.reserved,
Optional.empty(), History.empty(), type, new Reports(), Optional.empty());
}
/** Creates a node in the initial state (provisioned) */
public static Node create(String openStackId, IP.Config ipConfig, String hostname, Optional<String> parentHostname, Optional<String> modelName, Flavor flavor, NodeType type) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, Status.initial(), State.provisioned,
Optional.empty(), History.empty(), type, new Reports(), modelName);
}
/** Creates a node. See also the {@code create} helper methods. */
public Node(String id, IP.Config ipConfig, String hostname, Optional<String> parentHostname,
Flavor flavor, Status status, State state, Optional<Allocation> allocation, History history, NodeType type,
Reports reports, Optional<String> modelName) {
Objects.requireNonNull(id, "A node must have an ID");
requireNonEmptyString(hostname, "A node must have a hostname");
Objects.requireNonNull(ipConfig, "A node must a have an IP config");
requireNonEmptyString(parentHostname, "A parent host name must be a proper value");
Objects.requireNonNull(flavor, "A node must have a flavor");
Objects.requireNonNull(status, "A node must have a status");
Objects.requireNonNull(state, "A null node state is not permitted");
Objects.requireNonNull(allocation, "A null node allocation is not permitted");
Objects.requireNonNull(history, "A null node history is not permitted");
Objects.requireNonNull(type, "A null node type is not permitted");
Objects.requireNonNull(reports, "A null reports is not permitted");
Objects.requireNonNull(modelName, "A null modelName is not permitted");
if (state == State.active)
requireNonEmpty(ipConfig.primary(), "An active node must have at least one valid IP address");
if (parentHostname.isPresent()) {
if (!ipConfig.pool().asSet().isEmpty()) throw new IllegalArgumentException("A child node cannot have an IP address pool");
if (modelName.isPresent()) throw new IllegalArgumentException("A child node cannot have model name set");
}
this.hostname = hostname;
this.ipConfig = ipConfig;
this.parentHostname = parentHostname;
this.id = id;
this.flavor = flavor;
this.status = status;
this.state = state;
this.allocation = allocation;
this.history = history;
this.type = type;
this.reports = reports;
this.modelName = modelName;
}
/** Returns the IP addresses of this node */
public Set<String> ipAddresses() { return ipConfig.primary(); }
/** Returns the IP address pool available on this node. These IP addresses are available for use by containers
* running on this node */
public IP.Pool ipAddressPool() { return ipConfig.pool(); }
/** Returns the IP config of this node */
public IP.Config ipConfig() { return ipConfig; }
/** Returns the host name of this node */
public String hostname() { return hostname; }
/**
* Unique identifier for this node. Code should not depend on this as its main purpose is to aid human operators in
* mapping a node to the corresponding cloud instance. No particular format is enforced.
*
* Formats used vary between the underlying cloud providers:
*
* - OpenStack: UUID
* - AWS: Instance ID
* - Docker containers: fake-[hostname]
*/
public String id() { return id; }
/** Returns the parent hostname for this node if this node is a docker container or a VM (i.e. it has a parent host). Otherwise, empty **/
public Optional<String> parentHostname() { return parentHostname; }
/** Returns the flavor of this node */
public Flavor flavor() { return flavor; }
/** Returns the known information about the node's ephemeral status */
public Status status() { return status; }
/** Returns the current state of this node (in the node state machine) */
public State state() { return state; }
/** Returns the type of this node */
public NodeType type() { return type; }
/** Returns the current allocation of this, if any */
public Optional<Allocation> allocation() { return allocation; }
/** Returns the current allocation when it must exist, or throw exception there is not allocation. */
private Allocation requireAllocation(String message) {
final Optional<Allocation> allocation = this.allocation;
if ( ! allocation.isPresent())
throw new IllegalStateException(message + " for " + hostname() + ": The node is unallocated");
return allocation.get();
}
/** Returns a history of the last events happening to this node */
public History history() { return history; }
/** Returns all the reports on this node. */
public Reports reports() { return reports; }
/** Returns the hardware model of this node */
public Optional<String> modelName() { return modelName; }
/**
* Returns a copy of this node with wantToRetire set to the given value and updated history.
* If given wantToRetire is equal to the current, the method is no-op.
*/
public Node withWantToRetire(boolean wantToRetire, Agent agent, Instant at) {
if (wantToRetire == status.wantToRetire()) return this;
Node node = this.with(status.withWantToRetire(wantToRetire));
if (wantToRetire)
node = node.with(history.with(new History.Event(History.Event.Type.wantToRetire, agent, at)));
return node;
}
/**
* Returns a copy of this node which is retired.
* If the node was already retired it is returned as-is.
*/
public Node retire(Agent agent, Instant retiredAt) {
Allocation allocation = requireAllocation("Cannot retire");
if (allocation.membership().retired()) return this;
return with(allocation.retire())
.with(history.with(new History.Event(History.Event.Type.retired, agent, retiredAt)));
}
/** Returns a copy of this node which is retired */
public Node retire(Instant retiredAt) {
if (status.wantToRetire())
return retire(Agent.system, retiredAt);
else
return retire(Agent.application, retiredAt);
}
/** Returns a copy of this node which is not retired */
public Node unretire() {
return with(requireAllocation("Cannot unretire").unretire());
}
/** Returns a copy of this with the restart generation set to generation */
public Node withRestart(Generation generation) {
Allocation allocation = requireAllocation("Cannot set restart generation");
return with(allocation.withRestart(generation));
}
/** Returns a node with the status assigned to the given value */
public Node with(Status status) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the type assigned to the given value */
public Node with(NodeType type) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the flavor assigned to the given value */
public Node with(Flavor flavor) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the reboot generation set to generation */
public Node withReboot(Generation generation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status.withReboot(generation), state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the openStackId set */
public Node withOpenStackId(String openStackId) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with model name set to given value */
public Node withModelName(String modelName) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.of(modelName));
}
/** Returns a copy of this with model name cleared */
public Node withoutModelName() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.empty());
}
/** Returns a copy of this with a history record saying it was detected to be down at this instant */
public Node downAt(Instant instant) {
return with(history.with(new History.Event(History.Event.Type.down, Agent.system, instant)));
}
/** Returns a copy of this with any history record saying it has been detected down removed */
public Node up() {
return with(history.without(History.Event.Type.down));
}
/** Returns a copy of this with allocation set as specified. <code>node.state</code> is *not* changed. */
public Node allocate(ApplicationId owner, ClusterMembership membership, Instant at) {
return this.with(new Allocation(owner, membership, new Generation(0, 0), false))
.with(history.with(new History.Event(History.Event.Type.reserved, Agent.application, at)));
}
/**
* Returns a copy of this node with the allocation assigned to the given allocation.
* Do not use this to allocate a node.
*/
public Node with(Allocation allocation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.of(allocation), history, type, reports, modelName);
}
/** Returns a new Node without an allocation. */
public Node withoutAllocation() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.empty(), history, type, reports, modelName);
}
/** Returns a copy of this node with IP config set to the given value. */
public Node with(IP.Config ipConfig) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the parent hostname assigned to the given value. */
public Node withParentHostname(String parentHostname) {
return new Node(id, ipConfig, hostname, Optional.of(parentHostname), flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the current reboot generation set to the given number at the given instant */
public Node withCurrentRebootGeneration(long generation, Instant instant) {
Status newStatus = status().withReboot(status().reboot().withCurrent(generation));
History newHistory = history();
if (generation > status().reboot().current())
newHistory = history.with(new History.Event(History.Event.Type.rebooted, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the current OS version set to the given version at the given instant */
public Node withCurrentOsVersion(Version version, Instant instant) {
var newStatus = status.withOsVersion(version);
var newHistory = history();
if (status.osVersion().isEmpty() || !status.osVersion().get().equals(version)) {
newHistory = history.with(new History.Event(History.Event.Type.osUpgraded, Agent.system, instant));
}
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with firmware verified at the given instant */
public Node withFirmwareVerifiedAt(Instant instant) {
var newStatus = status.withFirmwareVerifiedAt(instant);
var newHistory = history.with(new History.Event(History.Event.Type.firmwareVerified, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the given history. */
public Node with(History history) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
public Node with(Reports reports) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
private static void requireNonEmptyString(Optional<String> value, String message) {
Objects.requireNonNull(value, message);
value.ifPresent(v -> requireNonEmptyString(v, message));
}
private static void requireNonEmptyString(String value, String message) {
Objects.requireNonNull(value, message);
if (value.trim().isEmpty())
throw new IllegalArgumentException(message + ", but was '" + value + "'");
}
private static void requireNonEmpty(Set<String> values, String message) {
if (values == null || values.isEmpty()) {
throw new IllegalArgumentException(message);
}
}
/** Computes the allocation skew of a host node */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return hostname.equals(node.hostname);
}
@Override
public int hashCode() {
return Objects.hash(hostname);
}
@Override
public String toString() {
return state + " node " +
hostname +
(allocation.map(allocation1 -> " " + allocation1).orElse("")) +
(parentHostname.map(parent -> " [on: " + parent + "]").orElse(""));
}
public enum State {
/** This node has been requested (from OpenStack) but is not yet ready for use */
provisioned,
/** This node is free and ready for use */
ready,
/** This node has been reserved by an application but is not yet used by it */
reserved,
/** This node is in active use by an application */
active,
/** This node has been used by an application, is still allocated to it and retains the data needed for its allocated role */
inactive,
/** This node is not allocated to an application but may contain data which must be cleaned before it is ready */
dirty,
/** This node has failed and must be repaired or removed. The node retains any allocation data for diagnosis. */
failed,
/**
* This node should not currently be used.
* This state follows the same rules as failed except that it will never be automatically moved out of
* this state.
*/
parked;
/** Returns whether this is a state where the node is assigned to an application */
public boolean isAllocated() {
return this == reserved || this == active || this == inactive || this == failed || this == parked;
}
}
/** The mean and mean deviation (squared difference) of a bunch of numbers */
private static class Mean {
private final double mean;
private final double deviation;
private Mean(double ... numbers) {
mean = Arrays.stream(numbers).sum() / numbers.length;
deviation = Arrays.stream(numbers).map(n -> Math.pow(mean - n, 2)).sum() / numbers.length;
}
public double deviation() { return deviation; }
}
} | class Node {
private final String hostname;
private final IP.Config ipConfig;
private final String id;
private final Optional<String> parentHostname;
private final Flavor flavor;
private final Status status;
private final State state;
private final NodeType type;
private final Reports reports;
private final Optional<String> modelName;
/** Record of the last event of each type happening to this node */
private final History history;
/** The current allocation of this node, if any */
private final Optional<Allocation> allocation;
/** Creates a node in the initial state (reserved) */
public static Node createDockerNode(Set<String> ipAddresses, String hostname, String parentHostname, NodeResources resources, NodeType type) {
return new Node("fake-" + hostname, new IP.Config(ipAddresses, Set.of()), hostname, Optional.of(parentHostname), new Flavor(resources), Status.initial(), State.reserved,
Optional.empty(), History.empty(), type, new Reports(), Optional.empty());
}
/** Creates a node in the initial state (provisioned) */
public static Node create(String openStackId, IP.Config ipConfig, String hostname, Optional<String> parentHostname, Optional<String> modelName, Flavor flavor, NodeType type) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, Status.initial(), State.provisioned,
Optional.empty(), History.empty(), type, new Reports(), modelName);
}
/** Creates a node. See also the {@code create} helper methods. */
public Node(String id, IP.Config ipConfig, String hostname, Optional<String> parentHostname,
Flavor flavor, Status status, State state, Optional<Allocation> allocation, History history, NodeType type,
Reports reports, Optional<String> modelName) {
Objects.requireNonNull(id, "A node must have an ID");
requireNonEmptyString(hostname, "A node must have a hostname");
Objects.requireNonNull(ipConfig, "A node must a have an IP config");
requireNonEmptyString(parentHostname, "A parent host name must be a proper value");
Objects.requireNonNull(flavor, "A node must have a flavor");
Objects.requireNonNull(status, "A node must have a status");
Objects.requireNonNull(state, "A null node state is not permitted");
Objects.requireNonNull(allocation, "A null node allocation is not permitted");
Objects.requireNonNull(history, "A null node history is not permitted");
Objects.requireNonNull(type, "A null node type is not permitted");
Objects.requireNonNull(reports, "A null reports is not permitted");
Objects.requireNonNull(modelName, "A null modelName is not permitted");
if (state == State.active)
requireNonEmpty(ipConfig.primary(), "An active node must have at least one valid IP address");
if (parentHostname.isPresent()) {
if (!ipConfig.pool().asSet().isEmpty()) throw new IllegalArgumentException("A child node cannot have an IP address pool");
if (modelName.isPresent()) throw new IllegalArgumentException("A child node cannot have model name set");
}
this.hostname = hostname;
this.ipConfig = ipConfig;
this.parentHostname = parentHostname;
this.id = id;
this.flavor = flavor;
this.status = status;
this.state = state;
this.allocation = allocation;
this.history = history;
this.type = type;
this.reports = reports;
this.modelName = modelName;
}
/** Returns the IP addresses of this node */
public Set<String> ipAddresses() { return ipConfig.primary(); }
/** Returns the IP address pool available on this node. These IP addresses are available for use by containers
* running on this node */
public IP.Pool ipAddressPool() { return ipConfig.pool(); }
/** Returns the IP config of this node */
public IP.Config ipConfig() { return ipConfig; }
/** Returns the host name of this node */
public String hostname() { return hostname; }
/**
* Unique identifier for this node. Code should not depend on this as its main purpose is to aid human operators in
* mapping a node to the corresponding cloud instance. No particular format is enforced.
*
* Formats used vary between the underlying cloud providers:
*
* - OpenStack: UUID
* - AWS: Instance ID
* - Docker containers: fake-[hostname]
*/
public String id() { return id; }
/** Returns the parent hostname for this node if this node is a docker container or a VM (i.e. it has a parent host). Otherwise, empty **/
public Optional<String> parentHostname() { return parentHostname; }
/** Returns the flavor of this node */
public Flavor flavor() { return flavor; }
/** Returns the known information about the node's ephemeral status */
public Status status() { return status; }
/** Returns the current state of this node (in the node state machine) */
public State state() { return state; }
/** Returns the type of this node */
public NodeType type() { return type; }
/** Returns the current allocation of this, if any */
public Optional<Allocation> allocation() { return allocation; }
/** Returns the current allocation when it must exist, or throw exception there is not allocation. */
private Allocation requireAllocation(String message) {
final Optional<Allocation> allocation = this.allocation;
if ( ! allocation.isPresent())
throw new IllegalStateException(message + " for " + hostname() + ": The node is unallocated");
return allocation.get();
}
/** Returns a history of the last events happening to this node */
public History history() { return history; }
/** Returns all the reports on this node. */
public Reports reports() { return reports; }
/** Returns the hardware model of this node */
public Optional<String> modelName() { return modelName; }
/**
* Returns a copy of this node with wantToRetire set to the given value and updated history.
* If given wantToRetire is equal to the current, the method is no-op.
*/
public Node withWantToRetire(boolean wantToRetire, Agent agent, Instant at) {
if (wantToRetire == status.wantToRetire()) return this;
Node node = this.with(status.withWantToRetire(wantToRetire));
if (wantToRetire)
node = node.with(history.with(new History.Event(History.Event.Type.wantToRetire, agent, at)));
return node;
}
/**
* Returns a copy of this node which is retired.
* If the node was already retired it is returned as-is.
*/
public Node retire(Agent agent, Instant retiredAt) {
Allocation allocation = requireAllocation("Cannot retire");
if (allocation.membership().retired()) return this;
return with(allocation.retire())
.with(history.with(new History.Event(History.Event.Type.retired, agent, retiredAt)));
}
/** Returns a copy of this node which is retired */
public Node retire(Instant retiredAt) {
if (status.wantToRetire())
return retire(Agent.system, retiredAt);
else
return retire(Agent.application, retiredAt);
}
/** Returns a copy of this node which is not retired */
public Node unretire() {
return with(requireAllocation("Cannot unretire").unretire());
}
/** Returns a copy of this with the restart generation set to generation */
public Node withRestart(Generation generation) {
Allocation allocation = requireAllocation("Cannot set restart generation");
return with(allocation.withRestart(generation));
}
/** Returns a node with the status assigned to the given value */
public Node with(Status status) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the type assigned to the given value */
public Node with(NodeType type) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the flavor assigned to the given value */
public Node with(Flavor flavor) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the reboot generation set to generation */
public Node withReboot(Generation generation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status.withReboot(generation), state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the openStackId set */
public Node withOpenStackId(String openStackId) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with model name set to given value */
public Node withModelName(String modelName) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.of(modelName));
}
/** Returns a copy of this with model name cleared */
public Node withoutModelName() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.empty());
}
/** Returns a copy of this with a history record saying it was detected to be down at this instant */
public Node downAt(Instant instant) {
return with(history.with(new History.Event(History.Event.Type.down, Agent.system, instant)));
}
/** Returns a copy of this with any history record saying it has been detected down removed */
public Node up() {
return with(history.without(History.Event.Type.down));
}
/** Returns a copy of this with allocation set as specified. <code>node.state</code> is *not* changed. */
public Node allocate(ApplicationId owner, ClusterMembership membership, Instant at) {
return this.with(new Allocation(owner, membership, new Generation(0, 0), false))
.with(history.with(new History.Event(History.Event.Type.reserved, Agent.application, at)));
}
/**
* Returns a copy of this node with the allocation assigned to the given allocation.
* Do not use this to allocate a node.
*/
public Node with(Allocation allocation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.of(allocation), history, type, reports, modelName);
}
/** Returns a new Node without an allocation. */
public Node withoutAllocation() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.empty(), history, type, reports, modelName);
}
/** Returns a copy of this node with IP config set to the given value. */
public Node with(IP.Config ipConfig) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the parent hostname assigned to the given value. */
public Node withParentHostname(String parentHostname) {
return new Node(id, ipConfig, hostname, Optional.of(parentHostname), flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the current reboot generation set to the given number at the given instant */
public Node withCurrentRebootGeneration(long generation, Instant instant) {
Status newStatus = status().withReboot(status().reboot().withCurrent(generation));
History newHistory = history();
if (generation > status().reboot().current())
newHistory = history.with(new History.Event(History.Event.Type.rebooted, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the current OS version set to the given version at the given instant */
public Node withCurrentOsVersion(Version version, Instant instant) {
var newStatus = status.withOsVersion(version);
var newHistory = history();
if (status.osVersion().isEmpty() || !status.osVersion().get().equals(version)) {
newHistory = history.with(new History.Event(History.Event.Type.osUpgraded, Agent.system, instant));
}
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with firmware verified at the given instant */
public Node withFirmwareVerifiedAt(Instant instant) {
var newStatus = status.withFirmwareVerifiedAt(instant);
var newHistory = history.with(new History.Event(History.Event.Type.firmwareVerified, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the given history. */
public Node with(History history) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
public Node with(Reports reports) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
private static void requireNonEmptyString(Optional<String> value, String message) {
Objects.requireNonNull(value, message);
value.ifPresent(v -> requireNonEmptyString(v, message));
}
private static void requireNonEmptyString(String value, String message) {
Objects.requireNonNull(value, message);
if (value.trim().isEmpty())
throw new IllegalArgumentException(message + ", but was '" + value + "'");
}
private static void requireNonEmpty(Set<String> values, String message) {
if (values == null || values.isEmpty()) {
throw new IllegalArgumentException(message);
}
}
/** Computes the allocation skew of a host node */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return hostname.equals(node.hostname);
}
@Override
public int hashCode() {
return Objects.hash(hostname);
}
@Override
public String toString() {
return state + " node " +
hostname +
(allocation.map(allocation1 -> " " + allocation1).orElse("")) +
(parentHostname.map(parent -> " [on: " + parent + "]").orElse(""));
}
public enum State {
/** This node has been requested (from OpenStack) but is not yet ready for use */
provisioned,
/** This node is free and ready for use */
ready,
/** This node has been reserved by an application but is not yet used by it */
reserved,
/** This node is in active use by an application */
active,
/** This node has been used by an application, is still allocated to it and retains the data needed for its allocated role */
inactive,
/** This node is not allocated to an application but may contain data which must be cleaned before it is ready */
dirty,
/** This node has failed and must be repaired or removed. The node retains any allocation data for diagnosis. */
failed,
/**
* This node should not currently be used.
* This state follows the same rules as failed except that it will never be automatically moved out of
* this state.
*/
parked;
/** Returns whether this is a state where the node is assigned to an application */
public boolean isAllocated() {
return this == reserved || this == active || this == inactive || this == failed || this == parked;
}
}
/** The mean and mean deviation (squared difference) of a bunch of numbers */
private static class Mean {
private final double mean;
private final double deviation;
private Mean(double ... numbers) {
mean = Arrays.stream(numbers).sum() / numbers.length;
deviation = Arrays.stream(numbers).map(n -> Math.pow(mean - n, 2)).sum() / numbers.length;
}
public double deviation() { return deviation; }
}
} |
I don't understand what you mean. | public Node withWantToRetire(boolean wantToRetire, Agent agent, Instant at) {
if (wantToRetire == status.wantToRetire()) return this;
Node node = this.with(status.withWantToRetire(wantToRetire));
if (wantToRetire)
node = node.with(history.with(new History.Event(History.Event.Type.wantToRetire, agent, at)));
return node;
} | if (wantToRetire) | public Node withWantToRetire(boolean wantToRetire, Agent agent, Instant at) {
if (wantToRetire == status.wantToRetire()) return this;
Node node = this.with(status.withWantToRetire(wantToRetire));
if (wantToRetire)
node = node.with(history.with(new History.Event(History.Event.Type.wantToRetire, agent, at)));
return node;
} | class Node {
private final String hostname;
private final IP.Config ipConfig;
private final String id;
private final Optional<String> parentHostname;
private final Flavor flavor;
private final Status status;
private final State state;
private final NodeType type;
private final Reports reports;
private final Optional<String> modelName;
/** Record of the last event of each type happening to this node */
private final History history;
/** The current allocation of this node, if any */
private final Optional<Allocation> allocation;
/** Creates a node in the initial state (reserved) */
public static Node createDockerNode(Set<String> ipAddresses, String hostname, String parentHostname, NodeResources resources, NodeType type) {
return new Node("fake-" + hostname, new IP.Config(ipAddresses, Set.of()), hostname, Optional.of(parentHostname), new Flavor(resources), Status.initial(), State.reserved,
Optional.empty(), History.empty(), type, new Reports(), Optional.empty());
}
/** Creates a node in the initial state (provisioned) */
public static Node create(String openStackId, IP.Config ipConfig, String hostname, Optional<String> parentHostname, Optional<String> modelName, Flavor flavor, NodeType type) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, Status.initial(), State.provisioned,
Optional.empty(), History.empty(), type, new Reports(), modelName);
}
/** Creates a node. See also the {@code create} helper methods. */
public Node(String id, IP.Config ipConfig, String hostname, Optional<String> parentHostname,
Flavor flavor, Status status, State state, Optional<Allocation> allocation, History history, NodeType type,
Reports reports, Optional<String> modelName) {
Objects.requireNonNull(id, "A node must have an ID");
requireNonEmptyString(hostname, "A node must have a hostname");
Objects.requireNonNull(ipConfig, "A node must a have an IP config");
requireNonEmptyString(parentHostname, "A parent host name must be a proper value");
Objects.requireNonNull(flavor, "A node must have a flavor");
Objects.requireNonNull(status, "A node must have a status");
Objects.requireNonNull(state, "A null node state is not permitted");
Objects.requireNonNull(allocation, "A null node allocation is not permitted");
Objects.requireNonNull(history, "A null node history is not permitted");
Objects.requireNonNull(type, "A null node type is not permitted");
Objects.requireNonNull(reports, "A null reports is not permitted");
Objects.requireNonNull(modelName, "A null modelName is not permitted");
if (state == State.active)
requireNonEmpty(ipConfig.primary(), "An active node must have at least one valid IP address");
if (parentHostname.isPresent()) {
if (!ipConfig.pool().asSet().isEmpty()) throw new IllegalArgumentException("A child node cannot have an IP address pool");
if (modelName.isPresent()) throw new IllegalArgumentException("A child node cannot have model name set");
}
this.hostname = hostname;
this.ipConfig = ipConfig;
this.parentHostname = parentHostname;
this.id = id;
this.flavor = flavor;
this.status = status;
this.state = state;
this.allocation = allocation;
this.history = history;
this.type = type;
this.reports = reports;
this.modelName = modelName;
}
/** Returns the IP addresses of this node */
public Set<String> ipAddresses() { return ipConfig.primary(); }
/** Returns the IP address pool available on this node. These IP addresses are available for use by containers
* running on this node */
public IP.Pool ipAddressPool() { return ipConfig.pool(); }
/** Returns the IP config of this node */
public IP.Config ipConfig() { return ipConfig; }
/** Returns the host name of this node */
public String hostname() { return hostname; }
/**
* Unique identifier for this node. Code should not depend on this as its main purpose is to aid human operators in
* mapping a node to the corresponding cloud instance. No particular format is enforced.
*
* Formats used vary between the underlying cloud providers:
*
* - OpenStack: UUID
* - AWS: Instance ID
* - Docker containers: fake-[hostname]
*/
public String id() { return id; }
/** Returns the parent hostname for this node if this node is a docker container or a VM (i.e. it has a parent host). Otherwise, empty **/
public Optional<String> parentHostname() { return parentHostname; }
/** Returns the flavor of this node */
public Flavor flavor() { return flavor; }
/** Returns the known information about the node's ephemeral status */
public Status status() { return status; }
/** Returns the current state of this node (in the node state machine) */
public State state() { return state; }
/** Returns the type of this node */
public NodeType type() { return type; }
/** Returns the current allocation of this, if any */
public Optional<Allocation> allocation() { return allocation; }
/** Returns the current allocation when it must exist, or throw exception there is not allocation. */
private Allocation requireAllocation(String message) {
final Optional<Allocation> allocation = this.allocation;
if ( ! allocation.isPresent())
throw new IllegalStateException(message + " for " + hostname() + ": The node is unallocated");
return allocation.get();
}
/** Returns a history of the last events happening to this node */
public History history() { return history; }
/** Returns all the reports on this node. */
public Reports reports() { return reports; }
/** Returns the hardware model of this node */
public Optional<String> modelName() { return modelName; }
/**
* Returns a copy of this node with wantToRetire set to the given value and updated history.
* If given wantToRetire is equal to the current, the method is no-op.
*/
/**
* Returns a copy of this node which is retired.
* If the node was already retired it is returned as-is.
*/
public Node retire(Agent agent, Instant retiredAt) {
Allocation allocation = requireAllocation("Cannot retire");
if (allocation.membership().retired()) return this;
return with(allocation.retire())
.with(history.with(new History.Event(History.Event.Type.retired, agent, retiredAt)));
}
/** Returns a copy of this node which is retired */
public Node retire(Instant retiredAt) {
if (status.wantToRetire())
return retire(Agent.system, retiredAt);
else
return retire(Agent.application, retiredAt);
}
/** Returns a copy of this node which is not retired */
public Node unretire() {
return with(requireAllocation("Cannot unretire").unretire());
}
/** Returns a copy of this with the restart generation set to generation */
public Node withRestart(Generation generation) {
Allocation allocation = requireAllocation("Cannot set restart generation");
return with(allocation.withRestart(generation));
}
/** Returns a node with the status assigned to the given value */
public Node with(Status status) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the type assigned to the given value */
public Node with(NodeType type) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the flavor assigned to the given value */
public Node with(Flavor flavor) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the reboot generation set to generation */
public Node withReboot(Generation generation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status.withReboot(generation), state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the openStackId set */
public Node withOpenStackId(String openStackId) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with model name set to given value */
public Node withModelName(String modelName) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.of(modelName));
}
/** Returns a copy of this with model name cleared */
public Node withoutModelName() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.empty());
}
/** Returns a copy of this with a history record saying it was detected to be down at this instant */
public Node downAt(Instant instant) {
return with(history.with(new History.Event(History.Event.Type.down, Agent.system, instant)));
}
/** Returns a copy of this with any history record saying it has been detected down removed */
public Node up() {
return with(history.without(History.Event.Type.down));
}
/** Returns a copy of this with allocation set as specified. <code>node.state</code> is *not* changed. */
public Node allocate(ApplicationId owner, ClusterMembership membership, Instant at) {
return this.with(new Allocation(owner, membership, new Generation(0, 0), false))
.with(history.with(new History.Event(History.Event.Type.reserved, Agent.application, at)));
}
/**
* Returns a copy of this node with the allocation assigned to the given allocation.
* Do not use this to allocate a node.
*/
public Node with(Allocation allocation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.of(allocation), history, type, reports, modelName);
}
/** Returns a new Node without an allocation. */
public Node withoutAllocation() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.empty(), history, type, reports, modelName);
}
/** Returns a copy of this node with IP config set to the given value. */
public Node with(IP.Config ipConfig) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the parent hostname assigned to the given value. */
public Node withParentHostname(String parentHostname) {
return new Node(id, ipConfig, hostname, Optional.of(parentHostname), flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the current reboot generation set to the given number at the given instant */
public Node withCurrentRebootGeneration(long generation, Instant instant) {
Status newStatus = status().withReboot(status().reboot().withCurrent(generation));
History newHistory = history();
if (generation > status().reboot().current())
newHistory = history.with(new History.Event(History.Event.Type.rebooted, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the current OS version set to the given version at the given instant */
public Node withCurrentOsVersion(Version version, Instant instant) {
var newStatus = status.withOsVersion(version);
var newHistory = history();
if (status.osVersion().isEmpty() || !status.osVersion().get().equals(version)) {
newHistory = history.with(new History.Event(History.Event.Type.osUpgraded, Agent.system, instant));
}
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with firmware verified at the given instant */
public Node withFirmwareVerifiedAt(Instant instant) {
var newStatus = status.withFirmwareVerifiedAt(instant);
var newHistory = history.with(new History.Event(History.Event.Type.firmwareVerified, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the given history. */
public Node with(History history) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
public Node with(Reports reports) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
private static void requireNonEmptyString(Optional<String> value, String message) {
Objects.requireNonNull(value, message);
value.ifPresent(v -> requireNonEmptyString(v, message));
}
private static void requireNonEmptyString(String value, String message) {
Objects.requireNonNull(value, message);
if (value.trim().isEmpty())
throw new IllegalArgumentException(message + ", but was '" + value + "'");
}
private static void requireNonEmpty(Set<String> values, String message) {
if (values == null || values.isEmpty()) {
throw new IllegalArgumentException(message);
}
}
/** Computes the allocation skew of a host node */
public static double skew(NodeResources totalHostCapacity, NodeResources freeHostCapacity) {
NodeResources all = totalHostCapacity.anySpeed();
NodeResources allocated = all.subtract(freeHostCapacity.anySpeed());
return new Mean(allocated.vcpu() / all.vcpu(),
allocated.memoryGb() / all.memoryGb(),
allocated.diskGb() / all.diskGb())
.deviation();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return hostname.equals(node.hostname);
}
@Override
public int hashCode() {
return Objects.hash(hostname);
}
@Override
public String toString() {
return state + " node " +
hostname +
(allocation.map(allocation1 -> " " + allocation1).orElse("")) +
(parentHostname.map(parent -> " [on: " + parent + "]").orElse(""));
}
public enum State {
/** This node has been requested (from OpenStack) but is not yet ready for use */
provisioned,
/** This node is free and ready for use */
ready,
/** This node has been reserved by an application but is not yet used by it */
reserved,
/** This node is in active use by an application */
active,
/** This node has been used by an application, is still allocated to it and retains the data needed for its allocated role */
inactive,
/** This node is not allocated to an application but may contain data which must be cleaned before it is ready */
dirty,
/** This node has failed and must be repaired or removed. The node retains any allocation data for diagnosis. */
failed,
/**
* This node should not currently be used.
* This state follows the same rules as failed except that it will never be automatically moved out of
* this state.
*/
parked;
/** Returns whether this is a state where the node is assigned to an application */
public boolean isAllocated() {
return this == reserved || this == active || this == inactive || this == failed || this == parked;
}
}
/** The mean and mean deviation (squared difference) of a bunch of numbers */
private static class Mean {
private final double mean;
private final double deviation;
private Mean(double ... numbers) {
mean = Arrays.stream(numbers).sum() / numbers.length;
deviation = Arrays.stream(numbers).map(n -> Math.pow(mean - n, 2)).sum() / numbers.length;
}
public double deviation() { return deviation; }
}
} | class Node {
private final String hostname;
private final IP.Config ipConfig;
private final String id;
private final Optional<String> parentHostname;
private final Flavor flavor;
private final Status status;
private final State state;
private final NodeType type;
private final Reports reports;
private final Optional<String> modelName;
/** Record of the last event of each type happening to this node */
private final History history;
/** The current allocation of this node, if any */
private final Optional<Allocation> allocation;
/** Creates a node in the initial state (reserved) */
public static Node createDockerNode(Set<String> ipAddresses, String hostname, String parentHostname, NodeResources resources, NodeType type) {
return new Node("fake-" + hostname, new IP.Config(ipAddresses, Set.of()), hostname, Optional.of(parentHostname), new Flavor(resources), Status.initial(), State.reserved,
Optional.empty(), History.empty(), type, new Reports(), Optional.empty());
}
/** Creates a node in the initial state (provisioned) */
public static Node create(String openStackId, IP.Config ipConfig, String hostname, Optional<String> parentHostname, Optional<String> modelName, Flavor flavor, NodeType type) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, Status.initial(), State.provisioned,
Optional.empty(), History.empty(), type, new Reports(), modelName);
}
/** Creates a node. See also the {@code create} helper methods. */
public Node(String id, IP.Config ipConfig, String hostname, Optional<String> parentHostname,
Flavor flavor, Status status, State state, Optional<Allocation> allocation, History history, NodeType type,
Reports reports, Optional<String> modelName) {
Objects.requireNonNull(id, "A node must have an ID");
requireNonEmptyString(hostname, "A node must have a hostname");
Objects.requireNonNull(ipConfig, "A node must a have an IP config");
requireNonEmptyString(parentHostname, "A parent host name must be a proper value");
Objects.requireNonNull(flavor, "A node must have a flavor");
Objects.requireNonNull(status, "A node must have a status");
Objects.requireNonNull(state, "A null node state is not permitted");
Objects.requireNonNull(allocation, "A null node allocation is not permitted");
Objects.requireNonNull(history, "A null node history is not permitted");
Objects.requireNonNull(type, "A null node type is not permitted");
Objects.requireNonNull(reports, "A null reports is not permitted");
Objects.requireNonNull(modelName, "A null modelName is not permitted");
if (state == State.active)
requireNonEmpty(ipConfig.primary(), "An active node must have at least one valid IP address");
if (parentHostname.isPresent()) {
if (!ipConfig.pool().asSet().isEmpty()) throw new IllegalArgumentException("A child node cannot have an IP address pool");
if (modelName.isPresent()) throw new IllegalArgumentException("A child node cannot have model name set");
}
this.hostname = hostname;
this.ipConfig = ipConfig;
this.parentHostname = parentHostname;
this.id = id;
this.flavor = flavor;
this.status = status;
this.state = state;
this.allocation = allocation;
this.history = history;
this.type = type;
this.reports = reports;
this.modelName = modelName;
}
/** Returns the IP addresses of this node */
public Set<String> ipAddresses() { return ipConfig.primary(); }
/** Returns the IP address pool available on this node. These IP addresses are available for use by containers
* running on this node */
public IP.Pool ipAddressPool() { return ipConfig.pool(); }
/** Returns the IP config of this node */
public IP.Config ipConfig() { return ipConfig; }
/** Returns the host name of this node */
public String hostname() { return hostname; }
/**
* Unique identifier for this node. Code should not depend on this as its main purpose is to aid human operators in
* mapping a node to the corresponding cloud instance. No particular format is enforced.
*
* Formats used vary between the underlying cloud providers:
*
* - OpenStack: UUID
* - AWS: Instance ID
* - Docker containers: fake-[hostname]
*/
public String id() { return id; }
/** Returns the parent hostname for this node if this node is a docker container or a VM (i.e. it has a parent host). Otherwise, empty **/
public Optional<String> parentHostname() { return parentHostname; }
/** Returns the flavor of this node */
public Flavor flavor() { return flavor; }
/** Returns the known information about the node's ephemeral status */
public Status status() { return status; }
/** Returns the current state of this node (in the node state machine) */
public State state() { return state; }
/** Returns the type of this node */
public NodeType type() { return type; }
/** Returns the current allocation of this, if any */
public Optional<Allocation> allocation() { return allocation; }
/** Returns the current allocation when it must exist, or throw exception there is not allocation. */
private Allocation requireAllocation(String message) {
final Optional<Allocation> allocation = this.allocation;
if ( ! allocation.isPresent())
throw new IllegalStateException(message + " for " + hostname() + ": The node is unallocated");
return allocation.get();
}
/** Returns a history of the last events happening to this node */
public History history() { return history; }
/** Returns all the reports on this node. */
public Reports reports() { return reports; }
/** Returns the hardware model of this node */
public Optional<String> modelName() { return modelName; }
/**
* Returns a copy of this node with wantToRetire set to the given value and updated history.
* If given wantToRetire is equal to the current, the method is no-op.
*/
/**
* Returns a copy of this node which is retired.
* If the node was already retired it is returned as-is.
*/
public Node retire(Agent agent, Instant retiredAt) {
Allocation allocation = requireAllocation("Cannot retire");
if (allocation.membership().retired()) return this;
return with(allocation.retire())
.with(history.with(new History.Event(History.Event.Type.retired, agent, retiredAt)));
}
/** Returns a copy of this node which is retired */
public Node retire(Instant retiredAt) {
if (status.wantToRetire())
return retire(Agent.system, retiredAt);
else
return retire(Agent.application, retiredAt);
}
/** Returns a copy of this node which is not retired */
public Node unretire() {
return with(requireAllocation("Cannot unretire").unretire());
}
/** Returns a copy of this with the restart generation set to generation */
public Node withRestart(Generation generation) {
Allocation allocation = requireAllocation("Cannot set restart generation");
return with(allocation.withRestart(generation));
}
/** Returns a node with the status assigned to the given value */
public Node with(Status status) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the type assigned to the given value */
public Node with(NodeType type) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a node with the flavor assigned to the given value */
public Node with(Flavor flavor) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the reboot generation set to generation */
public Node withReboot(Generation generation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status.withReboot(generation), state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with the openStackId set */
public Node withOpenStackId(String openStackId) {
return new Node(openStackId, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
/** Returns a copy of this with model name set to given value */
public Node withModelName(String modelName) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.of(modelName));
}
/** Returns a copy of this with model name cleared */
public Node withoutModelName() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, Optional.empty());
}
/** Returns a copy of this with a history record saying it was detected to be down at this instant */
public Node downAt(Instant instant) {
return with(history.with(new History.Event(History.Event.Type.down, Agent.system, instant)));
}
/** Returns a copy of this with any history record saying it has been detected down removed */
public Node up() {
return with(history.without(History.Event.Type.down));
}
/** Returns a copy of this with allocation set as specified. <code>node.state</code> is *not* changed. */
public Node allocate(ApplicationId owner, ClusterMembership membership, Instant at) {
return this.with(new Allocation(owner, membership, new Generation(0, 0), false))
.with(history.with(new History.Event(History.Event.Type.reserved, Agent.application, at)));
}
/**
* Returns a copy of this node with the allocation assigned to the given allocation.
* Do not use this to allocate a node.
*/
public Node with(Allocation allocation) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.of(allocation), history, type, reports, modelName);
}
/** Returns a new Node without an allocation. */
public Node withoutAllocation() {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
Optional.empty(), history, type, reports, modelName);
}
/** Returns a copy of this node with IP config set to the given value. */
public Node with(IP.Config ipConfig) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the parent hostname assigned to the given value. */
public Node withParentHostname(String parentHostname) {
return new Node(id, ipConfig, hostname, Optional.of(parentHostname), flavor, status, state,
allocation, history, type, reports, modelName);
}
/** Returns a copy of this node with the current reboot generation set to the given number at the given instant */
public Node withCurrentRebootGeneration(long generation, Instant instant) {
Status newStatus = status().withReboot(status().reboot().withCurrent(generation));
History newHistory = history();
if (generation > status().reboot().current())
newHistory = history.with(new History.Event(History.Event.Type.rebooted, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the current OS version set to the given version at the given instant */
public Node withCurrentOsVersion(Version version, Instant instant) {
var newStatus = status.withOsVersion(version);
var newHistory = history();
if (status.osVersion().isEmpty() || !status.osVersion().get().equals(version)) {
newHistory = history.with(new History.Event(History.Event.Type.osUpgraded, Agent.system, instant));
}
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with firmware verified at the given instant */
public Node withFirmwareVerifiedAt(Instant instant) {
var newStatus = status.withFirmwareVerifiedAt(instant);
var newHistory = history.with(new History.Event(History.Event.Type.firmwareVerified, Agent.system, instant));
return this.with(newStatus).with(newHistory);
}
/** Returns a copy of this node with the given history. */
public Node with(History history) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
public Node with(Reports reports) {
return new Node(id, ipConfig, hostname, parentHostname, flavor, status, state, allocation, history, type, reports, modelName);
}
private static void requireNonEmptyString(Optional<String> value, String message) {
Objects.requireNonNull(value, message);
value.ifPresent(v -> requireNonEmptyString(v, message));
}
private static void requireNonEmptyString(String value, String message) {
Objects.requireNonNull(value, message);
if (value.trim().isEmpty())
throw new IllegalArgumentException(message + ", but was '" + value + "'");
}
private static void requireNonEmpty(Set<String> values, String message) {
if (values == null || values.isEmpty()) {
throw new IllegalArgumentException(message);
}
}
/** Computes the allocation skew of a host node */
public static double skew(NodeResources totalHostCapacity, NodeResources freeHostCapacity) {
NodeResources all = totalHostCapacity.anySpeed();
NodeResources allocated = all.subtract(freeHostCapacity.anySpeed());
return new Mean(allocated.vcpu() / all.vcpu(),
allocated.memoryGb() / all.memoryGb(),
allocated.diskGb() / all.diskGb())
.deviation();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return hostname.equals(node.hostname);
}
@Override
public int hashCode() {
return Objects.hash(hostname);
}
@Override
public String toString() {
return state + " node " +
hostname +
(allocation.map(allocation1 -> " " + allocation1).orElse("")) +
(parentHostname.map(parent -> " [on: " + parent + "]").orElse(""));
}
public enum State {
/** This node has been requested (from OpenStack) but is not yet ready for use */
provisioned,
/** This node is free and ready for use */
ready,
/** This node has been reserved by an application but is not yet used by it */
reserved,
/** This node is in active use by an application */
active,
/** This node has been used by an application, is still allocated to it and retains the data needed for its allocated role */
inactive,
/** This node is not allocated to an application but may contain data which must be cleaned before it is ready */
dirty,
/** This node has failed and must be repaired or removed. The node retains any allocation data for diagnosis. */
failed,
/**
* This node should not currently be used.
* This state follows the same rules as failed except that it will never be automatically moved out of
* this state.
*/
parked;
/** Returns whether this is a state where the node is assigned to an application */
public boolean isAllocated() {
return this == reserved || this == active || this == inactive || this == failed || this == parked;
}
}
/** The mean and mean deviation (squared difference) of a bunch of numbers */
private static class Mean {
private final double mean;
private final double deviation;
private Mean(double ... numbers) {
mean = Arrays.stream(numbers).sum() / numbers.length;
deviation = Arrays.stream(numbers).map(n -> Math.pow(mean - n, 2)).sum() / numbers.length;
}
public double deviation() { return deviation; }
}
} |
> Limit this to tenant nodes, then you can also drop the second if I'd rather keep it there as long as the code otherwise supports tenant nodes without parents. The other 2: Thanks, done. | private Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.state(Node.State.active).asList()) {
for (Node toHost : allNodes.nodeType(NodeType.host).asList()) {
if (node.parentHostname().isEmpty()) continue;
if (toHost.hostname().equals(node.parentHostname().get())) continue;
if ( ! capacity.freeCapacityOf(toHost).satisfies(node.flavor().resources())) continue;
double skewReductionAtFromHost = skewReductionByRemoving(node, allNodes.parentOf(node).get(), capacity);
double skewReductionAtToHost = skewReductionByAdding(node, toHost, capacity);
double netSkewReduction = skewReductionAtFromHost + skewReductionAtToHost;
if (netSkewReduction > bestMove.netSkewReduction)
bestMove = new Move(node, netSkewReduction);
}
}
return bestMove;
} | for (Node node : allNodes.state(Node.State.active).asList()) { | private Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.state(NodePrioritizer.ALLOCATABLE_HOST_STATES).nodeType(NodeType.host)) {
if (toHost.hostname().equals(node.parentHostname().get())) continue;
if ( ! capacity.freeCapacityOf(toHost).satisfies(node.flavor().resources())) continue;
double skewReductionAtFromHost = skewReductionByRemoving(node, allNodes.parentOf(node).get(), capacity);
double skewReductionAtToHost = skewReductionByAdding(node, toHost, capacity);
double netSkewReduction = skewReductionAtFromHost + skewReductionAtToHost;
if (netSkewReduction > bestMove.netSkewReduction)
bestMove = new Move(node, netSkewReduction);
}
}
return bestMove;
} | class Rebalancer extends Maintainer {
private final HostResourcesCalculator hostResourcesCalculator;
private final Clock clock;
public Rebalancer(NodeRepository nodeRepository, HostResourcesCalculator hostResourcesCalculator, Clock clock, Duration interval) {
super(nodeRepository, interval);
this.hostResourcesCalculator = hostResourcesCalculator;
this.clock = clock;
}
@Override
protected void maintain() {
NodeList allNodes = nodeRepository().list();
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
markWantToRetire(bestMove.node);
}
private boolean zoneIsStable(NodeList allNodes) {
List<Node> active = allNodes.state(Node.State.active).asList();
if (active.stream().anyMatch(node -> node.allocation().get().membership().retired())) return false;
if (active.stream().anyMatch(node -> node.status().wantToRetire())) return false;
return true;
}
/**
* Find the best move to reduce allocation skew and returns it.
* Returns Move.none if no moves can be made to reduce skew.
*/
private void markWantToRetire(Node node) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return;
if (nodeToMove.get().state() != Node.State.active) return;
nodeRepository().write(nodeToMove.get().withWantToRetire(true, Agent.system, clock.instant()), lock);
log.info("Marked " + nodeToMove.get() + " as want to retire to reduce allocation skew");
}
}
private double skewReductionByRemoving(Node node, Node fromHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(fromHost);
double skewBefore = Node.skew(fromHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(fromHost.flavor().resources(), freeHostCapacity.add(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private double skewReductionByAdding(Node node, Node toHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(toHost);
double skewBefore = Node.skew(toHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(toHost.flavor().resources(), freeHostCapacity.subtract(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, 0);
final Node node;
final double netSkewReduction;
Move(Node node, double netSkewReduction) {
this.node = node;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move: " +
( node == null ? "none" : node.hostname() + ", skew reduction " + netSkewReduction );
}
}
} | class Rebalancer extends Maintainer {
private final HostResourcesCalculator hostResourcesCalculator;
private final Clock clock;
public Rebalancer(NodeRepository nodeRepository, HostResourcesCalculator hostResourcesCalculator, Clock clock, Duration interval) {
super(nodeRepository, interval);
this.hostResourcesCalculator = hostResourcesCalculator;
this.clock = clock;
}
@Override
protected void maintain() {
NodeList allNodes = nodeRepository().list();
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
markWantToRetire(bestMove.node);
}
private boolean zoneIsStable(NodeList allNodes) {
NodeList active = allNodes.state(Node.State.active);
if (active.stream().anyMatch(node -> node.allocation().get().membership().retired())) return false;
if (active.stream().anyMatch(node -> node.status().wantToRetire())) return false;
return true;
}
/**
* Find the best move to reduce allocation skew and returns it.
* Returns Move.none if no moves can be made to reduce skew.
*/
private void markWantToRetire(Node node) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return;
if (nodeToMove.get().state() != Node.State.active) return;
nodeRepository().write(nodeToMove.get().withWantToRetire(true, Agent.system, clock.instant()), lock);
log.info("Marked " + nodeToMove.get() + " as want to retire to reduce allocation skew");
}
}
private double skewReductionByRemoving(Node node, Node fromHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(fromHost);
double skewBefore = Node.skew(fromHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(fromHost.flavor().resources(), freeHostCapacity.add(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private double skewReductionByAdding(Node node, Node toHost, DockerHostCapacity capacity) {
NodeResources freeHostCapacity = capacity.freeCapacityOf(toHost);
double skewBefore = Node.skew(toHost.flavor().resources(), freeHostCapacity);
double skewAfter = Node.skew(toHost.flavor().resources(), freeHostCapacity.subtract(node.flavor().resources().anySpeed()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, 0);
final Node node;
final double netSkewReduction;
Move(Node node, double netSkewReduction) {
this.node = node;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move: " +
( node == null ? "none" : node.hostname() + ", skew reduction " + netSkewReduction );
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.