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 |
|---|---|---|---|---|---|
Operator setting `wantToRetire=false` wont update the history => `OperatorChangeApplicationMaintainer` wont pick up the change => Will have to wait for next regular deployment to undo a `wantToRetire` request. Probably not a big deal, but worth noting this consequence. | 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; }
}
} |
should extract the error-code too? | private static void verifySuccess(HttpResponse response, FlagsTarget target, FlagId flagId) throws IOException {
if (!success(response)) {
String message = getErrorMessage(response);
throw new FlagsException(response.getStatusLine().getStatusCode(), target, flagId, message);
}
} | String message = getErrorMessage(response); | private static void verifySuccess(HttpResponse response, FlagsTarget target, FlagId flagId) throws IOException {
if (!success(response)) {
throw createFlagsException(response, target, flagId);
}
} | class FlagsClient {
private static final String FLAGS_V1_PATH = "/flags/v1";
private static final ObjectMapper mapper = new ObjectMapper();
private final CloseableHttpClient client;
FlagsClient(ServiceIdentityProvider identityProvider, Set<FlagsTarget> targets) {
this.client = createClient(identityProvider, targets);
}
List<FlagData> listFlagData(FlagsTarget target) throws FlagsException, UncheckedIOException {
HttpGet request = new HttpGet(createUri(target, "/data"));
return executeRequest(request, response -> {
verifySuccess(response, target, null);
return FlagData.deserializeList(EntityUtils.toByteArray(response.getEntity()));
});
}
void putFlagData(FlagsTarget target, FlagData flagData) throws FlagsException, UncheckedIOException {
HttpPut request = new HttpPut(createUri(target, "/data/" + flagData.id().toString()));
request.setEntity(jsonContent(flagData.serializeToJson()));
executeRequest(request, response -> {
verifySuccess(response, target, flagData.id());
return null;
});
}
void deleteFlagData(FlagsTarget target, FlagId flagId) throws FlagsException, UncheckedIOException {
HttpDelete request = new HttpDelete(createUri(target, "/data/" + flagId.toString()));
executeRequest(request, response -> {
verifySuccess(response, target, flagId);
return null;
});
}
private static CloseableHttpClient createClient(ServiceIdentityProvider identityProvider, Set<FlagsTarget> targets) {
return HttpClientBuilder.create()
.setUserAgent("controller-flags-v1-client")
.setRetryHandler(new DefaultHttpRequestRetryHandler(5, /*retry on non-idempotent requests*/true))
.setSslcontext(identityProvider.getIdentitySslContext())
.setSSLHostnameVerifier(new FlagTargetsHostnameVerifier(targets))
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout((int) Duration.ofSeconds(10).toMillis())
.setConnectionRequestTimeout((int) Duration.ofSeconds(10).toMillis())
.setSocketTimeout((int) Duration.ofSeconds(20).toMillis())
.build())
.setMaxConnPerRoute(2)
.setMaxConnTotal(100)
.build();
}
private <T> T executeRequest(HttpUriRequest request, ResponseHandler<T> handler) {
try {
return client.execute(request, handler);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static URI createUri(FlagsTarget target, String subPath) {
try {
return new URIBuilder(target.endpoint()).setPath(FLAGS_V1_PATH + subPath).build();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
private static String getErrorMessage(HttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
if (ContentType.get(entity).getMimeType().equals(ContentType.APPLICATION_JSON.getMimeType())) {
WireErrorResponse errorResponse = mapper.readValue(content, WireErrorResponse.class);
return errorResponse.message;
}
return content;
}
private static boolean success(HttpResponse response) {
return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
}
private static StringEntity jsonContent(String json) {
return new StringEntity(json, ContentType.APPLICATION_JSON);
}
private static class FlagTargetsHostnameVerifier implements HostnameVerifier {
private final AthenzIdentityVerifier athenzVerifier;
FlagTargetsHostnameVerifier(Set<FlagsTarget> targets) {
this.athenzVerifier = createAthenzIdentityVerifier(targets);
}
private static AthenzIdentityVerifier createAthenzIdentityVerifier(Set<FlagsTarget> targets) {
Set<AthenzIdentity> identities = targets.stream()
.flatMap(target -> target.athenzHttpsIdentity().stream())
.collect(toSet());
return new AthenzIdentityVerifier(identities);
}
@Override
public boolean verify(String hostname, SSLSession session) {
return "localhost".equals(hostname) /* for controllers */ || athenzVerifier.verify(hostname, session);
}
}
static class FlagsException extends RuntimeException {
private FlagsException(int statusCode, FlagsTarget target, String responseMessage) {
this(statusCode, target, null, responseMessage);
}
private FlagsException(int statusCode, FlagsTarget target, FlagId flagId, String responseMessage) {
super(createErrorMessage(statusCode, target, flagId, responseMessage));
}
private static String createErrorMessage(int statusCode, FlagsTarget target, FlagId flagId, String responseMessage) {
StringBuilder builder = new StringBuilder()
.append("Received '").append(statusCode).append("' from '").append(target.endpoint().getHost()).append("'");
if (flagId != null) {
builder.append("' for flag '").append(flagId).append("'");
}
return builder.append(": ").append(responseMessage).toString();
}
}
} | class FlagsClient {
private static final String FLAGS_V1_PATH = "/flags/v1";
private static final ObjectMapper mapper = new ObjectMapper();
private final CloseableHttpClient client;
FlagsClient(ServiceIdentityProvider identityProvider, Set<FlagsTarget> targets) {
this.client = createClient(identityProvider, targets);
}
List<FlagData> listFlagData(FlagsTarget target) throws FlagsException, UncheckedIOException {
HttpGet request = new HttpGet(createUri(target, "/data"));
return executeRequest(request, response -> {
verifySuccess(response, target, null);
return FlagData.deserializeList(EntityUtils.toByteArray(response.getEntity()));
});
}
void putFlagData(FlagsTarget target, FlagData flagData) throws FlagsException, UncheckedIOException {
HttpPut request = new HttpPut(createUri(target, "/data/" + flagData.id().toString()));
request.setEntity(jsonContent(flagData.serializeToJson()));
executeRequest(request, response -> {
verifySuccess(response, target, flagData.id());
return null;
});
}
void deleteFlagData(FlagsTarget target, FlagId flagId) throws FlagsException, UncheckedIOException {
HttpDelete request = new HttpDelete(createUri(target, "/data/" + flagId.toString()));
executeRequest(request, response -> {
verifySuccess(response, target, flagId);
return null;
});
}
private static CloseableHttpClient createClient(ServiceIdentityProvider identityProvider, Set<FlagsTarget> targets) {
return HttpClientBuilder.create()
.setUserAgent("controller-flags-v1-client")
.setRetryHandler(new DefaultHttpRequestRetryHandler(5, /*retry on non-idempotent requests*/true))
.setSslcontext(identityProvider.getIdentitySslContext())
.setSSLHostnameVerifier(new FlagTargetsHostnameVerifier(targets))
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout((int) Duration.ofSeconds(10).toMillis())
.setConnectionRequestTimeout((int) Duration.ofSeconds(10).toMillis())
.setSocketTimeout((int) Duration.ofSeconds(20).toMillis())
.build())
.setMaxConnPerRoute(2)
.setMaxConnTotal(100)
.build();
}
private <T> T executeRequest(HttpUriRequest request, ResponseHandler<T> handler) {
try {
return client.execute(request, handler);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static URI createUri(FlagsTarget target, String subPath) {
try {
return new URIBuilder(target.endpoint()).setPath(FLAGS_V1_PATH + subPath).build();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
private static FlagsException createFlagsException(HttpResponse response, FlagsTarget target, FlagId flagId) throws IOException {
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
int statusCode = response.getStatusLine().getStatusCode();
if (ContentType.get(entity).getMimeType().equals(ContentType.APPLICATION_JSON.getMimeType())) {
WireErrorResponse error = mapper.readValue(content, WireErrorResponse.class);
return new FlagsException(statusCode, target, flagId, error.errorCode, error.message);
} else {
return new FlagsException(statusCode, target, flagId, null, content);
}
}
private static boolean success(HttpResponse response) {
return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
}
private static StringEntity jsonContent(String json) {
return new StringEntity(json, ContentType.APPLICATION_JSON);
}
private static class FlagTargetsHostnameVerifier implements HostnameVerifier {
private final AthenzIdentityVerifier athenzVerifier;
FlagTargetsHostnameVerifier(Set<FlagsTarget> targets) {
this.athenzVerifier = createAthenzIdentityVerifier(targets);
}
private static AthenzIdentityVerifier createAthenzIdentityVerifier(Set<FlagsTarget> targets) {
Set<AthenzIdentity> identities = targets.stream()
.flatMap(target -> target.athenzHttpsIdentity().stream())
.collect(toSet());
return new AthenzIdentityVerifier(identities);
}
@Override
public boolean verify(String hostname, SSLSession session) {
return "localhost".equals(hostname) /* for controllers */ || athenzVerifier.verify(hostname, session);
}
}
static class FlagsException extends RuntimeException {
private FlagsException(int statusCode, FlagsTarget target, FlagId flagId, String errorCode, String errorMessage) {
super(createErrorMessage(statusCode, target, flagId, errorCode, errorMessage));
}
private static String createErrorMessage(int statusCode, FlagsTarget target, FlagId flagId, String errorCode, String errorMessage) {
StringBuilder builder = new StringBuilder().append("Received ").append(statusCode);
if (errorCode != null) {
builder.append('/').append(errorCode);
}
builder.append(" from '").append(target.endpoint().getHost()).append("'");
if (flagId != null) {
builder.append("' for flag '").append(flagId).append("'");
}
return builder.append(": ").append(errorMessage).toString();
}
}
} |
Ah, right. Ok, if it becomes a problem I think we need another history entry type for it. It's just wrong to insert a wantToRetire history entry when we want the opposite. | 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; }
}
} |
> I'd rather keep it there as long as the code otherwise supports tenant nodes without parents. The first `if` allows for that already? Anyway, limiting this to `tenant`s is a good idea anyway to prevent the `Rebalancer` from attempting to retiring a `proxy`/`configserver` node (they are technically overallocated in AWS, there should be skew). | 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 );
}
}
} |
> limiting this to tenants is a good idea Good point. Another PR incoming for that. (The second if is to not consider moving a node to the same host.) | 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 );
}
}
} |
https://github.com/vespa-engine/vespa/pull/11011 | 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 );
}
}
} |
Nested ternary 😞 Also, extracting variables for the magic constants would make this more readable. E.g. `oneMinute` instead of `60e3` / `60_000`. | private int numberOfApplicationsToUpgrade() {
long intervalMillis = maintenanceInterval().dividedBy(Math.max(1, controller().curator().cluster().size())).toMillis();
long intervalStart = ((controller().clock().millis() + intervalMillis / 2) / intervalMillis) * intervalMillis;
long upgradeIntervalMillis = upgradesPerMinute() > 60e3 ? 1 : upgradesPerMinute() < 60e-3 ? 1_000_000 : (long) (60_000 / upgradesPerMinute());
return (int) ((intervalStart + intervalMillis) / upgradeIntervalMillis - intervalStart / intervalMillis);
} | long upgradeIntervalMillis = upgradesPerMinute() > 60e3 ? 1 : upgradesPerMinute() < 60e-3 ? 1_000_000 : (long) (60_000 / upgradesPerMinute()); | private int numberOfApplicationsToUpgrade() {
return numberOfApplicationsToUpgrade(maintenanceInterval().dividedBy(Math.max(1, controller().curator().cluster().size())).toMillis(),
controller().clock().millis(),
upgradesPerMinute());
} | class Upgrader extends Maintainer {
private static final Logger log = Logger.getLogger(Upgrader.class.getName());
private final CuratorDb curator;
public Upgrader(Controller controller, Duration interval, JobControl jobControl, CuratorDb curator) {
super(controller, interval, jobControl);
this.curator = Objects.requireNonNull(curator, "curator cannot be null");
}
/**
* Schedule application upgrades. Note that this implementation must be idempotent.
*/
@Override
public void maintain() {
Optional<Version> canaryTarget = controller().versionStatus().systemVersion().map(VespaVersion::versionNumber);
Collection<Version> defaultTargets = targetVersions(Confidence.normal);
Collection<Version> conservativeTargets = targetVersions(Confidence.high);
for (VespaVersion version : controller().versionStatus().versions()) {
if (version.confidence() == Confidence.broken)
cancelUpgradesOf(applications().without(UpgradePolicy.canary).upgradingTo(version.versionNumber()),
version.versionNumber() + " is broken");
}
cancelUpgradesOf(applications().with(UpgradePolicy.canary).upgrading().notUpgradingTo(canaryTarget),
"Outdated target version for Canaries");
String reason = "Failing on outdated version";
cancelUpgradesOf(applications().with(UpgradePolicy.defaultPolicy).upgrading().failing().notUpgradingTo(defaultTargets), reason);
cancelUpgradesOf(applications().with(UpgradePolicy.conservative).upgrading().failing().notUpgradingTo(conservativeTargets), reason);
ApplicationList applications = applications();
canaryTarget.ifPresent(target -> upgrade(applications.with(UpgradePolicy.canary), target));
defaultTargets.forEach(target -> upgrade(applications.with(UpgradePolicy.defaultPolicy), target));
conservativeTargets.forEach(target -> upgrade(applications.with(UpgradePolicy.conservative), target));
}
/** Returns the target versions for given confidence, one per major version in the system */
private Collection<Version> targetVersions(Confidence confidence) {
return controller().versionStatus().versions().stream()
.filter(v -> !v.versionNumber().isAfter(controller().systemVersion()))
.filter(v -> v.confidence().equalOrHigherThan(confidence))
.map(VespaVersion::versionNumber)
.collect(Collectors.toMap(Version::getMajor,
Function.identity(),
BinaryOperator.<Version>maxBy(Comparator.naturalOrder())))
.values();
}
/** Returns a list of all applications, except those which are pinned — these should not be manipulated by the Upgrader */
private ApplicationList applications() {
return ApplicationList.from(controller().applications().asList()).unpinned();
}
private void upgrade(ApplicationList applications, Version version) {
applications = applications.withProductionDeployment();
applications = applications.onLowerVersionThan(version);
applications = applications.allowMajorVersion(version.getMajor(), targetMajorVersion().orElse(version.getMajor()));
applications = applications.notDeploying();
applications = applications.notFailingOn(version);
applications = applications.canUpgradeAt(controller().clock().instant());
applications = applications.byIncreasingDeployedVersion();
applications = applications.first(numberOfApplicationsToUpgrade());
for (Application application : applications.asList())
controller().applications().deploymentTrigger().triggerChange(application.id(), Change.of(version));
}
private void cancelUpgradesOf(ApplicationList applications, String reason) {
if (applications.isEmpty()) return;
log.info("Cancelling upgrading of " + applications.asList().size() + " applications: " + reason);
for (Application application : applications.asList())
controller().applications().deploymentTrigger().cancelChange(application.id(), PLATFORM);
}
/** Returns the number of applications to upgrade in this run */
/** Returns number of upgrades per minute */
public double upgradesPerMinute() {
return curator.readUpgradesPerMinute();
}
/** Sets the number of upgrades per minute */
public void setUpgradesPerMinute(double n) {
if (n < 0)
throw new IllegalArgumentException("Upgrades per minute must be >= 0, got " + n);
curator.writeUpgradesPerMinute(n);
}
/** Returns the target major version for applications not specifying one */
public Optional<Integer> targetMajorVersion() {
return curator.readTargetMajorVersion();
}
/** Sets the default target major version. Set to empty to determine target version normally (by confidence) */
public void setTargetMajorVersion(Optional<Integer> targetMajorVersion) {
curator.writeTargetMajorVersion(targetMajorVersion);
}
/** Override confidence for given version. This will cause the computed confidence to be ignored */
public void overrideConfidence(Version version, Confidence confidence) {
try (Lock lock = curator.lockConfidenceOverrides()) {
Map<Version, Confidence> overrides = new LinkedHashMap<>(curator.readConfidenceOverrides());
overrides.put(version, confidence);
curator.writeConfidenceOverrides(overrides);
}
}
/** Returns all confidence overrides */
public Map<Version, Confidence> confidenceOverrides() {
return curator.readConfidenceOverrides();
}
/** Remove confidence override for given version */
public void removeConfidenceOverride(Version version) {
controller().removeConfidenceOverride(version::equals);
}
} | class Upgrader extends Maintainer {
private static final Logger log = Logger.getLogger(Upgrader.class.getName());
private final CuratorDb curator;
public Upgrader(Controller controller, Duration interval, JobControl jobControl, CuratorDb curator) {
super(controller, interval, jobControl);
this.curator = Objects.requireNonNull(curator, "curator cannot be null");
}
/**
* Schedule application upgrades. Note that this implementation must be idempotent.
*/
@Override
public void maintain() {
Optional<Version> canaryTarget = controller().versionStatus().systemVersion().map(VespaVersion::versionNumber);
Collection<Version> defaultTargets = targetVersions(Confidence.normal);
Collection<Version> conservativeTargets = targetVersions(Confidence.high);
for (VespaVersion version : controller().versionStatus().versions()) {
if (version.confidence() == Confidence.broken)
cancelUpgradesOf(applications().without(UpgradePolicy.canary).upgradingTo(version.versionNumber()),
version.versionNumber() + " is broken");
}
cancelUpgradesOf(applications().with(UpgradePolicy.canary).upgrading().notUpgradingTo(canaryTarget),
"Outdated target version for Canaries");
String reason = "Failing on outdated version";
cancelUpgradesOf(applications().with(UpgradePolicy.defaultPolicy).upgrading().failing().notUpgradingTo(defaultTargets), reason);
cancelUpgradesOf(applications().with(UpgradePolicy.conservative).upgrading().failing().notUpgradingTo(conservativeTargets), reason);
ApplicationList applications = applications();
canaryTarget.ifPresent(target -> upgrade(applications.with(UpgradePolicy.canary), target));
defaultTargets.forEach(target -> upgrade(applications.with(UpgradePolicy.defaultPolicy), target));
conservativeTargets.forEach(target -> upgrade(applications.with(UpgradePolicy.conservative), target));
}
/** Returns the target versions for given confidence, one per major version in the system */
private Collection<Version> targetVersions(Confidence confidence) {
return controller().versionStatus().versions().stream()
.filter(v -> !v.versionNumber().isAfter(controller().systemVersion()))
.filter(v -> v.confidence().equalOrHigherThan(confidence))
.map(VespaVersion::versionNumber)
.collect(Collectors.toMap(Version::getMajor,
Function.identity(),
BinaryOperator.<Version>maxBy(Comparator.naturalOrder())))
.values();
}
/** Returns a list of all applications, except those which are pinned — these should not be manipulated by the Upgrader */
private ApplicationList applications() {
return ApplicationList.from(controller().applications().asList()).unpinned();
}
private void upgrade(ApplicationList applications, Version version) {
applications = applications.withProductionDeployment();
applications = applications.onLowerVersionThan(version);
applications = applications.allowMajorVersion(version.getMajor(), targetMajorVersion().orElse(version.getMajor()));
applications = applications.notDeploying();
applications = applications.notFailingOn(version);
applications = applications.canUpgradeAt(controller().clock().instant());
applications = applications.byIncreasingDeployedVersion();
applications = applications.first(numberOfApplicationsToUpgrade());
for (Application application : applications.asList())
controller().applications().deploymentTrigger().triggerChange(application.id(), Change.of(version));
}
private void cancelUpgradesOf(ApplicationList applications, String reason) {
if (applications.isEmpty()) return;
log.info("Cancelling upgrading of " + applications.asList().size() + " applications: " + reason);
for (Application application : applications.asList())
controller().applications().deploymentTrigger().cancelChange(application.id(), PLATFORM);
}
/** Returns the number of applications to upgrade in this run */
/** Returns the number of applications to upgrade in the interval containing now */
static int numberOfApplicationsToUpgrade(long intervalMillis, long nowMillis, double upgradesPerMinute) {
long intervalStart = Math.round(nowMillis / (double) intervalMillis) * intervalMillis;
double upgradesPerMilli = upgradesPerMinute / 60_000;
long upgradesAtStart = (long) (intervalStart * upgradesPerMilli);
long upgradesAtEnd = (long) ((intervalStart + intervalMillis) * upgradesPerMilli);
return (int) (upgradesAtEnd - upgradesAtStart);
}
/** Returns number of upgrades per minute */
public double upgradesPerMinute() {
return curator.readUpgradesPerMinute();
}
/** Sets the number of upgrades per minute */
public void setUpgradesPerMinute(double n) {
if (n < 0)
throw new IllegalArgumentException("Upgrades per minute must be >= 0, got " + n);
curator.writeUpgradesPerMinute(n);
}
/** Returns the target major version for applications not specifying one */
public Optional<Integer> targetMajorVersion() {
return curator.readTargetMajorVersion();
}
/** Sets the default target major version. Set to empty to determine target version normally (by confidence) */
public void setTargetMajorVersion(Optional<Integer> targetMajorVersion) {
curator.writeTargetMajorVersion(targetMajorVersion);
}
/** Override confidence for given version. This will cause the computed confidence to be ignored */
public void overrideConfidence(Version version, Confidence confidence) {
try (Lock lock = curator.lockConfidenceOverrides()) {
Map<Version, Confidence> overrides = new LinkedHashMap<>(curator.readConfidenceOverrides());
overrides.put(version, confidence);
curator.writeConfidenceOverrides(overrides);
}
}
/** Returns all confidence overrides */
public Map<Version, Confidence> confidenceOverrides() {
return curator.readConfidenceOverrides();
}
/** Remove confidence override for given version */
public void removeConfidenceOverride(Version version) {
controller().removeConfidenceOverride(version::equals);
}
} |
I'd argue it's rather a chained ternary, which reads pretty well as a switch without fallthrough, and with a default clause at the end :) In any case, I managed to avoid it completely, by replacing // with * :) | private int numberOfApplicationsToUpgrade() {
long intervalMillis = maintenanceInterval().dividedBy(Math.max(1, controller().curator().cluster().size())).toMillis();
long intervalStart = ((controller().clock().millis() + intervalMillis / 2) / intervalMillis) * intervalMillis;
long upgradeIntervalMillis = upgradesPerMinute() > 60e3 ? 1 : upgradesPerMinute() < 60e-3 ? 1_000_000 : (long) (60_000 / upgradesPerMinute());
return (int) ((intervalStart + intervalMillis) / upgradeIntervalMillis - intervalStart / intervalMillis);
} | long upgradeIntervalMillis = upgradesPerMinute() > 60e3 ? 1 : upgradesPerMinute() < 60e-3 ? 1_000_000 : (long) (60_000 / upgradesPerMinute()); | private int numberOfApplicationsToUpgrade() {
return numberOfApplicationsToUpgrade(maintenanceInterval().dividedBy(Math.max(1, controller().curator().cluster().size())).toMillis(),
controller().clock().millis(),
upgradesPerMinute());
} | class Upgrader extends Maintainer {
private static final Logger log = Logger.getLogger(Upgrader.class.getName());
private final CuratorDb curator;
public Upgrader(Controller controller, Duration interval, JobControl jobControl, CuratorDb curator) {
super(controller, interval, jobControl);
this.curator = Objects.requireNonNull(curator, "curator cannot be null");
}
/**
* Schedule application upgrades. Note that this implementation must be idempotent.
*/
@Override
public void maintain() {
Optional<Version> canaryTarget = controller().versionStatus().systemVersion().map(VespaVersion::versionNumber);
Collection<Version> defaultTargets = targetVersions(Confidence.normal);
Collection<Version> conservativeTargets = targetVersions(Confidence.high);
for (VespaVersion version : controller().versionStatus().versions()) {
if (version.confidence() == Confidence.broken)
cancelUpgradesOf(applications().without(UpgradePolicy.canary).upgradingTo(version.versionNumber()),
version.versionNumber() + " is broken");
}
cancelUpgradesOf(applications().with(UpgradePolicy.canary).upgrading().notUpgradingTo(canaryTarget),
"Outdated target version for Canaries");
String reason = "Failing on outdated version";
cancelUpgradesOf(applications().with(UpgradePolicy.defaultPolicy).upgrading().failing().notUpgradingTo(defaultTargets), reason);
cancelUpgradesOf(applications().with(UpgradePolicy.conservative).upgrading().failing().notUpgradingTo(conservativeTargets), reason);
ApplicationList applications = applications();
canaryTarget.ifPresent(target -> upgrade(applications.with(UpgradePolicy.canary), target));
defaultTargets.forEach(target -> upgrade(applications.with(UpgradePolicy.defaultPolicy), target));
conservativeTargets.forEach(target -> upgrade(applications.with(UpgradePolicy.conservative), target));
}
/** Returns the target versions for given confidence, one per major version in the system */
private Collection<Version> targetVersions(Confidence confidence) {
return controller().versionStatus().versions().stream()
.filter(v -> !v.versionNumber().isAfter(controller().systemVersion()))
.filter(v -> v.confidence().equalOrHigherThan(confidence))
.map(VespaVersion::versionNumber)
.collect(Collectors.toMap(Version::getMajor,
Function.identity(),
BinaryOperator.<Version>maxBy(Comparator.naturalOrder())))
.values();
}
/** Returns a list of all applications, except those which are pinned — these should not be manipulated by the Upgrader */
private ApplicationList applications() {
return ApplicationList.from(controller().applications().asList()).unpinned();
}
private void upgrade(ApplicationList applications, Version version) {
applications = applications.withProductionDeployment();
applications = applications.onLowerVersionThan(version);
applications = applications.allowMajorVersion(version.getMajor(), targetMajorVersion().orElse(version.getMajor()));
applications = applications.notDeploying();
applications = applications.notFailingOn(version);
applications = applications.canUpgradeAt(controller().clock().instant());
applications = applications.byIncreasingDeployedVersion();
applications = applications.first(numberOfApplicationsToUpgrade());
for (Application application : applications.asList())
controller().applications().deploymentTrigger().triggerChange(application.id(), Change.of(version));
}
private void cancelUpgradesOf(ApplicationList applications, String reason) {
if (applications.isEmpty()) return;
log.info("Cancelling upgrading of " + applications.asList().size() + " applications: " + reason);
for (Application application : applications.asList())
controller().applications().deploymentTrigger().cancelChange(application.id(), PLATFORM);
}
/** Returns the number of applications to upgrade in this run */
/** Returns number of upgrades per minute */
public double upgradesPerMinute() {
return curator.readUpgradesPerMinute();
}
/** Sets the number of upgrades per minute */
public void setUpgradesPerMinute(double n) {
if (n < 0)
throw new IllegalArgumentException("Upgrades per minute must be >= 0, got " + n);
curator.writeUpgradesPerMinute(n);
}
/** Returns the target major version for applications not specifying one */
public Optional<Integer> targetMajorVersion() {
return curator.readTargetMajorVersion();
}
/** Sets the default target major version. Set to empty to determine target version normally (by confidence) */
public void setTargetMajorVersion(Optional<Integer> targetMajorVersion) {
curator.writeTargetMajorVersion(targetMajorVersion);
}
/** Override confidence for given version. This will cause the computed confidence to be ignored */
public void overrideConfidence(Version version, Confidence confidence) {
try (Lock lock = curator.lockConfidenceOverrides()) {
Map<Version, Confidence> overrides = new LinkedHashMap<>(curator.readConfidenceOverrides());
overrides.put(version, confidence);
curator.writeConfidenceOverrides(overrides);
}
}
/** Returns all confidence overrides */
public Map<Version, Confidence> confidenceOverrides() {
return curator.readConfidenceOverrides();
}
/** Remove confidence override for given version */
public void removeConfidenceOverride(Version version) {
controller().removeConfidenceOverride(version::equals);
}
} | class Upgrader extends Maintainer {
private static final Logger log = Logger.getLogger(Upgrader.class.getName());
private final CuratorDb curator;
public Upgrader(Controller controller, Duration interval, JobControl jobControl, CuratorDb curator) {
super(controller, interval, jobControl);
this.curator = Objects.requireNonNull(curator, "curator cannot be null");
}
/**
* Schedule application upgrades. Note that this implementation must be idempotent.
*/
@Override
public void maintain() {
Optional<Version> canaryTarget = controller().versionStatus().systemVersion().map(VespaVersion::versionNumber);
Collection<Version> defaultTargets = targetVersions(Confidence.normal);
Collection<Version> conservativeTargets = targetVersions(Confidence.high);
for (VespaVersion version : controller().versionStatus().versions()) {
if (version.confidence() == Confidence.broken)
cancelUpgradesOf(applications().without(UpgradePolicy.canary).upgradingTo(version.versionNumber()),
version.versionNumber() + " is broken");
}
cancelUpgradesOf(applications().with(UpgradePolicy.canary).upgrading().notUpgradingTo(canaryTarget),
"Outdated target version for Canaries");
String reason = "Failing on outdated version";
cancelUpgradesOf(applications().with(UpgradePolicy.defaultPolicy).upgrading().failing().notUpgradingTo(defaultTargets), reason);
cancelUpgradesOf(applications().with(UpgradePolicy.conservative).upgrading().failing().notUpgradingTo(conservativeTargets), reason);
ApplicationList applications = applications();
canaryTarget.ifPresent(target -> upgrade(applications.with(UpgradePolicy.canary), target));
defaultTargets.forEach(target -> upgrade(applications.with(UpgradePolicy.defaultPolicy), target));
conservativeTargets.forEach(target -> upgrade(applications.with(UpgradePolicy.conservative), target));
}
/** Returns the target versions for given confidence, one per major version in the system */
private Collection<Version> targetVersions(Confidence confidence) {
return controller().versionStatus().versions().stream()
.filter(v -> !v.versionNumber().isAfter(controller().systemVersion()))
.filter(v -> v.confidence().equalOrHigherThan(confidence))
.map(VespaVersion::versionNumber)
.collect(Collectors.toMap(Version::getMajor,
Function.identity(),
BinaryOperator.<Version>maxBy(Comparator.naturalOrder())))
.values();
}
/** Returns a list of all applications, except those which are pinned — these should not be manipulated by the Upgrader */
private ApplicationList applications() {
return ApplicationList.from(controller().applications().asList()).unpinned();
}
private void upgrade(ApplicationList applications, Version version) {
applications = applications.withProductionDeployment();
applications = applications.onLowerVersionThan(version);
applications = applications.allowMajorVersion(version.getMajor(), targetMajorVersion().orElse(version.getMajor()));
applications = applications.notDeploying();
applications = applications.notFailingOn(version);
applications = applications.canUpgradeAt(controller().clock().instant());
applications = applications.byIncreasingDeployedVersion();
applications = applications.first(numberOfApplicationsToUpgrade());
for (Application application : applications.asList())
controller().applications().deploymentTrigger().triggerChange(application.id(), Change.of(version));
}
private void cancelUpgradesOf(ApplicationList applications, String reason) {
if (applications.isEmpty()) return;
log.info("Cancelling upgrading of " + applications.asList().size() + " applications: " + reason);
for (Application application : applications.asList())
controller().applications().deploymentTrigger().cancelChange(application.id(), PLATFORM);
}
/** Returns the number of applications to upgrade in this run */
/** Returns the number of applications to upgrade in the interval containing now */
static int numberOfApplicationsToUpgrade(long intervalMillis, long nowMillis, double upgradesPerMinute) {
long intervalStart = Math.round(nowMillis / (double) intervalMillis) * intervalMillis;
double upgradesPerMilli = upgradesPerMinute / 60_000;
long upgradesAtStart = (long) (intervalStart * upgradesPerMilli);
long upgradesAtEnd = (long) ((intervalStart + intervalMillis) * upgradesPerMilli);
return (int) (upgradesAtEnd - upgradesAtStart);
}
/** Returns number of upgrades per minute */
public double upgradesPerMinute() {
return curator.readUpgradesPerMinute();
}
/** Sets the number of upgrades per minute */
public void setUpgradesPerMinute(double n) {
if (n < 0)
throw new IllegalArgumentException("Upgrades per minute must be >= 0, got " + n);
curator.writeUpgradesPerMinute(n);
}
/** Returns the target major version for applications not specifying one */
public Optional<Integer> targetMajorVersion() {
return curator.readTargetMajorVersion();
}
/** Sets the default target major version. Set to empty to determine target version normally (by confidence) */
public void setTargetMajorVersion(Optional<Integer> targetMajorVersion) {
curator.writeTargetMajorVersion(targetMajorVersion);
}
/** Override confidence for given version. This will cause the computed confidence to be ignored */
public void overrideConfidence(Version version, Confidence confidence) {
try (Lock lock = curator.lockConfidenceOverrides()) {
Map<Version, Confidence> overrides = new LinkedHashMap<>(curator.readConfidenceOverrides());
overrides.put(version, confidence);
curator.writeConfidenceOverrides(overrides);
}
}
/** Returns all confidence overrides */
public Map<Version, Confidence> confidenceOverrides() {
return curator.readConfidenceOverrides();
}
/** Remove confidence override for given version */
public void removeConfidenceOverride(Version version) {
controller().removeConfidenceOverride(version::equals);
}
} |
Ah, another. | public void doTests(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = job.type().zone(tester.controller().system());
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installReal));
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installTester));
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.startTests));
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.endTests));
cloud.set(TesterCloud.Status.SUCCESS);
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasEnded());
assertFalse(jobs.run(id).get().hasFailed());
assertEquals(job.type().isProduction(), tester.instance(job.application()).deployments().containsKey(zone));
assertTrue(tester.configServer().nodeRepository().list(zone, TesterId.of(id.application()).id()).isEmpty());
} | assertEquals(job.type().isProduction(), tester.instance(job.application()).deployments().containsKey(zone)); | public void doTests(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = job.type().zone(tester.controller().system());
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installReal));
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installTester));
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.startTests));
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.endTests));
cloud.set(TesterCloud.Status.SUCCESS);
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasEnded());
assertFalse(jobs.run(id).get().hasFailed());
assertEquals(job.type().isProduction(), tester.instance(job.application()).deployments().containsKey(zone));
assertTrue(tester.configServer().nodeRepository().list(zone, TesterId.of(id.application()).id()).isEmpty());
} | class InternalDeploymentTester {
private static final String ATHENZ_DOMAIN = "domain";
private static final String ATHENZ_SERVICE = "service";
public static final ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from(ATHENZ_DOMAIN), AthenzService.from(ATHENZ_SERVICE))
.upgradePolicy("default")
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.emailRole("author")
.emailAddress("b@a")
.build();
public static final ApplicationPackage publicCdApplicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from(ATHENZ_DOMAIN), AthenzService.from(ATHENZ_SERVICE))
.upgradePolicy("default")
.region("aws-us-east-1c")
.emailRole("author")
.emailAddress("b@a")
.trust(generateCertificate())
.build();
public static final TenantAndApplicationId appId = TenantAndApplicationId.from("tenant", "application");
public static final ApplicationId instanceId = appId.defaultInstance();
public static final TesterId testerId = TesterId.of(instanceId);
public static final String athenzDomain = "domain";
private final DeploymentTester tester;
private final JobController jobs;
private final RoutingGeneratorMock routing;
private final MockTesterCloud cloud;
private final JobRunner runner;
private final NameServiceDispatcher nameServiceDispatcher;
private final AtomicLong nextPropertyId = new AtomicLong(1);
private final AtomicInteger nextProjectId = new AtomicInteger(1);
private final AtomicInteger nextDomainId = new AtomicInteger(100);
public DeploymentTester tester() { return tester; }
public JobController jobs() { return jobs; }
public RoutingGeneratorMock routing() { return routing; }
public MockTesterCloud cloud() { return cloud; }
public JobRunner runner() { return runner; }
public ConfigServerMock configServer() { return tester.configServer(); }
public Controller controller() { return tester.controller(); }
public ApplicationController applications() { return tester.applications(); }
public ManualClock clock() { return tester.clock(); }
public Application application() { return tester.application(appId); }
public Instance instance() { return tester.instance(instanceId); }
public InternalDeploymentTester() {
tester = new DeploymentTester();
createApplication(instanceId.tenant().value(), instanceId.application().value(), instanceId.instance().value());
jobs = tester.controller().jobController();
routing = tester.controllerTester().serviceRegistry().routingGeneratorMock();
cloud = (MockTesterCloud) tester.controller().jobController().cloud();
runner = new JobRunner(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator()),
JobRunnerTest.inThreadExecutor(), new InternalStepRunner(tester.controller()));
this.nameServiceDispatcher = new NameServiceDispatcher(tester.controller(), Duration.ofHours(12),
new JobControl(tester.controller().curator()),
Integer.MAX_VALUE);
routing.putEndpoints(new DeploymentId(null, null), Collections.emptyList());
Logger.getLogger(InternalStepRunner.class.getName()).setLevel(LogLevel.DEBUG);
Logger.getLogger("").setLevel(LogLevel.DEBUG);
tester.controllerTester().configureDefaultLogHandler(handler -> handler.setLevel(LogLevel.DEBUG));
AthenzDbMock.Domain domain = tester.controllerTester().athenzDb().getOrCreateDomain(new com.yahoo.vespa.athenz.api.AthenzDomain(ATHENZ_DOMAIN));
domain.services.put(ATHENZ_SERVICE, new AthenzDbMock.Service(true));
}
/** Create a new application with given tenant and application name */
public Application createApplication(String tenantName, String applicationName, String instanceName) {
return tester.controllerTester().createApplication(tester.controllerTester().createTenant(tenantName,
athenzDomain + nextDomainId.getAndIncrement(),
nextPropertyId.getAndIncrement()),
applicationName,
instanceName,
nextProjectId.getAndIncrement());
}
/** Submits a new application, and returns the version of the new submission. */
public ApplicationVersion newSubmission(TenantAndApplicationId id, ApplicationPackage applicationPackage,
SourceRevision revision, String authorEmail, long projectId) {
return jobs.submit(id, revision, authorEmail, projectId, applicationPackage, new byte[0]);
}
/** Submits a new application, and returns the version of the new submission. */
public ApplicationVersion newSubmission(TenantAndApplicationId id, ApplicationPackage applicationPackage) {
var projectId = tester.application(id).projectId().orElseThrow(() -> new IllegalArgumentException("No project ID set for " + id));
return newSubmission(id, applicationPackage, BuildJob.defaultSourceRevision, "a@b", projectId);
}
/**
* Submits a new application package, and returns the version of the new submission.
*/
public ApplicationVersion newSubmission(ApplicationPackage applicationPackage) {
return newSubmission(appId, applicationPackage);
}
/**
* Submits a new application, and returns the version of the new submission.
*/
public ApplicationVersion newSubmission() {
return newSubmission(appId, tester.controller().system().isPublic() ? publicCdApplicationPackage : applicationPackage);
}
/**
* Sets a single endpoint in the routing mock; this matches that required for the tester.
*/
public void setEndpoints(ApplicationId id, ZoneId zone) {
routing.putEndpoints(new DeploymentId(id, zone),
Collections.singletonList(new RoutingEndpoint(String.format("https:
id.instance().value(),
id.application().value(),
id.tenant().value(),
zone.region().value(),
zone.environment().value()),
"host1",
false,
String.format("cluster1.%s.%s.%s.%s",
id.application().value(),
id.tenant().value(),
zone.region().value(),
zone.environment().value()))));
}
/** Runs and returns all remaining jobs for the application, at most once, and asserts the current change is rolled out. */
public List<JobType> completeRollout(TenantAndApplicationId id) {
tester.readyJobTrigger().run();
Set<JobType> jobs = new HashSet<>();
List<Run> activeRuns;
while ( ! (activeRuns = jobs().active(id)).isEmpty())
for (Run run : activeRuns)
if (jobs.add(run.id().type())) {
runJob(run.id().job());
tester.readyJobTrigger().run();
}
else
throw new AssertionError("Job '" + run.id().type() + "' was run twice for '" + instanceId + "'");
assertFalse("Change should have no targets, but was " + application().change(), application().change().hasTargets());
return List.copyOf(jobs);
}
/** Completely deploys the given application version, assuming it is the last to be submitted. */
public void deployNewSubmission(ApplicationVersion version) {
deployNewSubmission(appId, version);
}
/** Completely deploys the given application version, assuming it is the last to be submitted. */
public void deployNewSubmission(TenantAndApplicationId id, ApplicationVersion version) {
assertFalse(tester.application(id).instances().values().stream()
.anyMatch(instance -> instance.deployments().values().stream()
.anyMatch(deployment -> deployment.applicationVersion().equals(version))));
assertEquals(version, tester.application(id).change().application().get());
assertFalse(tester.application(id).change().platform().isPresent());
completeRollout(id);
assertFalse(tester.application(id).change().hasTargets());
}
/** Completely deploys the given, new platform. */
public void deployNewPlatform(Version version) {
deployNewPlatform(appId, version);
}
/** Completely deploys the given, new platform. */
public void deployNewPlatform(TenantAndApplicationId id, Version version) {
assertEquals(tester.controller().systemVersion(), version);
assertFalse(tester.application(id).instances().values().stream()
.anyMatch(instance -> instance.deployments().values().stream()
.anyMatch(deployment -> deployment.version().equals(version))));
assertEquals(version, tester.application(id).change().platform().get());
assertFalse(tester.application(id).change().application().isPresent());
completeRollout(id);
assertTrue(tester.application(id).productionDeployments().values().stream()
.allMatch(deployments -> deployments.stream()
.allMatch(deployment -> deployment.version().equals(version))));
for (JobType type : new DeploymentSteps(application().deploymentSpec(), tester.controller()::system).productionJobs())
assertTrue(tester.configServer().nodeRepository()
.list(type.zone(tester.controller().system()), id.defaultInstance()).stream()
.allMatch(node -> node.currentVersion().equals(version)));
assertFalse(tester.application(id).change().hasTargets());
}
public void triggerJobs() {
tester.triggerUntilQuiescence();
}
/** Returns the current run for the given job type, and verifies it is still running normally. */
public Run currentRun(JobId job) {
Run run = jobs.last(job)
.filter(r -> r.id().type() == job.type())
.orElseThrow(() -> new AssertionError(job.type() + " is not among the active: " + jobs.active()));
assertFalse(run.hasFailed());
assertNotEquals(aborted, run.status());
return run;
}
/** Deploys tester and real app, and completes initial staging installation first if needed. */
public void doDeploy(JobType type) {
doDeploy(new JobId(instanceId, type));
}
/** Deploys tester and real app, and completes initial staging installation first if needed. */
public void doDeploy(ApplicationId instanceId, JobType type) {
doDeploy(new JobId(instanceId, type));
}
/** Deploys tester and real app, and completes initial staging installation first if needed. */
public void doDeploy(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = job.type().zone(tester.controller().system());
DeploymentId deployment = new DeploymentId(job.application(), zone);
runner.advance(currentRun(job));
if (job.type() == JobType.stagingTest) {
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installInitialReal));
currentRun(job).versions().sourcePlatform().ifPresent(version -> tester.configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), version));
tester.configServer().convergeServices(id.application(), zone);
setEndpoints(id.application(), zone);
runner.advance(currentRun(job));
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installInitialReal));
}
}
/** Upgrades nodes to target version. */
public void doUpgrade(JobType type) {
doUpgrade(new JobId(instanceId, type));
}
/** Upgrades nodes to target version. */
public void doUpgrade(ApplicationId instanceId, JobType type) {
doUpgrade(new JobId(instanceId, type));
}
/** Upgrades nodes to target version. */
public void doUpgrade(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = job.type().zone(tester.controller().system());
DeploymentId deployment = new DeploymentId(job.application(), zone);
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
tester.configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), currentRun(job).versions().targetPlatform());
runner.advance(currentRun(job));
}
/** Lets nodes converge on new application version. */
public void doConverge(JobType type) {
doConverge(new JobId(instanceId, type));
}
/** Lets nodes converge on new application version. */
public void doConverge(ApplicationId instanceId, JobType type) {
doConverge(new JobId(instanceId, type));
}
/** Lets nodes converge on new application version. */
public void doConverge(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = job.type().zone(tester.controller().system());
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
tester.configServer().convergeServices(id.application(), zone);
runner.advance(currentRun(job));
if ( ! (currentRun(job).versions().sourceApplication().isPresent() && job.type().isProduction())
&& job.type() != JobType.stagingTest) {
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
setEndpoints(id.application(), zone);
}
runner.advance(currentRun(job));
if (job.type().environment().isManuallyDeployed()) {
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installReal));
assertTrue(jobs.run(id).get().hasEnded());
return;
}
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installReal));
}
/** Installs tester and starts tests. */
public void doInstallTester(JobType type) {
doInstallTester(new JobId(instanceId, type));
}
/** Installs tester and starts tests. */
public void doInstallTester(ApplicationId instanceId, JobType type) {
doInstallTester(new JobId(instanceId, type));
}
/** Installs tester and starts tests. */
public void doInstallTester(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = job.type().zone(tester.controller().system());
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installTester));
tester.configServer().nodeRepository().doUpgrade(new DeploymentId(TesterId.of(job.application()).id(), zone), Optional.empty(), currentRun(job).versions().targetPlatform());
runner.advance(currentRun(job));
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installTester));
tester.configServer().convergeServices(TesterId.of(id.application()).id(), zone);
runner.advance(currentRun(job));
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installTester));
setEndpoints(TesterId.of(id.application()).id(), zone);
runner.advance(currentRun(job));
}
/** Completes tests with success. */
public void doTests(JobType type) {
doTests(new JobId(instanceId, type));
}
/** Completes tests with success. */
public void doTests(ApplicationId instanceId, JobType type) {
doTests(new JobId(instanceId, type));
}
/** Completes tests with success. */
/** Removes endpoints from routing layer — always call this. */
public void doTeardown(JobType type) {
doTeardown(new JobId(instanceId, type));
}
/** Removes endpoints from routing layer — always call this. */
public void doTeardown(ApplicationId instanceId, JobType type) {
doTeardown(new JobId(instanceId, type));
}
/** Removes endpoints from routing layer — always call this. */
public void doTeardown(JobId job) {
ZoneId zone = job.type().zone(tester.controller().system());
DeploymentId deployment = new DeploymentId(job.application(), zone);
if ( ! instance().deployments().containsKey(zone))
routing.removeEndpoints(deployment);
routing.removeEndpoints(new DeploymentId(TesterId.of(job.application()).id(), zone));
}
/** Pulls the ready job trigger, and then runs the whole of the given job, successfully. */
public void runJob(JobType type) {
runJob(instanceId, type);
}
/** Pulls the ready job trigger, and then runs the whole of the given job, successfully. */
public void runJob(ApplicationId instanceId, JobType type) {
runJob(new JobId(instanceId, type));
}
/** Pulls the ready job trigger, and then runs the whole of the given job, successfully. */
public void runJob(JobId job) {
tester.readyJobTrigger().run();
doDeploy(job);
doUpgrade(job);
doConverge(job);
if (job.type().environment().isManuallyDeployed())
return;
doInstallTester(job);
doTests(job);
doTeardown(job);
}
public void failDeployment(JobType type) {
failDeployment(new JobId(instanceId, type));
}
public void failDeployment(ApplicationId instanceId, JobType type) {
failDeployment(new JobId(instanceId, type));
}
public void failDeployment(JobId job) {
RunId id = currentRun(job).id();
tester.readyJobTrigger().run();
tester.configServer().throwOnNextPrepare(new IllegalArgumentException("Exception"));
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasFailed());
assertTrue(jobs.run(id).get().hasEnded());
doTeardown(job);
}
public void timeOutUpgrade(JobType type) {
timeOutUpgrade(new JobId(instanceId, type));
}
public void timeOutUpgrade(ApplicationId instanceId, JobType type) {
timeOutUpgrade(new JobId(instanceId, type));
}
public void timeOutUpgrade(JobId job) {
RunId id = currentRun(job).id();
tester.readyJobTrigger().run();
doDeploy(job);
clock().advance(InternalStepRunner.installationTimeout.plusSeconds(1));
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasFailed());
assertTrue(jobs.run(id).get().hasEnded());
doTeardown(job);
}
public void timeOutConvergence(JobType type) {
timeOutConvergence(new JobId(instanceId, type));
}
public void timeOutConvergence(ApplicationId instanceId, JobType type) {
timeOutConvergence(new JobId(instanceId, type));
}
public void timeOutConvergence(JobId job) {
RunId id = currentRun(job).id();
tester.readyJobTrigger().run();
doDeploy(job);
doUpgrade(job);
clock().advance(InternalStepRunner.installationTimeout.plusSeconds(1));
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasFailed());
assertTrue(jobs.run(id).get().hasEnded());
doTeardown(job);
}
public RunId startSystemTestTests() {
RunId id = newRun(JobType.systemTest);
runner.run();
tester.configServer().convergeServices(instanceId, JobType.systemTest.zone(tester.controller().system()));
tester.configServer().convergeServices(testerId.id(), JobType.systemTest.zone(tester.controller().system()));
setEndpoints(instanceId, JobType.systemTest.zone(tester.controller().system()));
setEndpoints(testerId.id(), JobType.systemTest.zone(tester.controller().system()));
runner.run();
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.endTests));
return id;
}
/** Creates and submits a new application, and then starts the job of the given type. Use only once per test. */
public RunId newRun(JobType type) {
assertFalse(application().internal());
newSubmission();
tester.readyJobTrigger().maintain();
if (type.isProduction()) {
runJob(new JobId(instanceId, JobType.systemTest));
runJob(new JobId(instanceId, JobType.stagingTest));
tester.readyJobTrigger().maintain();
}
Run run = jobs.active().stream()
.filter(r -> r.id().type() == type)
.findAny()
.orElseThrow(() -> new AssertionError(type + " is not among the active: " + jobs.active()));
return run.id();
}
static X509Certificate generateCertificate() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X500Principal subject = new X500Principal("CN=subject");
return X509CertificateBuilder.fromKeypair(keyPair,
subject,
Instant.now(),
Instant.now().plusSeconds(1),
SignatureAlgorithm.SHA512_WITH_ECDSA,
BigInteger.valueOf(1))
.build();
}
public void assertRunning(JobType type) {
assertRunning(instanceId, type);
}
public void assertRunning(ApplicationId id, JobType type) {
assertTrue(jobs.active().stream().anyMatch(run -> run.id().application().equals(id) && run.id().type() == type));
}
/** Flush all pending name services requests */
public void flushDnsRequests() {
nameServiceDispatcher.run();
assertTrue("All name service requests dispatched",
controller().curator().readNameServiceQueue().requests().isEmpty());
}
} | class InternalDeploymentTester {
private static final String ATHENZ_DOMAIN = "domain";
private static final String ATHENZ_SERVICE = "service";
public static final ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from(ATHENZ_DOMAIN), AthenzService.from(ATHENZ_SERVICE))
.upgradePolicy("default")
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.emailRole("author")
.emailAddress("b@a")
.build();
public static final ApplicationPackage publicCdApplicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from(ATHENZ_DOMAIN), AthenzService.from(ATHENZ_SERVICE))
.upgradePolicy("default")
.region("aws-us-east-1c")
.emailRole("author")
.emailAddress("b@a")
.trust(generateCertificate())
.build();
public static final TenantAndApplicationId appId = TenantAndApplicationId.from("tenant", "application");
public static final ApplicationId instanceId = appId.defaultInstance();
public static final TesterId testerId = TesterId.of(instanceId);
public static final String athenzDomain = "domain";
private final DeploymentTester tester;
private final JobController jobs;
private final RoutingGeneratorMock routing;
private final MockTesterCloud cloud;
private final JobRunner runner;
private final NameServiceDispatcher nameServiceDispatcher;
private final AtomicLong nextPropertyId = new AtomicLong(1);
private final AtomicInteger nextProjectId = new AtomicInteger(1);
private final AtomicInteger nextDomainId = new AtomicInteger(100);
public DeploymentTester tester() { return tester; }
public JobController jobs() { return jobs; }
public RoutingGeneratorMock routing() { return routing; }
public MockTesterCloud cloud() { return cloud; }
public JobRunner runner() { return runner; }
public ConfigServerMock configServer() { return tester.configServer(); }
public Controller controller() { return tester.controller(); }
public ApplicationController applications() { return tester.applications(); }
public ManualClock clock() { return tester.clock(); }
public Application application() { return tester.application(appId); }
public Instance instance() { return tester.instance(instanceId); }
public InternalDeploymentTester() {
tester = new DeploymentTester();
createApplication(instanceId.tenant().value(), instanceId.application().value(), instanceId.instance().value());
jobs = tester.controller().jobController();
routing = tester.controllerTester().serviceRegistry().routingGeneratorMock();
cloud = (MockTesterCloud) tester.controller().jobController().cloud();
runner = new JobRunner(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator()),
JobRunnerTest.inThreadExecutor(), new InternalStepRunner(tester.controller()));
this.nameServiceDispatcher = new NameServiceDispatcher(tester.controller(), Duration.ofHours(12),
new JobControl(tester.controller().curator()),
Integer.MAX_VALUE);
routing.putEndpoints(new DeploymentId(null, null), Collections.emptyList());
Logger.getLogger(InternalStepRunner.class.getName()).setLevel(LogLevel.DEBUG);
Logger.getLogger("").setLevel(LogLevel.DEBUG);
tester.controllerTester().configureDefaultLogHandler(handler -> handler.setLevel(LogLevel.DEBUG));
AthenzDbMock.Domain domain = tester.controllerTester().athenzDb().getOrCreateDomain(new com.yahoo.vespa.athenz.api.AthenzDomain(ATHENZ_DOMAIN));
domain.services.put(ATHENZ_SERVICE, new AthenzDbMock.Service(true));
}
/** Create a new application with given tenant and application name */
public Application createApplication(String tenantName, String applicationName, String instanceName) {
return tester.controllerTester().createApplication(tester.controllerTester().createTenant(tenantName,
athenzDomain + nextDomainId.getAndIncrement(),
nextPropertyId.getAndIncrement()),
applicationName,
instanceName,
nextProjectId.getAndIncrement());
}
/** Submits a new application, and returns the version of the new submission. */
public ApplicationVersion newSubmission(TenantAndApplicationId id, ApplicationPackage applicationPackage,
SourceRevision revision, String authorEmail, long projectId) {
return jobs.submit(id, revision, authorEmail, projectId, applicationPackage, new byte[0]);
}
/** Submits a new application, and returns the version of the new submission. */
public ApplicationVersion newSubmission(TenantAndApplicationId id, ApplicationPackage applicationPackage) {
var projectId = tester.application(id).projectId().orElseThrow(() -> new IllegalArgumentException("No project ID set for " + id));
return newSubmission(id, applicationPackage, BuildJob.defaultSourceRevision, "a@b", projectId);
}
/**
* Submits a new application package, and returns the version of the new submission.
*/
public ApplicationVersion newSubmission(ApplicationPackage applicationPackage) {
return newSubmission(appId, applicationPackage);
}
/**
* Submits a new application, and returns the version of the new submission.
*/
public ApplicationVersion newSubmission() {
return newSubmission(appId, tester.controller().system().isPublic() ? publicCdApplicationPackage : applicationPackage);
}
/**
* Sets a single endpoint in the routing mock; this matches that required for the tester.
*/
public void setEndpoints(ApplicationId id, ZoneId zone) {
routing.putEndpoints(new DeploymentId(id, zone),
Collections.singletonList(new RoutingEndpoint(String.format("https:
id.instance().value(),
id.application().value(),
id.tenant().value(),
zone.region().value(),
zone.environment().value()),
"host1",
false,
String.format("cluster1.%s.%s.%s.%s",
id.application().value(),
id.tenant().value(),
zone.region().value(),
zone.environment().value()))));
}
/** Runs and returns all remaining jobs for the application, at most once, and asserts the current change is rolled out. */
public List<JobType> completeRollout(TenantAndApplicationId id) {
tester.readyJobTrigger().run();
Set<JobType> jobs = new HashSet<>();
List<Run> activeRuns;
while ( ! (activeRuns = jobs().active(id)).isEmpty())
for (Run run : activeRuns)
if (jobs.add(run.id().type())) {
runJob(run.id().job());
tester.readyJobTrigger().run();
}
else
throw new AssertionError("Job '" + run.id().type() + "' was run twice for '" + instanceId + "'");
assertFalse("Change should have no targets, but was " + application().change(), application().change().hasTargets());
return List.copyOf(jobs);
}
/** Completely deploys the given application version, assuming it is the last to be submitted. */
public void deployNewSubmission(ApplicationVersion version) {
deployNewSubmission(appId, version);
}
/** Completely deploys the given application version, assuming it is the last to be submitted. */
public void deployNewSubmission(TenantAndApplicationId id, ApplicationVersion version) {
assertFalse(tester.application(id).instances().values().stream()
.anyMatch(instance -> instance.deployments().values().stream()
.anyMatch(deployment -> deployment.applicationVersion().equals(version))));
assertEquals(version, tester.application(id).change().application().get());
assertFalse(tester.application(id).change().platform().isPresent());
completeRollout(id);
assertFalse(tester.application(id).change().hasTargets());
}
/** Completely deploys the given, new platform. */
public void deployNewPlatform(Version version) {
deployNewPlatform(appId, version);
}
/** Completely deploys the given, new platform. */
public void deployNewPlatform(TenantAndApplicationId id, Version version) {
assertEquals(tester.controller().systemVersion(), version);
assertFalse(tester.application(id).instances().values().stream()
.anyMatch(instance -> instance.deployments().values().stream()
.anyMatch(deployment -> deployment.version().equals(version))));
assertEquals(version, tester.application(id).change().platform().get());
assertFalse(tester.application(id).change().application().isPresent());
completeRollout(id);
assertTrue(tester.application(id).productionDeployments().values().stream()
.allMatch(deployments -> deployments.stream()
.allMatch(deployment -> deployment.version().equals(version))));
for (JobType type : new DeploymentSteps(application().deploymentSpec(), tester.controller()::system).productionJobs())
assertTrue(tester.configServer().nodeRepository()
.list(type.zone(tester.controller().system()), id.defaultInstance()).stream()
.allMatch(node -> node.currentVersion().equals(version)));
assertFalse(tester.application(id).change().hasTargets());
}
public void triggerJobs() {
tester.triggerUntilQuiescence();
}
/** Returns the current run for the given job type, and verifies it is still running normally. */
public Run currentRun(JobId job) {
Run run = jobs.last(job)
.filter(r -> r.id().type() == job.type())
.orElseThrow(() -> new AssertionError(job.type() + " is not among the active: " + jobs.active()));
assertFalse(run.hasFailed());
assertNotEquals(aborted, run.status());
return run;
}
/** Deploys tester and real app, and completes initial staging installation first if needed. */
public void doDeploy(JobType type) {
doDeploy(new JobId(instanceId, type));
}
/** Deploys tester and real app, and completes initial staging installation first if needed. */
public void doDeploy(ApplicationId instanceId, JobType type) {
doDeploy(new JobId(instanceId, type));
}
/** Deploys tester and real app, and completes initial staging installation first if needed. */
public void doDeploy(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = job.type().zone(tester.controller().system());
DeploymentId deployment = new DeploymentId(job.application(), zone);
runner.advance(currentRun(job));
if (job.type() == JobType.stagingTest) {
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installInitialReal));
currentRun(job).versions().sourcePlatform().ifPresent(version -> tester.configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), version));
tester.configServer().convergeServices(id.application(), zone);
setEndpoints(id.application(), zone);
runner.advance(currentRun(job));
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installInitialReal));
}
}
/** Upgrades nodes to target version. */
public void doUpgrade(JobType type) {
doUpgrade(new JobId(instanceId, type));
}
/** Upgrades nodes to target version. */
public void doUpgrade(ApplicationId instanceId, JobType type) {
doUpgrade(new JobId(instanceId, type));
}
/** Upgrades nodes to target version. */
public void doUpgrade(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = job.type().zone(tester.controller().system());
DeploymentId deployment = new DeploymentId(job.application(), zone);
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
tester.configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), currentRun(job).versions().targetPlatform());
runner.advance(currentRun(job));
}
/** Lets nodes converge on new application version. */
public void doConverge(JobType type) {
doConverge(new JobId(instanceId, type));
}
/** Lets nodes converge on new application version. */
public void doConverge(ApplicationId instanceId, JobType type) {
doConverge(new JobId(instanceId, type));
}
/** Lets nodes converge on new application version. */
public void doConverge(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = job.type().zone(tester.controller().system());
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
tester.configServer().convergeServices(id.application(), zone);
runner.advance(currentRun(job));
if ( ! (currentRun(job).versions().sourceApplication().isPresent() && job.type().isProduction())
&& job.type() != JobType.stagingTest) {
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
setEndpoints(id.application(), zone);
}
runner.advance(currentRun(job));
if (job.type().environment().isManuallyDeployed()) {
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installReal));
assertTrue(jobs.run(id).get().hasEnded());
return;
}
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installReal));
}
/** Installs tester and starts tests. */
public void doInstallTester(JobType type) {
doInstallTester(new JobId(instanceId, type));
}
/** Installs tester and starts tests. */
public void doInstallTester(ApplicationId instanceId, JobType type) {
doInstallTester(new JobId(instanceId, type));
}
/** Installs tester and starts tests. */
public void doInstallTester(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = job.type().zone(tester.controller().system());
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installTester));
tester.configServer().nodeRepository().doUpgrade(new DeploymentId(TesterId.of(job.application()).id(), zone), Optional.empty(), currentRun(job).versions().targetPlatform());
runner.advance(currentRun(job));
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installTester));
tester.configServer().convergeServices(TesterId.of(id.application()).id(), zone);
runner.advance(currentRun(job));
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installTester));
setEndpoints(TesterId.of(id.application()).id(), zone);
runner.advance(currentRun(job));
}
/** Completes tests with success. */
public void doTests(JobType type) {
doTests(new JobId(instanceId, type));
}
/** Completes tests with success. */
public void doTests(ApplicationId instanceId, JobType type) {
doTests(new JobId(instanceId, type));
}
/** Completes tests with success. */
/** Removes endpoints from routing layer — always call this. */
public void doTeardown(JobType type) {
doTeardown(new JobId(instanceId, type));
}
/** Removes endpoints from routing layer — always call this. */
public void doTeardown(ApplicationId instanceId, JobType type) {
doTeardown(new JobId(instanceId, type));
}
/** Removes endpoints from routing layer — always call this. */
public void doTeardown(JobId job) {
ZoneId zone = job.type().zone(tester.controller().system());
DeploymentId deployment = new DeploymentId(job.application(), zone);
if ( ! instance().deployments().containsKey(zone))
routing.removeEndpoints(deployment);
routing.removeEndpoints(new DeploymentId(TesterId.of(job.application()).id(), zone));
}
/** Pulls the ready job trigger, and then runs the whole of the given job, successfully. */
public void runJob(JobType type) {
runJob(instanceId, type);
}
/** Pulls the ready job trigger, and then runs the whole of the given job, successfully. */
public void runJob(ApplicationId instanceId, JobType type) {
runJob(new JobId(instanceId, type));
}
/** Pulls the ready job trigger, and then runs the whole of the given job, successfully. */
public void runJob(JobId job) {
tester.readyJobTrigger().run();
doDeploy(job);
doUpgrade(job);
doConverge(job);
if (job.type().environment().isManuallyDeployed())
return;
doInstallTester(job);
doTests(job);
doTeardown(job);
}
public void failDeployment(JobType type) {
failDeployment(new JobId(instanceId, type));
}
public void failDeployment(ApplicationId instanceId, JobType type) {
failDeployment(new JobId(instanceId, type));
}
public void failDeployment(JobId job) {
RunId id = currentRun(job).id();
tester.readyJobTrigger().run();
tester.configServer().throwOnNextPrepare(new IllegalArgumentException("Exception"));
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasFailed());
assertTrue(jobs.run(id).get().hasEnded());
doTeardown(job);
}
public void timeOutUpgrade(JobType type) {
timeOutUpgrade(new JobId(instanceId, type));
}
public void timeOutUpgrade(ApplicationId instanceId, JobType type) {
timeOutUpgrade(new JobId(instanceId, type));
}
public void timeOutUpgrade(JobId job) {
RunId id = currentRun(job).id();
tester.readyJobTrigger().run();
doDeploy(job);
clock().advance(InternalStepRunner.installationTimeout.plusSeconds(1));
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasFailed());
assertTrue(jobs.run(id).get().hasEnded());
doTeardown(job);
}
public void timeOutConvergence(JobType type) {
timeOutConvergence(new JobId(instanceId, type));
}
public void timeOutConvergence(ApplicationId instanceId, JobType type) {
timeOutConvergence(new JobId(instanceId, type));
}
public void timeOutConvergence(JobId job) {
RunId id = currentRun(job).id();
tester.readyJobTrigger().run();
doDeploy(job);
doUpgrade(job);
clock().advance(InternalStepRunner.installationTimeout.plusSeconds(1));
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasFailed());
assertTrue(jobs.run(id).get().hasEnded());
doTeardown(job);
}
public RunId startSystemTestTests() {
RunId id = newRun(JobType.systemTest);
runner.run();
tester.configServer().convergeServices(instanceId, JobType.systemTest.zone(tester.controller().system()));
tester.configServer().convergeServices(testerId.id(), JobType.systemTest.zone(tester.controller().system()));
setEndpoints(instanceId, JobType.systemTest.zone(tester.controller().system()));
setEndpoints(testerId.id(), JobType.systemTest.zone(tester.controller().system()));
runner.run();
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.endTests));
return id;
}
/** Creates and submits a new application, and then starts the job of the given type. Use only once per test. */
public RunId newRun(JobType type) {
assertFalse(application().internal());
newSubmission();
tester.readyJobTrigger().maintain();
if (type.isProduction()) {
runJob(new JobId(instanceId, JobType.systemTest));
runJob(new JobId(instanceId, JobType.stagingTest));
tester.readyJobTrigger().maintain();
}
Run run = jobs.active().stream()
.filter(r -> r.id().type() == type)
.findAny()
.orElseThrow(() -> new AssertionError(type + " is not among the active: " + jobs.active()));
return run.id();
}
static X509Certificate generateCertificate() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X500Principal subject = new X500Principal("CN=subject");
return X509CertificateBuilder.fromKeypair(keyPair,
subject,
Instant.now(),
Instant.now().plusSeconds(1),
SignatureAlgorithm.SHA512_WITH_ECDSA,
BigInteger.valueOf(1))
.build();
}
public void assertRunning(JobType type) {
assertRunning(instanceId, type);
}
public void assertRunning(ApplicationId id, JobType type) {
assertTrue(jobs.active().stream().anyMatch(run -> run.id().application().equals(id) && run.id().type() == type));
}
/** Flush all pending name services requests */
public void flushDnsRequests() {
nameServiceDispatcher.run();
assertTrue("All name service requests dispatched",
controller().curator().readNameServiceQueue().requests().isEmpty());
}
} |
We should be able to remove the instance here soon. Perhaps already now? | public void deployment_warnings_metric() {
var tester = new InternalDeploymentTester();
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", "default");
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.deployNewSubmission(application.id(), tester.newSubmission(application.id(), applicationPackage));
reporter.maintain();
assertEquals(4, getDeploymentWarnings(application.id().defaultInstance()));
} | Application application = tester.createApplication("app1", "tenant1", "default"); | public void deployment_warnings_metric() {
var tester = new InternalDeploymentTester();
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", "default");
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.deployNewSubmission(application.id(), tester.newSubmission(application.id(), applicationPackage));
reporter.maintain();
assertEquals(4, getDeploymentWarnings(application.id().defaultInstance()));
} | class MetricsReporterTest {
private final MetricsMock metrics = new MetricsMock();
@Test
public void deployment_fail_ratio() {
var tester = new InternalDeploymentTester();
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", "default");
Application app2 = tester.createApplication("app2", "tenant1", "default");
Application app3 = tester.createApplication("app3", "tenant1", "default");
Application app4 = tester.createApplication("app4", "tenant1", "default");
var version1 = tester.newSubmission(app1.id(), applicationPackage);
tester.deployNewSubmission(app1.id(), version1);
tester.deployNewSubmission(app2.id(), tester.newSubmission(app2.id(), applicationPackage));
tester.deployNewSubmission(app3.id(), tester.newSubmission(app3.id(), applicationPackage));
tester.deployNewSubmission(app4.id(), tester.newSubmission(app4.id(), applicationPackage));
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
tester.newSubmission(app4.id(), applicationPackage);
tester.triggerJobs();
tester.failDeployment(app4.id().defaultInstance(), systemTest);
metricsReporter.maintain();
assertEquals(25.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
}
@Test
public void 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 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
@Test
public void build_time_reporting() {
var 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 name_service_queue_size_metric() {
var tester = new InternalDeploymentTester();
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", "default");
reporter.maintain();
assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
tester.deployNewSubmission(application.id(), tester.newSubmission(application.id(), 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 nodes_failing_system_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone1 = ZoneApiMock.fromId("prod.eu-west-1");
tester.zoneRegistry().setUpgradePolicy(UpgradePolicy.create().upgrade(zone1));
var systemUpgrader = new SystemUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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
public void nodes_failing_os_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone = ZoneApiMock.fromId("prod.eu-west-1");
var cloud = CloudName.defaultName();
tester.zoneRegistry().setOsUpgradePolicy(cloud, UpgradePolicy.create().upgrade(zone));
var osUpgrader = new OsUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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());
}
}
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 deployment_fail_ratio() {
var tester = new InternalDeploymentTester();
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", "default");
Application app2 = tester.createApplication("app2", "tenant1", "default");
Application app3 = tester.createApplication("app3", "tenant1", "default");
Application app4 = tester.createApplication("app4", "tenant1", "default");
var version1 = tester.newSubmission(app1.id(), applicationPackage);
tester.deployNewSubmission(app1.id(), version1);
tester.deployNewSubmission(app2.id(), tester.newSubmission(app2.id(), applicationPackage));
tester.deployNewSubmission(app3.id(), tester.newSubmission(app3.id(), applicationPackage));
tester.deployNewSubmission(app4.id(), tester.newSubmission(app4.id(), applicationPackage));
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
tester.newSubmission(app4.id(), applicationPackage);
tester.triggerJobs();
tester.failDeployment(app4.id().defaultInstance(), systemTest);
metricsReporter.maintain();
assertEquals(25.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
}
@Test
public void 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 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
@Test
public void build_time_reporting() {
var 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 name_service_queue_size_metric() {
var tester = new InternalDeploymentTester();
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", "default");
reporter.maintain();
assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
tester.deployNewSubmission(application.id(), tester.newSubmission(application.id(), 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 nodes_failing_system_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone1 = ZoneApiMock.fromId("prod.eu-west-1");
tester.zoneRegistry().setUpgradePolicy(UpgradePolicy.create().upgrade(zone1));
var systemUpgrader = new SystemUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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
public void nodes_failing_os_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone = ZoneApiMock.fromId("prod.eu-west-1");
var cloud = CloudName.defaultName();
tester.zoneRegistry().setOsUpgradePolicy(cloud, UpgradePolicy.create().upgrade(zone));
var osUpgrader = new OsUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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());
}
}
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();
}
} |
Fixed | private static void verifySuccess(HttpResponse response, FlagsTarget target, FlagId flagId) throws IOException {
if (!success(response)) {
String message = getErrorMessage(response);
throw new FlagsException(response.getStatusLine().getStatusCode(), target, flagId, message);
}
} | String message = getErrorMessage(response); | private static void verifySuccess(HttpResponse response, FlagsTarget target, FlagId flagId) throws IOException {
if (!success(response)) {
throw createFlagsException(response, target, flagId);
}
} | class FlagsClient {
private static final String FLAGS_V1_PATH = "/flags/v1";
private static final ObjectMapper mapper = new ObjectMapper();
private final CloseableHttpClient client;
FlagsClient(ServiceIdentityProvider identityProvider, Set<FlagsTarget> targets) {
this.client = createClient(identityProvider, targets);
}
List<FlagData> listFlagData(FlagsTarget target) throws FlagsException, UncheckedIOException {
HttpGet request = new HttpGet(createUri(target, "/data"));
return executeRequest(request, response -> {
verifySuccess(response, target, null);
return FlagData.deserializeList(EntityUtils.toByteArray(response.getEntity()));
});
}
void putFlagData(FlagsTarget target, FlagData flagData) throws FlagsException, UncheckedIOException {
HttpPut request = new HttpPut(createUri(target, "/data/" + flagData.id().toString()));
request.setEntity(jsonContent(flagData.serializeToJson()));
executeRequest(request, response -> {
verifySuccess(response, target, flagData.id());
return null;
});
}
void deleteFlagData(FlagsTarget target, FlagId flagId) throws FlagsException, UncheckedIOException {
HttpDelete request = new HttpDelete(createUri(target, "/data/" + flagId.toString()));
executeRequest(request, response -> {
verifySuccess(response, target, flagId);
return null;
});
}
private static CloseableHttpClient createClient(ServiceIdentityProvider identityProvider, Set<FlagsTarget> targets) {
return HttpClientBuilder.create()
.setUserAgent("controller-flags-v1-client")
.setRetryHandler(new DefaultHttpRequestRetryHandler(5, /*retry on non-idempotent requests*/true))
.setSslcontext(identityProvider.getIdentitySslContext())
.setSSLHostnameVerifier(new FlagTargetsHostnameVerifier(targets))
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout((int) Duration.ofSeconds(10).toMillis())
.setConnectionRequestTimeout((int) Duration.ofSeconds(10).toMillis())
.setSocketTimeout((int) Duration.ofSeconds(20).toMillis())
.build())
.setMaxConnPerRoute(2)
.setMaxConnTotal(100)
.build();
}
private <T> T executeRequest(HttpUriRequest request, ResponseHandler<T> handler) {
try {
return client.execute(request, handler);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static URI createUri(FlagsTarget target, String subPath) {
try {
return new URIBuilder(target.endpoint()).setPath(FLAGS_V1_PATH + subPath).build();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
private static String getErrorMessage(HttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
if (ContentType.get(entity).getMimeType().equals(ContentType.APPLICATION_JSON.getMimeType())) {
WireErrorResponse errorResponse = mapper.readValue(content, WireErrorResponse.class);
return errorResponse.message;
}
return content;
}
private static boolean success(HttpResponse response) {
return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
}
private static StringEntity jsonContent(String json) {
return new StringEntity(json, ContentType.APPLICATION_JSON);
}
private static class FlagTargetsHostnameVerifier implements HostnameVerifier {
private final AthenzIdentityVerifier athenzVerifier;
FlagTargetsHostnameVerifier(Set<FlagsTarget> targets) {
this.athenzVerifier = createAthenzIdentityVerifier(targets);
}
private static AthenzIdentityVerifier createAthenzIdentityVerifier(Set<FlagsTarget> targets) {
Set<AthenzIdentity> identities = targets.stream()
.flatMap(target -> target.athenzHttpsIdentity().stream())
.collect(toSet());
return new AthenzIdentityVerifier(identities);
}
@Override
public boolean verify(String hostname, SSLSession session) {
return "localhost".equals(hostname) /* for controllers */ || athenzVerifier.verify(hostname, session);
}
}
static class FlagsException extends RuntimeException {
private FlagsException(int statusCode, FlagsTarget target, String responseMessage) {
this(statusCode, target, null, responseMessage);
}
private FlagsException(int statusCode, FlagsTarget target, FlagId flagId, String responseMessage) {
super(createErrorMessage(statusCode, target, flagId, responseMessage));
}
private static String createErrorMessage(int statusCode, FlagsTarget target, FlagId flagId, String responseMessage) {
StringBuilder builder = new StringBuilder()
.append("Received '").append(statusCode).append("' from '").append(target.endpoint().getHost()).append("'");
if (flagId != null) {
builder.append("' for flag '").append(flagId).append("'");
}
return builder.append(": ").append(responseMessage).toString();
}
}
} | class FlagsClient {
private static final String FLAGS_V1_PATH = "/flags/v1";
private static final ObjectMapper mapper = new ObjectMapper();
private final CloseableHttpClient client;
FlagsClient(ServiceIdentityProvider identityProvider, Set<FlagsTarget> targets) {
this.client = createClient(identityProvider, targets);
}
List<FlagData> listFlagData(FlagsTarget target) throws FlagsException, UncheckedIOException {
HttpGet request = new HttpGet(createUri(target, "/data"));
return executeRequest(request, response -> {
verifySuccess(response, target, null);
return FlagData.deserializeList(EntityUtils.toByteArray(response.getEntity()));
});
}
void putFlagData(FlagsTarget target, FlagData flagData) throws FlagsException, UncheckedIOException {
HttpPut request = new HttpPut(createUri(target, "/data/" + flagData.id().toString()));
request.setEntity(jsonContent(flagData.serializeToJson()));
executeRequest(request, response -> {
verifySuccess(response, target, flagData.id());
return null;
});
}
void deleteFlagData(FlagsTarget target, FlagId flagId) throws FlagsException, UncheckedIOException {
HttpDelete request = new HttpDelete(createUri(target, "/data/" + flagId.toString()));
executeRequest(request, response -> {
verifySuccess(response, target, flagId);
return null;
});
}
private static CloseableHttpClient createClient(ServiceIdentityProvider identityProvider, Set<FlagsTarget> targets) {
return HttpClientBuilder.create()
.setUserAgent("controller-flags-v1-client")
.setRetryHandler(new DefaultHttpRequestRetryHandler(5, /*retry on non-idempotent requests*/true))
.setSslcontext(identityProvider.getIdentitySslContext())
.setSSLHostnameVerifier(new FlagTargetsHostnameVerifier(targets))
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout((int) Duration.ofSeconds(10).toMillis())
.setConnectionRequestTimeout((int) Duration.ofSeconds(10).toMillis())
.setSocketTimeout((int) Duration.ofSeconds(20).toMillis())
.build())
.setMaxConnPerRoute(2)
.setMaxConnTotal(100)
.build();
}
private <T> T executeRequest(HttpUriRequest request, ResponseHandler<T> handler) {
try {
return client.execute(request, handler);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static URI createUri(FlagsTarget target, String subPath) {
try {
return new URIBuilder(target.endpoint()).setPath(FLAGS_V1_PATH + subPath).build();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
private static FlagsException createFlagsException(HttpResponse response, FlagsTarget target, FlagId flagId) throws IOException {
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
int statusCode = response.getStatusLine().getStatusCode();
if (ContentType.get(entity).getMimeType().equals(ContentType.APPLICATION_JSON.getMimeType())) {
WireErrorResponse error = mapper.readValue(content, WireErrorResponse.class);
return new FlagsException(statusCode, target, flagId, error.errorCode, error.message);
} else {
return new FlagsException(statusCode, target, flagId, null, content);
}
}
private static boolean success(HttpResponse response) {
return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
}
private static StringEntity jsonContent(String json) {
return new StringEntity(json, ContentType.APPLICATION_JSON);
}
private static class FlagTargetsHostnameVerifier implements HostnameVerifier {
private final AthenzIdentityVerifier athenzVerifier;
FlagTargetsHostnameVerifier(Set<FlagsTarget> targets) {
this.athenzVerifier = createAthenzIdentityVerifier(targets);
}
private static AthenzIdentityVerifier createAthenzIdentityVerifier(Set<FlagsTarget> targets) {
Set<AthenzIdentity> identities = targets.stream()
.flatMap(target -> target.athenzHttpsIdentity().stream())
.collect(toSet());
return new AthenzIdentityVerifier(identities);
}
@Override
public boolean verify(String hostname, SSLSession session) {
return "localhost".equals(hostname) /* for controllers */ || athenzVerifier.verify(hostname, session);
}
}
static class FlagsException extends RuntimeException {
private FlagsException(int statusCode, FlagsTarget target, FlagId flagId, String errorCode, String errorMessage) {
super(createErrorMessage(statusCode, target, flagId, errorCode, errorMessage));
}
private static String createErrorMessage(int statusCode, FlagsTarget target, FlagId flagId, String errorCode, String errorMessage) {
StringBuilder builder = new StringBuilder().append("Received ").append(statusCode);
if (errorCode != null) {
builder.append('/').append(errorCode);
}
builder.append(" from '").append(target.endpoint().getHost()).append("'");
if (flagId != null) {
builder.append("' for flag '").append(flagId).append("'");
}
return builder.append(": ").append(errorMessage).toString();
}
}
} |
```suggestion triggerJobs(); ``` | public DeploymentContext completeRollout() {
readyJobsTrigger.run();
Set<JobType> jobs = new HashSet<>();
List<Run> activeRuns;
while ( ! (activeRuns = this.jobs.active(applicationId)).isEmpty())
for (Run run : activeRuns)
if (jobs.add(run.id().type())) {
runJob(run.id().type());
readyJobsTrigger.run();
}
else
throw new AssertionError("Job '" + run.id().type() + "' was run twice for '" + instanceId + "'");
assertFalse("Change should have no targets, but was " + application().change(), application().change().hasTargets());
if (!deferDnsUpdates) {
flushDnsUpdates();
}
return this;
} | readyJobsTrigger.run(); | public DeploymentContext completeRollout() {
triggerJobs();
Set<JobType> jobs = new HashSet<>();
List<Run> activeRuns;
while ( ! (activeRuns = this.jobs.active(applicationId)).isEmpty())
for (Run run : activeRuns)
if (jobs.add(run.id().type())) {
runJob(run.id().type());
readyJobsTrigger.run();
}
else
throw new AssertionError("Job '" + run.id().type() + "' was run twice for '" + instanceId + "'");
assertFalse("Change should have no targets, but was " + application().change(), application().change().hasTargets());
if (!deferDnsUpdates) {
flushDnsUpdates();
}
return this;
} | class DeploymentContext {
public static final ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
.upgradePolicy("default")
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.emailRole("author")
.emailAddress("b@a")
.build();
public static final ApplicationPackage publicCdApplicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
.upgradePolicy("default")
.region("aws-us-east-1c")
.emailRole("author")
.emailAddress("b@a")
.trust(generateCertificate())
.build();
private final TenantAndApplicationId applicationId;
private final ApplicationId instanceId;
private final TesterId testerId;
private final JobController jobs;
private final RoutingGeneratorMock routing;
private final MockTesterCloud cloud;
private final JobRunner runner;
private final ControllerTester tester;
private final ReadyJobsTrigger readyJobsTrigger;
private final NameServiceDispatcher nameServiceDispatcher;;
private ApplicationVersion lastSubmission = null;
private boolean deferDnsUpdates = false;
public DeploymentContext(ApplicationId instanceId, InternalDeploymentTester tester) {
this.applicationId = TenantAndApplicationId.from(instanceId);
this.instanceId = instanceId;
this.testerId = TesterId.of(instanceId);
this.jobs = tester.controller().jobController();
this.runner = tester.runner();
this.tester = tester.controllerTester();
this.routing = this.tester.serviceRegistry().routingGeneratorMock();
this.cloud = this.tester.serviceRegistry().testerCloud();
this.readyJobsTrigger = tester.readyJobsTrigger();
this.nameServiceDispatcher = tester.nameServiceDispatcher();
createTenantAndApplication();
}
private void createTenantAndApplication() {
try {
var tenant = tester.createTenant(instanceId.tenant().value());
tester.createApplication(tenant, instanceId.application().value(), instanceId.instance().value());
} catch (IllegalArgumentException ignored) {
}
}
public Application application() {
return tester.controller().applications().requireApplication(applicationId);
}
public Instance instance() {
return tester.controller().applications().requireInstance(instanceId);
}
public ApplicationId instanceId() {
return instanceId;
}
public DeploymentId deploymentIdIn(ZoneId zone) {
return new DeploymentId(instanceId, zone);
}
/** Completely deploy the latest change */
public DeploymentContext deploy() {
assertNotNull("Application package submitted", lastSubmission);
assertFalse("Submission is not already deployed", application().instances().values().stream()
.anyMatch(instance -> instance.deployments().values().stream()
.anyMatch(deployment -> deployment.applicationVersion().equals(lastSubmission))));
assertEquals(lastSubmission, application().change().application().get());
assertFalse(application().change().platform().isPresent());
completeRollout();
assertFalse(application().change().hasTargets());
return this;
}
/** Upgrade platform of this to given version */
public DeploymentContext deployPlatform(Version version) {
assertEquals(tester.controller().systemVersion(), version);
assertFalse(application().instances().values().stream()
.anyMatch(instance -> instance.deployments().values().stream()
.anyMatch(deployment -> deployment.version().equals(version))));
assertEquals(version, application().change().platform().get());
assertFalse(application().change().application().isPresent());
completeRollout();
assertTrue(application().productionDeployments().values().stream()
.allMatch(deployments -> deployments.stream()
.allMatch(deployment -> deployment.version().equals(version))));
for (JobType type : new DeploymentSteps(application().deploymentSpec(), tester.controller()::system).productionJobs())
assertTrue(tester.configServer().nodeRepository()
.list(type.zone(tester.controller().system()), applicationId.defaultInstance()).stream()
.allMatch(node -> node.currentVersion().equals(version)));
assertFalse(application().change().hasTargets());
return this;
}
/** Defer DNS updates */
public DeploymentContext deferDnsUpdates() {
deferDnsUpdates = true;
return this;
}
/** Flush all pending DNS updates */
public DeploymentContext flushDnsUpdates() {
nameServiceDispatcher.run();
assertTrue("All name service requests dispatched",
tester.controller().curator().readNameServiceQueue().requests().isEmpty());
return this;
}
/** Submit given application package for deployment */
public DeploymentContext submit(ApplicationPackage applicationPackage) {
return submit(applicationPackage, BuildJob.defaultSourceRevision);
}
/** Submit given application package for deployment */
public DeploymentContext submit(ApplicationPackage applicationPackage, SourceRevision sourceRevision) {
var projectId = tester.controller().applications()
.requireApplication(applicationId)
.projectId()
.orElseThrow(() -> new IllegalArgumentException("No project ID set for " + applicationId));
lastSubmission = jobs.submit(applicationId, sourceRevision, "a@b", projectId, applicationPackage, new byte[0]);
return this;
}
/** Submit the default application package for deployment */
public DeploymentContext submit() {
return submit(tester.controller().system().isPublic() ? publicCdApplicationPackage : applicationPackage);
}
/** Trigger all outstanding jobs, if any */
public DeploymentContext triggerJobs() {
while (tester.controller().applications().deploymentTrigger().triggerReadyJobs() > 0);
return this;
}
/** Fail current deployment in given job */
public DeploymentContext failDeployment(JobType type) {
triggerJobs();
var job = jobId(type);
RunId id = currentRun(job).id();
configServer().throwOnNextPrepare(new IllegalArgumentException("Exception"));
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasFailed());
assertTrue(jobs.run(id).get().hasEnded());
doTeardown(job);
return this;
}
/** Returns the last submitted application version */
public Optional<ApplicationVersion> lastSubmission() {
return Optional.ofNullable(lastSubmission);
}
/** Runs and returns all remaining jobs for the application, at most once, and asserts the current change is rolled out. */
/** Pulls the ready job trigger, and then runs the whole of the given job, successfully. */
public DeploymentContext runJob(JobType type) {
var job = jobId(type);
triggerJobs();
doDeploy(job);
doUpgrade(job);
doConverge(job);
if (job.type().environment().isManuallyDeployed())
return this;
doInstallTester(job);
doTests(job);
doTeardown(job);
return this;
}
/** Simulate upgrade time out in given job */
public DeploymentContext timeOutUpgrade(JobType type) {
var job = jobId(type);
triggerJobs();
RunId id = currentRun(job).id();
doDeploy(job);
tester.clock().advance(InternalStepRunner.installationTimeout.plusSeconds(1));
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasFailed());
assertTrue(jobs.run(id).get().hasEnded());
doTeardown(job);
return this;
}
/** Simulate convergence time out in given job */
public void timeOutConvergence(JobType type) {
var job = jobId(type);
triggerJobs();
RunId id = currentRun(job).id();
doDeploy(job);
doUpgrade(job);
tester.clock().advance(InternalStepRunner.installationTimeout.plusSeconds(1));
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasFailed());
assertTrue(jobs.run(id).get().hasEnded());
doTeardown(job);
}
/** Sets a single endpoint in the routing layer for the instance in this */
public DeploymentContext setEndpoints(ZoneId zone) {
return setEndpoints(zone, false);
}
/** Deploy default application package, start a run for that change and return its ID */
public RunId newRun(JobType type) {
assertFalse(application().internal());
submit();
readyJobsTrigger.maintain();
if (type.isProduction()) {
runJob(JobType.systemTest);
runJob(JobType.stagingTest);
readyJobsTrigger.maintain();
}
Run run = jobs.active().stream()
.filter(r -> r.id().type() == type)
.findAny()
.orElseThrow(() -> new AssertionError(type + " is not among the active: " + jobs.active()));
return run.id();
}
/** Start tests in system test stage */
public RunId startSystemTestTests() {
RunId id = newRun(JobType.systemTest);
runner.run();
configServer().convergeServices(instanceId, JobType.systemTest.zone(tester.controller().system()));
configServer().convergeServices(testerId.id(), JobType.systemTest.zone(tester.controller().system()));
setEndpoints(JobType.systemTest.zone(tester.controller().system()));
setTesterEndpoints(JobType.systemTest.zone(tester.controller().system()));
runner.run();
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.endTests));
return id;
}
/** Deploys tester and real app, and completes initial staging installation first if needed. */
private void doDeploy(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = zone(job);
DeploymentId deployment = new DeploymentId(job.application(), zone);
runner.advance(currentRun(job));
if (job.type() == JobType.stagingTest) {
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installInitialReal));
Versions versions = currentRun(job).versions();
tester.configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), versions.sourcePlatform().orElse(versions.targetPlatform()));
configServer().convergeServices(id.application(), zone);
setEndpoints(zone);
runner.advance(currentRun(job));
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installInitialReal));
}
}
/** Upgrades nodes to target version. */
private void doUpgrade(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = zone(job);
DeploymentId deployment = new DeploymentId(job.application(), zone);
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), currentRun(job).versions().targetPlatform());
runner.advance(currentRun(job));
}
/** Returns the current run for the given job type, and verifies it is still running normally. */
private Run currentRun(JobId job) {
Run run = jobs.last(job)
.filter(r -> r.id().type() == job.type())
.orElseThrow(() -> new AssertionError(job.type() + " is not among the active: " + jobs.active()));
assertFalse(run.hasFailed());
assertFalse(run.hasEnded());
return run;
}
/** Sets a single endpoint in the routing layer for the tester instance in this */
private DeploymentContext setTesterEndpoints(ZoneId zone) {
return setEndpoints(zone, true);
}
/** Sets a single endpoint in the routing layer; this matches that required for the tester */
private DeploymentContext setEndpoints(ZoneId zone, boolean tester) {
var id = instanceId;
if (tester) {
id = testerId.id();
}
routing.putEndpoints(new DeploymentId(id, zone),
Collections.singletonList(new RoutingEndpoint(String.format("https:
id.instance().value(),
id.application().value(),
id.tenant().value(),
zone.region().value(),
zone.environment().value()),
"host1",
false,
String.format("cluster1.%s.%s.%s.%s",
id.application().value(),
id.tenant().value(),
zone.region().value(),
zone.environment().value()))));
return this;
}
/** Lets nodes converge on new application version. */
private void doConverge(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = zone(job);
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
configServer().convergeServices(id.application(), zone);
setEndpoints(zone);
runner.advance(currentRun(job));
if (job.type().environment().isManuallyDeployed()) {
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installReal));
assertTrue(jobs.run(id).get().hasEnded());
return;
}
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installReal));
}
/** Installs tester and starts tests. */
private void doInstallTester(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = zone(job);
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installTester));
configServer().nodeRepository().doUpgrade(new DeploymentId(TesterId.of(job.application()).id(), zone), Optional.empty(), currentRun(job).versions().targetPlatform());
runner.advance(currentRun(job));
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installTester));
configServer().convergeServices(TesterId.of(id.application()).id(), zone);
runner.advance(currentRun(job));
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installTester));
setTesterEndpoints(zone);
runner.advance(currentRun(job));
}
/** Completes tests with success. */
private void doTests(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = zone(job);
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installReal));
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installTester));
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.startTests));
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.endTests));
cloud.set(TesterCloud.Status.SUCCESS);
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasEnded());
assertFalse(jobs.run(id).get().hasFailed());
assertEquals(job.type().isProduction(), instance().deployments().containsKey(zone));
assertTrue(configServer().nodeRepository().list(zone, TesterId.of(id.application()).id()).isEmpty());
}
/** Removes endpoints from routing layer — always call this. */
private void doTeardown(JobId job) {
ZoneId zone = zone(job);
DeploymentId deployment = new DeploymentId(job.application(), zone);
if ( ! instance().deployments().containsKey(zone))
routing.removeEndpoints(deployment);
routing.removeEndpoints(new DeploymentId(TesterId.of(job.application()).id(), zone));
}
private JobId jobId(JobType type) {
return new JobId(instanceId, type);
}
private ZoneId zone(JobId job) {
return job.type().zone(tester.controller().system());
}
private ConfigServerMock configServer() {
return tester.configServer();
}
private static X509Certificate generateCertificate() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X500Principal subject = new X500Principal("CN=subject");
return X509CertificateBuilder.fromKeypair(keyPair,
subject,
Instant.now(),
Instant.now().plusSeconds(1),
SignatureAlgorithm.SHA512_WITH_ECDSA,
BigInteger.valueOf(1))
.build();
}
} | class DeploymentContext {
public static final ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
.upgradePolicy("default")
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.emailRole("author")
.emailAddress("b@a")
.build();
public static final ApplicationPackage publicCdApplicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
.upgradePolicy("default")
.region("aws-us-east-1c")
.emailRole("author")
.emailAddress("b@a")
.trust(generateCertificate())
.build();
private final TenantAndApplicationId applicationId;
private final ApplicationId instanceId;
private final TesterId testerId;
private final JobController jobs;
private final RoutingGeneratorMock routing;
private final MockTesterCloud cloud;
private final JobRunner runner;
private final ControllerTester tester;
private final ReadyJobsTrigger readyJobsTrigger;
private final NameServiceDispatcher nameServiceDispatcher;;
private ApplicationVersion lastSubmission = null;
private boolean deferDnsUpdates = false;
public DeploymentContext(ApplicationId instanceId, InternalDeploymentTester tester) {
this.applicationId = TenantAndApplicationId.from(instanceId);
this.instanceId = instanceId;
this.testerId = TesterId.of(instanceId);
this.jobs = tester.controller().jobController();
this.runner = tester.runner();
this.tester = tester.controllerTester();
this.routing = this.tester.serviceRegistry().routingGeneratorMock();
this.cloud = this.tester.serviceRegistry().testerCloud();
this.readyJobsTrigger = tester.readyJobsTrigger();
this.nameServiceDispatcher = tester.nameServiceDispatcher();
createTenantAndApplication();
}
private void createTenantAndApplication() {
try {
var tenant = tester.createTenant(instanceId.tenant().value());
tester.createApplication(tenant, instanceId.application().value(), instanceId.instance().value());
} catch (IllegalArgumentException ignored) {
}
}
public Application application() {
return tester.controller().applications().requireApplication(applicationId);
}
public Instance instance() {
return tester.controller().applications().requireInstance(instanceId);
}
public ApplicationId instanceId() {
return instanceId;
}
public DeploymentId deploymentIdIn(ZoneId zone) {
return new DeploymentId(instanceId, zone);
}
/** Completely deploy the latest change */
public DeploymentContext deploy() {
assertNotNull("Application package submitted", lastSubmission);
assertFalse("Submission is not already deployed", application().instances().values().stream()
.anyMatch(instance -> instance.deployments().values().stream()
.anyMatch(deployment -> deployment.applicationVersion().equals(lastSubmission))));
assertEquals(lastSubmission, application().change().application().get());
assertFalse(application().change().platform().isPresent());
completeRollout();
assertFalse(application().change().hasTargets());
return this;
}
/** Upgrade platform of this to given version */
public DeploymentContext deployPlatform(Version version) {
assertEquals(tester.controller().systemVersion(), version);
assertFalse(application().instances().values().stream()
.anyMatch(instance -> instance.deployments().values().stream()
.anyMatch(deployment -> deployment.version().equals(version))));
assertEquals(version, application().change().platform().get());
assertFalse(application().change().application().isPresent());
completeRollout();
assertTrue(application().productionDeployments().values().stream()
.allMatch(deployments -> deployments.stream()
.allMatch(deployment -> deployment.version().equals(version))));
for (JobType type : new DeploymentSteps(application().deploymentSpec(), tester.controller()::system).productionJobs())
assertTrue(tester.configServer().nodeRepository()
.list(type.zone(tester.controller().system()), applicationId.defaultInstance()).stream()
.allMatch(node -> node.currentVersion().equals(version)));
assertFalse(application().change().hasTargets());
return this;
}
/** Defer DNS updates */
public DeploymentContext deferDnsUpdates() {
deferDnsUpdates = true;
return this;
}
/** Flush all pending DNS updates */
public DeploymentContext flushDnsUpdates() {
nameServiceDispatcher.run();
assertTrue("All name service requests dispatched",
tester.controller().curator().readNameServiceQueue().requests().isEmpty());
return this;
}
/** Submit given application package for deployment */
public DeploymentContext submit(ApplicationPackage applicationPackage) {
return submit(applicationPackage, BuildJob.defaultSourceRevision);
}
/** Submit given application package for deployment */
public DeploymentContext submit(ApplicationPackage applicationPackage, SourceRevision sourceRevision) {
var projectId = tester.controller().applications()
.requireApplication(applicationId)
.projectId()
.orElseThrow(() -> new IllegalArgumentException("No project ID set for " + applicationId));
lastSubmission = jobs.submit(applicationId, sourceRevision, "a@b", projectId, applicationPackage, new byte[0]);
return this;
}
/** Submit the default application package for deployment */
public DeploymentContext submit() {
return submit(tester.controller().system().isPublic() ? publicCdApplicationPackage : applicationPackage);
}
/** Trigger all outstanding jobs, if any */
public DeploymentContext triggerJobs() {
while (tester.controller().applications().deploymentTrigger().triggerReadyJobs() > 0);
return this;
}
/** Fail current deployment in given job */
public DeploymentContext failDeployment(JobType type) {
triggerJobs();
var job = jobId(type);
RunId id = currentRun(job).id();
configServer().throwOnNextPrepare(new IllegalArgumentException("Exception"));
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasFailed());
assertTrue(jobs.run(id).get().hasEnded());
doTeardown(job);
return this;
}
/** Returns the last submitted application version */
public Optional<ApplicationVersion> lastSubmission() {
return Optional.ofNullable(lastSubmission);
}
/** Runs and returns all remaining jobs for the application, at most once, and asserts the current change is rolled out. */
/** Pulls the ready job trigger, and then runs the whole of the given job, successfully. */
public DeploymentContext runJob(JobType type) {
var job = jobId(type);
triggerJobs();
doDeploy(job);
doUpgrade(job);
doConverge(job);
if (job.type().environment().isManuallyDeployed())
return this;
doInstallTester(job);
doTests(job);
doTeardown(job);
return this;
}
/** Simulate upgrade time out in given job */
public DeploymentContext timeOutUpgrade(JobType type) {
var job = jobId(type);
triggerJobs();
RunId id = currentRun(job).id();
doDeploy(job);
tester.clock().advance(InternalStepRunner.installationTimeout.plusSeconds(1));
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasFailed());
assertTrue(jobs.run(id).get().hasEnded());
doTeardown(job);
return this;
}
/** Simulate convergence time out in given job */
public void timeOutConvergence(JobType type) {
var job = jobId(type);
triggerJobs();
RunId id = currentRun(job).id();
doDeploy(job);
doUpgrade(job);
tester.clock().advance(InternalStepRunner.installationTimeout.plusSeconds(1));
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasFailed());
assertTrue(jobs.run(id).get().hasEnded());
doTeardown(job);
}
/** Sets a single endpoint in the routing layer for the instance in this */
public DeploymentContext setEndpoints(ZoneId zone) {
return setEndpoints(zone, false);
}
/** Deploy default application package, start a run for that change and return its ID */
public RunId newRun(JobType type) {
assertFalse(application().internal());
submit();
readyJobsTrigger.maintain();
if (type.isProduction()) {
runJob(JobType.systemTest);
runJob(JobType.stagingTest);
readyJobsTrigger.maintain();
}
Run run = jobs.active().stream()
.filter(r -> r.id().type() == type)
.findAny()
.orElseThrow(() -> new AssertionError(type + " is not among the active: " + jobs.active()));
return run.id();
}
/** Start tests in system test stage */
public RunId startSystemTestTests() {
RunId id = newRun(JobType.systemTest);
runner.run();
configServer().convergeServices(instanceId, JobType.systemTest.zone(tester.controller().system()));
configServer().convergeServices(testerId.id(), JobType.systemTest.zone(tester.controller().system()));
setEndpoints(JobType.systemTest.zone(tester.controller().system()));
setTesterEndpoints(JobType.systemTest.zone(tester.controller().system()));
runner.run();
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.endTests));
return id;
}
/** Deploys tester and real app, and completes initial staging installation first if needed. */
private void doDeploy(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = zone(job);
DeploymentId deployment = new DeploymentId(job.application(), zone);
runner.advance(currentRun(job));
if (job.type() == JobType.stagingTest) {
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installInitialReal));
Versions versions = currentRun(job).versions();
tester.configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), versions.sourcePlatform().orElse(versions.targetPlatform()));
configServer().convergeServices(id.application(), zone);
setEndpoints(zone);
runner.advance(currentRun(job));
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installInitialReal));
}
}
/** Upgrades nodes to target version. */
private void doUpgrade(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = zone(job);
DeploymentId deployment = new DeploymentId(job.application(), zone);
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), currentRun(job).versions().targetPlatform());
runner.advance(currentRun(job));
}
/** Returns the current run for the given job type, and verifies it is still running normally. */
private Run currentRun(JobId job) {
Run run = jobs.last(job)
.filter(r -> r.id().type() == job.type())
.orElseThrow(() -> new AssertionError(job.type() + " is not among the active: " + jobs.active()));
assertFalse(run.hasFailed());
assertFalse(run.hasEnded());
return run;
}
/** Sets a single endpoint in the routing layer for the tester instance in this */
private DeploymentContext setTesterEndpoints(ZoneId zone) {
return setEndpoints(zone, true);
}
/** Sets a single endpoint in the routing layer; this matches that required for the tester */
private DeploymentContext setEndpoints(ZoneId zone, boolean tester) {
var id = instanceId;
if (tester) {
id = testerId.id();
}
routing.putEndpoints(new DeploymentId(id, zone),
Collections.singletonList(new RoutingEndpoint(String.format("https:
id.instance().value(),
id.application().value(),
id.tenant().value(),
zone.region().value(),
zone.environment().value()),
"host1",
false,
String.format("cluster1.%s.%s.%s.%s",
id.application().value(),
id.tenant().value(),
zone.region().value(),
zone.environment().value()))));
return this;
}
/** Lets nodes converge on new application version. */
private void doConverge(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = zone(job);
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
configServer().convergeServices(id.application(), zone);
setEndpoints(zone);
runner.advance(currentRun(job));
if (job.type().environment().isManuallyDeployed()) {
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installReal));
assertTrue(jobs.run(id).get().hasEnded());
return;
}
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installReal));
}
/** Installs tester and starts tests. */
private void doInstallTester(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = zone(job);
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installTester));
configServer().nodeRepository().doUpgrade(new DeploymentId(TesterId.of(job.application()).id(), zone), Optional.empty(), currentRun(job).versions().targetPlatform());
runner.advance(currentRun(job));
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installTester));
configServer().convergeServices(TesterId.of(id.application()).id(), zone);
runner.advance(currentRun(job));
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installTester));
setTesterEndpoints(zone);
runner.advance(currentRun(job));
}
/** Completes tests with success. */
private void doTests(JobId job) {
RunId id = currentRun(job).id();
ZoneId zone = zone(job);
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installReal));
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.installTester));
assertEquals(Step.Status.succeeded, jobs.run(id).get().steps().get(Step.startTests));
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.endTests));
cloud.set(TesterCloud.Status.SUCCESS);
runner.advance(currentRun(job));
assertTrue(jobs.run(id).get().hasEnded());
assertFalse(jobs.run(id).get().hasFailed());
assertEquals(job.type().isProduction(), instance().deployments().containsKey(zone));
assertTrue(configServer().nodeRepository().list(zone, TesterId.of(id.application()).id()).isEmpty());
}
/** Removes endpoints from routing layer — always call this. */
private void doTeardown(JobId job) {
ZoneId zone = zone(job);
DeploymentId deployment = new DeploymentId(job.application(), zone);
if ( ! instance().deployments().containsKey(zone))
routing.removeEndpoints(deployment);
routing.removeEndpoints(new DeploymentId(TesterId.of(job.application()).id(), zone));
}
private JobId jobId(JobType type) {
return new JobId(instanceId, type);
}
private ZoneId zone(JobId job) {
return job.type().zone(tester.controller().system());
}
private ConfigServerMock configServer() {
return tester.configServer();
}
private static X509Certificate generateCertificate() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X500Principal subject = new X500Principal("CN=subject");
return X509CertificateBuilder.fromKeypair(keyPair,
subject,
Instant.now(),
Instant.now().plusSeconds(1),
SignatureAlgorithm.SHA512_WITH_ECDSA,
BigInteger.valueOf(1))
.build();
}
} |
Collectors.toSet() makes no guarantee about the mutability of the returned Set: "There are no guarantees on the type, mutability, ...". Because of this I have never tried nor seen a `.add` so I guess it works... But consider using the toSet(Supplier) instead. | private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
var deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toSet());
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.applications().clusterEndpoints(deployments),
controller.applications().contentClustersByZone(deployments)));
} | deployments.add(new DeploymentId(id, testedZone)); | private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
var deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toSet());
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.applications().clusterEndpoints(deployments),
controller.applications().contentClustersByZone(deployments)));
} | 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}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), 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) {
Set<YearMonth> months = controller.serviceRegistry().tenantCost().monthsWithMetering(tenant.name());
var slime = new Slime();
var objectCursor = slime.setObject();
var monthsCursor = objectCursor.setArray("months");
months.forEach(month -> monthsCursor.addString(month.toString()));
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 YearMonth tenantCostParseDate(String dateString) {
try {
return YearMonth.parse(dateString);
} catch (DateTimeParseException e){
throw new IllegalArgumentException("Could not parse year-month '" + dateString + "'");
}
}
private HttpResponse tenantCost(Tenant tenant, YearMonth month, HttpRequest request) {
var slime = new Slime();
Cursor cursor = slime.setObject();
cursor.setString("month", month.toString());
List<CostInfo> costInfos = controller.serviceRegistry().tenantCost()
.getTenantCostOfMonth(tenant.name(), month);
Cursor array = cursor.setArray("items");
costInfos.forEach(costInfo -> {
Cursor costObject = array.addObject();
costObject.setString("applicationId", costInfo.getApplicationId().serializedForm());
costObject.setString("zoneId", costInfo.getZoneId().value());
Cursor cpu = costObject.setObject("cpu");
cpu.setDouble("usage", costInfo.getCpuHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
cpu.setLong("charge", costInfo.getCpuCost());
Cursor memory = costObject.setObject("memory");
memory.setDouble("usage", costInfo.getMemoryHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
memory.setLong("charge", costInfo.getMemoryCost());
Cursor disk = costObject.setObject("disk");
disk.setDouble("usage", costInfo.getDiskHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
disk.setLong("charge", costInfo.getDiskCost());
});
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 applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse 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, 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());
}
}
}
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(TenantName.from(tenant), ApplicationName.from(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 +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<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));
}
}
/** Returns test config for indicated job, with production deployments of the default instance. */
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'");
if (applicationPackage.deploymentSpec().instances().size() != 1)
throw new IllegalArgumentException("Only single-instance deployment specs are currently supported");
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}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), 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) {
Set<YearMonth> months = controller.serviceRegistry().tenantCost().monthsWithMetering(tenant.name());
var slime = new Slime();
var objectCursor = slime.setObject();
var monthsCursor = objectCursor.setArray("months");
months.forEach(month -> monthsCursor.addString(month.toString()));
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 YearMonth tenantCostParseDate(String dateString) {
try {
return YearMonth.parse(dateString);
} catch (DateTimeParseException e){
throw new IllegalArgumentException("Could not parse year-month '" + dateString + "'");
}
}
private HttpResponse tenantCost(Tenant tenant, YearMonth month, HttpRequest request) {
var slime = new Slime();
Cursor cursor = slime.setObject();
cursor.setString("month", month.toString());
List<CostInfo> costInfos = controller.serviceRegistry().tenantCost()
.getTenantCostOfMonth(tenant.name(), month);
Cursor array = cursor.setArray("items");
costInfos.forEach(costInfo -> {
Cursor costObject = array.addObject();
costObject.setString("applicationId", costInfo.getApplicationId().serializedForm());
costObject.setString("zoneId", costInfo.getZoneId().value());
Cursor cpu = costObject.setObject("cpu");
cpu.setDouble("usage", costInfo.getCpuHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
cpu.setLong("charge", costInfo.getCpuCost());
Cursor memory = costObject.setObject("memory");
memory.setDouble("usage", costInfo.getMemoryHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
memory.setLong("charge", costInfo.getMemoryCost());
Cursor disk = costObject.setObject("disk");
disk.setDouble("usage", costInfo.getDiskHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
disk.setLong("charge", costInfo.getDiskCost());
});
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 applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse 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, 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());
}
}
}
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(TenantName.from(tenant), ApplicationName.from(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 +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<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));
}
}
/** Returns test config for indicated job, with production deployments of the default instance. */
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'");
if (applicationPackage.deploymentSpec().instances().size() != 1)
throw new IllegalArgumentException("Only single-instance deployment specs are currently supported");
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";
}
} |
So tests are only run on the default instance because non-default instances are assumed to be tested implicitly by testing the default? But someone set up only non-default instances? | private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
var deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toSet());
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.applications().clusterEndpoints(deployments),
controller.applications().contentClustersByZone(deployments)));
} | private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
var deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toSet());
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.applications().clusterEndpoints(deployments),
controller.applications().contentClustersByZone(deployments)));
} | 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}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), 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) {
Set<YearMonth> months = controller.serviceRegistry().tenantCost().monthsWithMetering(tenant.name());
var slime = new Slime();
var objectCursor = slime.setObject();
var monthsCursor = objectCursor.setArray("months");
months.forEach(month -> monthsCursor.addString(month.toString()));
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 YearMonth tenantCostParseDate(String dateString) {
try {
return YearMonth.parse(dateString);
} catch (DateTimeParseException e){
throw new IllegalArgumentException("Could not parse year-month '" + dateString + "'");
}
}
private HttpResponse tenantCost(Tenant tenant, YearMonth month, HttpRequest request) {
var slime = new Slime();
Cursor cursor = slime.setObject();
cursor.setString("month", month.toString());
List<CostInfo> costInfos = controller.serviceRegistry().tenantCost()
.getTenantCostOfMonth(tenant.name(), month);
Cursor array = cursor.setArray("items");
costInfos.forEach(costInfo -> {
Cursor costObject = array.addObject();
costObject.setString("applicationId", costInfo.getApplicationId().serializedForm());
costObject.setString("zoneId", costInfo.getZoneId().value());
Cursor cpu = costObject.setObject("cpu");
cpu.setDouble("usage", costInfo.getCpuHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
cpu.setLong("charge", costInfo.getCpuCost());
Cursor memory = costObject.setObject("memory");
memory.setDouble("usage", costInfo.getMemoryHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
memory.setLong("charge", costInfo.getMemoryCost());
Cursor disk = costObject.setObject("disk");
disk.setDouble("usage", costInfo.getDiskHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
disk.setLong("charge", costInfo.getDiskCost());
});
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 applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse 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, 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());
}
}
}
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(TenantName.from(tenant), ApplicationName.from(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 +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<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));
}
}
/** Returns test config for indicated job, with production deployments of the default instance. */
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'");
if (applicationPackage.deploymentSpec().instances().size() != 1)
throw new IllegalArgumentException("Only single-instance deployment specs are currently supported");
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}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), 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) {
Set<YearMonth> months = controller.serviceRegistry().tenantCost().monthsWithMetering(tenant.name());
var slime = new Slime();
var objectCursor = slime.setObject();
var monthsCursor = objectCursor.setArray("months");
months.forEach(month -> monthsCursor.addString(month.toString()));
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 YearMonth tenantCostParseDate(String dateString) {
try {
return YearMonth.parse(dateString);
} catch (DateTimeParseException e){
throw new IllegalArgumentException("Could not parse year-month '" + dateString + "'");
}
}
private HttpResponse tenantCost(Tenant tenant, YearMonth month, HttpRequest request) {
var slime = new Slime();
Cursor cursor = slime.setObject();
cursor.setString("month", month.toString());
List<CostInfo> costInfos = controller.serviceRegistry().tenantCost()
.getTenantCostOfMonth(tenant.name(), month);
Cursor array = cursor.setArray("items");
costInfos.forEach(costInfo -> {
Cursor costObject = array.addObject();
costObject.setString("applicationId", costInfo.getApplicationId().serializedForm());
costObject.setString("zoneId", costInfo.getZoneId().value());
Cursor cpu = costObject.setObject("cpu");
cpu.setDouble("usage", costInfo.getCpuHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
cpu.setLong("charge", costInfo.getCpuCost());
Cursor memory = costObject.setObject("memory");
memory.setDouble("usage", costInfo.getMemoryHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
memory.setLong("charge", costInfo.getMemoryCost());
Cursor disk = costObject.setObject("disk");
disk.setDouble("usage", costInfo.getDiskHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
disk.setLong("charge", costInfo.getDiskCost());
});
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 applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse 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, 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());
}
}
}
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(TenantName.from(tenant), ApplicationName.from(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 +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<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));
}
}
/** Returns test config for indicated job, with production deployments of the default instance. */
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'");
if (applicationPackage.deploymentSpec().instances().size() != 1)
throw new IllegalArgumentException("Only single-instance deployment specs are currently supported");
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";
}
} | |
The assumption is that only the "default" instance is defined in deployment.xml for now, and config for a production job is therefore aimed at one of its deployments — not the user's `dev` instance, and not the user's non-existent production deployments :P Will need to expose instances in the test config API, but will do later. | private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
var deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toSet());
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.applications().clusterEndpoints(deployments),
controller.applications().contentClustersByZone(deployments)));
} | private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
var deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toSet());
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.applications().clusterEndpoints(deployments),
controller.applications().contentClustersByZone(deployments)));
} | 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}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), 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) {
Set<YearMonth> months = controller.serviceRegistry().tenantCost().monthsWithMetering(tenant.name());
var slime = new Slime();
var objectCursor = slime.setObject();
var monthsCursor = objectCursor.setArray("months");
months.forEach(month -> monthsCursor.addString(month.toString()));
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 YearMonth tenantCostParseDate(String dateString) {
try {
return YearMonth.parse(dateString);
} catch (DateTimeParseException e){
throw new IllegalArgumentException("Could not parse year-month '" + dateString + "'");
}
}
private HttpResponse tenantCost(Tenant tenant, YearMonth month, HttpRequest request) {
var slime = new Slime();
Cursor cursor = slime.setObject();
cursor.setString("month", month.toString());
List<CostInfo> costInfos = controller.serviceRegistry().tenantCost()
.getTenantCostOfMonth(tenant.name(), month);
Cursor array = cursor.setArray("items");
costInfos.forEach(costInfo -> {
Cursor costObject = array.addObject();
costObject.setString("applicationId", costInfo.getApplicationId().serializedForm());
costObject.setString("zoneId", costInfo.getZoneId().value());
Cursor cpu = costObject.setObject("cpu");
cpu.setDouble("usage", costInfo.getCpuHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
cpu.setLong("charge", costInfo.getCpuCost());
Cursor memory = costObject.setObject("memory");
memory.setDouble("usage", costInfo.getMemoryHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
memory.setLong("charge", costInfo.getMemoryCost());
Cursor disk = costObject.setObject("disk");
disk.setDouble("usage", costInfo.getDiskHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
disk.setLong("charge", costInfo.getDiskCost());
});
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 applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse 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, 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());
}
}
}
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(TenantName.from(tenant), ApplicationName.from(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 +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<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));
}
}
/** Returns test config for indicated job, with production deployments of the default instance. */
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'");
if (applicationPackage.deploymentSpec().instances().size() != 1)
throw new IllegalArgumentException("Only single-instance deployment specs are currently supported");
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}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), 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) {
Set<YearMonth> months = controller.serviceRegistry().tenantCost().monthsWithMetering(tenant.name());
var slime = new Slime();
var objectCursor = slime.setObject();
var monthsCursor = objectCursor.setArray("months");
months.forEach(month -> monthsCursor.addString(month.toString()));
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 YearMonth tenantCostParseDate(String dateString) {
try {
return YearMonth.parse(dateString);
} catch (DateTimeParseException e){
throw new IllegalArgumentException("Could not parse year-month '" + dateString + "'");
}
}
private HttpResponse tenantCost(Tenant tenant, YearMonth month, HttpRequest request) {
var slime = new Slime();
Cursor cursor = slime.setObject();
cursor.setString("month", month.toString());
List<CostInfo> costInfos = controller.serviceRegistry().tenantCost()
.getTenantCostOfMonth(tenant.name(), month);
Cursor array = cursor.setArray("items");
costInfos.forEach(costInfo -> {
Cursor costObject = array.addObject();
costObject.setString("applicationId", costInfo.getApplicationId().serializedForm());
costObject.setString("zoneId", costInfo.getZoneId().value());
Cursor cpu = costObject.setObject("cpu");
cpu.setDouble("usage", costInfo.getCpuHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
cpu.setLong("charge", costInfo.getCpuCost());
Cursor memory = costObject.setObject("memory");
memory.setDouble("usage", costInfo.getMemoryHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
memory.setLong("charge", costInfo.getMemoryCost());
Cursor disk = costObject.setObject("disk");
disk.setDouble("usage", costInfo.getDiskHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
disk.setLong("charge", costInfo.getDiskCost());
});
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 applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse 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, 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());
}
}
}
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(TenantName.from(tenant), ApplicationName.from(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 +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<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));
}
}
/** Returns test config for indicated job, with production deployments of the default instance. */
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'");
if (applicationPackage.deploymentSpec().instances().size() != 1)
throw new IllegalArgumentException("Only single-instance deployment specs are currently supported");
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";
}
} | |
Will do. | private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
var deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toSet());
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.applications().clusterEndpoints(deployments),
controller.applications().contentClustersByZone(deployments)));
} | deployments.add(new DeploymentId(id, testedZone)); | private HttpResponse testConfig(ApplicationId id, JobType type) {
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
var deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toSet());
var testedZone = type.zone(controller.system());
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.applications().clusterEndpoints(deployments),
controller.applications().contentClustersByZone(deployments)));
} | 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}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), 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) {
Set<YearMonth> months = controller.serviceRegistry().tenantCost().monthsWithMetering(tenant.name());
var slime = new Slime();
var objectCursor = slime.setObject();
var monthsCursor = objectCursor.setArray("months");
months.forEach(month -> monthsCursor.addString(month.toString()));
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 YearMonth tenantCostParseDate(String dateString) {
try {
return YearMonth.parse(dateString);
} catch (DateTimeParseException e){
throw new IllegalArgumentException("Could not parse year-month '" + dateString + "'");
}
}
private HttpResponse tenantCost(Tenant tenant, YearMonth month, HttpRequest request) {
var slime = new Slime();
Cursor cursor = slime.setObject();
cursor.setString("month", month.toString());
List<CostInfo> costInfos = controller.serviceRegistry().tenantCost()
.getTenantCostOfMonth(tenant.name(), month);
Cursor array = cursor.setArray("items");
costInfos.forEach(costInfo -> {
Cursor costObject = array.addObject();
costObject.setString("applicationId", costInfo.getApplicationId().serializedForm());
costObject.setString("zoneId", costInfo.getZoneId().value());
Cursor cpu = costObject.setObject("cpu");
cpu.setDouble("usage", costInfo.getCpuHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
cpu.setLong("charge", costInfo.getCpuCost());
Cursor memory = costObject.setObject("memory");
memory.setDouble("usage", costInfo.getMemoryHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
memory.setLong("charge", costInfo.getMemoryCost());
Cursor disk = costObject.setObject("disk");
disk.setDouble("usage", costInfo.getDiskHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
disk.setLong("charge", costInfo.getDiskCost());
});
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 applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse 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, 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());
}
}
}
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(TenantName.from(tenant), ApplicationName.from(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 +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<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));
}
}
/** Returns test config for indicated job, with production deployments of the default instance. */
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'");
if (applicationPackage.deploymentSpec().instances().size() != 1)
throw new IllegalArgumentException("Only single-instance deployment specs are currently supported");
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}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), 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) {
Set<YearMonth> months = controller.serviceRegistry().tenantCost().monthsWithMetering(tenant.name());
var slime = new Slime();
var objectCursor = slime.setObject();
var monthsCursor = objectCursor.setArray("months");
months.forEach(month -> monthsCursor.addString(month.toString()));
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 YearMonth tenantCostParseDate(String dateString) {
try {
return YearMonth.parse(dateString);
} catch (DateTimeParseException e){
throw new IllegalArgumentException("Could not parse year-month '" + dateString + "'");
}
}
private HttpResponse tenantCost(Tenant tenant, YearMonth month, HttpRequest request) {
var slime = new Slime();
Cursor cursor = slime.setObject();
cursor.setString("month", month.toString());
List<CostInfo> costInfos = controller.serviceRegistry().tenantCost()
.getTenantCostOfMonth(tenant.name(), month);
Cursor array = cursor.setArray("items");
costInfos.forEach(costInfo -> {
Cursor costObject = array.addObject();
costObject.setString("applicationId", costInfo.getApplicationId().serializedForm());
costObject.setString("zoneId", costInfo.getZoneId().value());
Cursor cpu = costObject.setObject("cpu");
cpu.setDouble("usage", costInfo.getCpuHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
cpu.setLong("charge", costInfo.getCpuCost());
Cursor memory = costObject.setObject("memory");
memory.setDouble("usage", costInfo.getMemoryHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
memory.setLong("charge", costInfo.getMemoryCost());
Cursor disk = costObject.setObject("disk");
disk.setDouble("usage", costInfo.getDiskHours().setScale(1, RoundingMode.HALF_UP).doubleValue());
disk.setLong("charge", costInfo.getDiskCost());
});
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 applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
var applicationId = ApplicationId.from(tenantName, applicationName, InstanceName.defaultName().value());
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) {
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse 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, 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());
}
}
}
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(TenantName.from(tenant), ApplicationName.from(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 +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = ZoneId.from(environment, region);
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
/*
* Special handling of the proxy application (the only system application with an application package)
* Setting any other deployOptions here is not supported for now (e.g. specifying version), but
* this might be handy later to handle emergency downgrades.
*/
boolean isZoneApplication = SystemApplication.proxy.id().equals(applicationId);
if (isZoneApplication) {
String versionStr = deployOptions.field("vespaVersion").asString();
boolean versionPresent = !versionStr.isEmpty() && !versionStr.equals("null");
if (versionPresent) {
throw new RuntimeException("Version not supported for system applications");
}
if (controller.versionStatus().isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = controller.versionStatus().systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(SystemApplication.proxy, zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
/*
* Normal applications from here
*/
Optional<ApplicationPackage> applicationPackage = Optional.ofNullable(dataParts.get("applicationZip"))
.map(ApplicationPackage::new);
Optional<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));
}
}
/** Returns test config for indicated job, with production deployments of the default instance. */
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'");
if (applicationPackage.deploymentSpec().instances().size() != 1)
throw new IllegalArgumentException("Only single-instance deployment specs are currently supported");
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";
}
} |
I do not think you want these debug statements lying around. | public static CompiledQueryProfile compile(QueryProfile in, CompiledQueryProfileRegistry registry) {
try {
DimensionalMap.Builder<CompoundName, Object> values = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, QueryProfileType> types = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, Object> references = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, Object> unoverridables = new DimensionalMap.Builder<>();
System.out.println("Compiling " + in.toString());
Set<DimensionBindingForPath> variants = collectVariants(CompoundName.empty, in, DimensionBinding.nullBinding);
variants.add(new DimensionBindingForPath(DimensionBinding.nullBinding, CompoundName.empty));
log.fine(() -> "Compiling " + in.toString() + " having " + variants.size() + " variants");
for (DimensionBindingForPath variant : variants) {
log.finer(() -> " Compiling variant " + variant);
System.out.println(" Compiling variant " + variant);
for (Map.Entry<String, Object> entry : in.listValues(variant.path(), variant.binding().getContext(), null).entrySet()) {
values.put(variant.path().append(entry.getKey()), variant.binding(), entry.getValue());
}
for (Map.Entry<CompoundName, QueryProfileType> entry : in.listTypes(variant.path(), variant.binding().getContext()).entrySet())
types.put(variant.path().append(entry.getKey()), variant.binding(), entry.getValue());
for (CompoundName reference : in.listReferences(variant.path(), variant.binding().getContext()))
references.put(variant.path().append(reference), variant.binding(), Boolean.TRUE);
for (CompoundName name : in.listUnoverridable(variant.path(), variant.binding().getContext()))
unoverridables.put(variant.path().append(name), variant.binding(), Boolean.TRUE);
}
return new CompiledQueryProfile(in.getId(), in.getType(),
values.build(), types.build(), references.build(), unoverridables.build(),
registry);
}
catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid " + in, e);
}
} | System.out.println(" Compiling variant " + variant); | public static CompiledQueryProfile compile(QueryProfile in, CompiledQueryProfileRegistry registry) {
try {
DimensionalMap.Builder<CompoundName, Object> values = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, QueryProfileType> types = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, Object> references = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, Object> unoverridables = new DimensionalMap.Builder<>();
System.out.println("Compiling " + in.toString());
Set<DimensionBindingForPath> variants = collectVariants(CompoundName.empty, in, DimensionBinding.nullBinding);
variants.add(new DimensionBindingForPath(DimensionBinding.nullBinding, CompoundName.empty));
log.fine(() -> "Compiling " + in.toString() + " having " + variants.size() + " variants");
for (DimensionBindingForPath variant : variants) {
log.finer(() -> " Compiling variant " + variant);
System.out.println(" Compiling variant " + variant);
for (Map.Entry<String, Object> entry : in.listValues(variant.path(), variant.binding().getContext(), null).entrySet()) {
values.put(variant.path().append(entry.getKey()), variant.binding(), entry.getValue());
}
for (Map.Entry<CompoundName, QueryProfileType> entry : in.listTypes(variant.path(), variant.binding().getContext()).entrySet())
types.put(variant.path().append(entry.getKey()), variant.binding(), entry.getValue());
for (CompoundName reference : in.listReferences(variant.path(), variant.binding().getContext()))
references.put(variant.path().append(reference), variant.binding(), Boolean.TRUE);
for (CompoundName name : in.listUnoverridable(variant.path(), variant.binding().getContext()))
unoverridables.put(variant.path().append(name), variant.binding(), Boolean.TRUE);
}
return new CompiledQueryProfile(in.getId(), in.getType(),
values.build(), types.build(), references.build(), unoverridables.build(),
registry);
}
catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid " + in, e);
}
} | class QueryProfileCompiler {
private static final Logger log = Logger.getLogger(QueryProfileCompiler.class.getName());
public static CompiledQueryProfileRegistry compile(QueryProfileRegistry input) {
CompiledQueryProfileRegistry output = new CompiledQueryProfileRegistry(input.getTypeRegistry());
for (QueryProfile inputProfile : input.allComponents()) {
output.register(compile(inputProfile, output));
}
return output;
}
/**
* Returns all the unique combinations of dimension values which have values reachable from this profile.
*
* @param profile the profile we are collecting the variants of
* @param currentVariant the variant we must have to arrive at this point in the query profile graph
*/
private static Set<DimensionBindingForPath> collectVariants(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
variants.addAll(collectVariantsFromValues(path, profile.getContent(), currentVariant));
variants.addAll(collectVariantsInThis(path, profile, currentVariant));
if (profile instanceof BackedOverridableQueryProfile)
variants.addAll(collectVariantsInThis(path, ((BackedOverridableQueryProfile) profile).getBacking(), currentVariant));
Set<DimensionBindingForPath> parentVariants;
for (QueryProfile inheritedProfile : profile.inherited()) {
parentVariants = collectVariants(path, inheritedProfile, currentVariant);
variants.addAll(parentVariants);
variants.addAll(combined(variants, parentVariants));
}
variants.addAll(wildcardExpanded(variants));
return variants;
}
/**
* For variants which are underspecified we must explicitly resolve each possible combination
* of actual left-side values.
*
* I.e if we have the variants [-,b=b1], [a=a1,-], [a=a2,-],
* this returns the variants [a=a1,b=b1], [a=a2,b=b1]
*
* This is necessary because left-specified values takes precedence, such that resolving [a=a1,b=b1] would
* lead us to the compiled profile [a=a1,-], which may contain default values for properties where
* we should have preferred variant values in [-,b=b1].
*/
private static Set<DimensionBindingForPath> wildcardExpanded(Set<DimensionBindingForPath> variants) {
Set<DimensionBindingForPath> expanded = new HashSet<>();
for (var variant : variants) {
if (hasWildcardBeforeEnd(variant.binding()))
expanded.addAll(wildcardExpanded(variant, variants));
}
return expanded;
}
private static boolean hasWildcardBeforeEnd(DimensionBinding variant) {
for (int i = 0; i < variant.getValues().size() - 1; i++) {
if (variant.getValues().get(i) == null)
return true;
}
return false;
}
private static Set<DimensionBindingForPath> wildcardExpanded(DimensionBindingForPath variantToExpand,
Set<DimensionBindingForPath> variants) {
Set<DimensionBindingForPath> expanded = new HashSet<>();
for (var variant : variants) {
if (variant.binding().isNull()) continue;
DimensionBinding combined = variantToExpand.binding().combineWith(variant.binding());
if ( ! combined.isInvalid() ) {
expanded.add(new DimensionBindingForPath(combined, variantToExpand.path()));
}
}
return expanded;
}
/** Generates a set of all the (legal) combinations of the variants in the given sets */
private static Set<DimensionBindingForPath> combined(Set<DimensionBindingForPath> v1s,
Set<DimensionBindingForPath> v2s) {
Set<DimensionBindingForPath> combinedVariants = new HashSet<>();
for (DimensionBindingForPath v1 : v1s) {
if (v1.binding().isNull()) continue;
for (DimensionBindingForPath v2 : v2s) {
if (v1.binding().isNull()) continue;
DimensionBinding combined = v1.binding().combineWith(v2.binding());
if ( combined.isInvalid() ) continue;
combinedVariants.add(new DimensionBindingForPath(combined, v1.path()));
}
}
return combinedVariants;
}
private static Set<DimensionBindingForPath> collectVariantsInThis(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
QueryProfileVariants profileVariants = profile.getVariants();
Set<DimensionBindingForPath> variants = new HashSet<>();
if (profileVariants != null) {
for (QueryProfileVariant variant : profile.getVariants().getVariants()) {
DimensionBinding combinedVariant =
DimensionBinding.createFrom(profile.getDimensions(), variant.getDimensionValues()).combineWith(currentVariant);
if (combinedVariant.isInvalid()) continue;
variants.addAll(collectVariantsFromValues(path, variant.values(), combinedVariant));
for (QueryProfile variantInheritedProfile : variant.inherited())
variants.addAll(collectVariants(path, variantInheritedProfile, combinedVariant));
}
}
return variants;
}
private static Set<DimensionBindingForPath> collectVariantsFromValues(CompoundName path,
Map<String, Object> values,
DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
if ( ! values.isEmpty())
variants.add(new DimensionBindingForPath(currentVariant, path));
for (Map.Entry<String, Object> entry : values.entrySet()) {
if (entry.getValue() instanceof QueryProfile)
variants.addAll(collectVariants(path.append(entry.getKey()), (QueryProfile)entry.getValue(), currentVariant));
}
return variants;
}
private static class DimensionBindingForPath {
private final DimensionBinding binding;
private final CompoundName path;
public DimensionBindingForPath(DimensionBinding binding, CompoundName path) {
this.binding = binding;
this.path = path;
}
public DimensionBinding binding() { return binding; }
public CompoundName path() { return path; }
@Override
public boolean equals(Object o) {
if ( o == this ) return true;
if ( ! (o instanceof DimensionBindingForPath)) return false;
DimensionBindingForPath other = (DimensionBindingForPath)o;
return other.binding.equals(this.binding) && other.path.equals(this.path);
}
@Override
public int hashCode() {
return binding.hashCode() + 17*path.hashCode();
}
@Override
public String toString() {
return binding + " for path " + path;
}
}
} | class QueryProfileCompiler {
private static final Logger log = Logger.getLogger(QueryProfileCompiler.class.getName());
public static CompiledQueryProfileRegistry compile(QueryProfileRegistry input) {
CompiledQueryProfileRegistry output = new CompiledQueryProfileRegistry(input.getTypeRegistry());
for (QueryProfile inputProfile : input.allComponents()) {
output.register(compile(inputProfile, output));
}
return output;
}
/**
* Returns all the unique combinations of dimension values which have values reachable from this profile.
*
* @param profile the profile we are collecting the variants of
* @param currentVariant the variant we must have to arrive at this point in the query profile graph
*/
private static Set<DimensionBindingForPath> collectVariants(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
variants.addAll(collectVariantsFromValues(path, profile.getContent(), currentVariant));
variants.addAll(collectVariantsInThis(path, profile, currentVariant));
if (profile instanceof BackedOverridableQueryProfile)
variants.addAll(collectVariantsInThis(path, ((BackedOverridableQueryProfile) profile).getBacking(), currentVariant));
Set<DimensionBindingForPath> parentVariants;
for (QueryProfile inheritedProfile : profile.inherited()) {
parentVariants = collectVariants(path, inheritedProfile, currentVariant);
variants.addAll(parentVariants);
variants.addAll(combined(variants, parentVariants));
}
variants.addAll(wildcardExpanded(variants));
return variants;
}
/**
* For variants which are underspecified we must explicitly resolve each possible combination
* of actual left-side values.
*
* I.e if we have the variants [-,b=b1], [a=a1,-], [a=a2,-],
* this returns the variants [a=a1,b=b1], [a=a2,b=b1]
*
* This is necessary because left-specified values takes precedence, such that resolving [a=a1,b=b1] would
* lead us to the compiled profile [a=a1,-], which may contain default values for properties where
* we should have preferred variant values in [-,b=b1].
*/
private static Set<DimensionBindingForPath> wildcardExpanded(Set<DimensionBindingForPath> variants) {
Set<DimensionBindingForPath> expanded = new HashSet<>();
for (var variant : variants) {
if (hasWildcardBeforeEnd(variant.binding()))
expanded.addAll(wildcardExpanded(variant, variants));
}
return expanded;
}
private static boolean hasWildcardBeforeEnd(DimensionBinding variant) {
for (int i = 0; i < variant.getValues().size() - 1; i++) {
if (variant.getValues().get(i) == null)
return true;
}
return false;
}
private static Set<DimensionBindingForPath> wildcardExpanded(DimensionBindingForPath variantToExpand,
Set<DimensionBindingForPath> variants) {
Set<DimensionBindingForPath> expanded = new HashSet<>();
for (var variant : variants) {
if (variant.binding().isNull()) continue;
DimensionBinding combined = variantToExpand.binding().combineWith(variant.binding());
if ( ! combined.isInvalid() ) {
expanded.add(new DimensionBindingForPath(combined, variantToExpand.path()));
}
}
return expanded;
}
/** Generates a set of all the (legal) combinations of the variants in the given sets */
private static Set<DimensionBindingForPath> combined(Set<DimensionBindingForPath> v1s,
Set<DimensionBindingForPath> v2s) {
Set<DimensionBindingForPath> combinedVariants = new HashSet<>();
for (DimensionBindingForPath v1 : v1s) {
if (v1.binding().isNull()) continue;
for (DimensionBindingForPath v2 : v2s) {
if (v1.binding().isNull()) continue;
DimensionBinding combined = v1.binding().combineWith(v2.binding());
if ( combined.isInvalid() ) continue;
combinedVariants.add(new DimensionBindingForPath(combined, v1.path()));
}
}
return combinedVariants;
}
private static Set<DimensionBindingForPath> collectVariantsInThis(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
QueryProfileVariants profileVariants = profile.getVariants();
Set<DimensionBindingForPath> variants = new HashSet<>();
if (profileVariants != null) {
for (QueryProfileVariant variant : profile.getVariants().getVariants()) {
DimensionBinding combinedVariant =
DimensionBinding.createFrom(profile.getDimensions(), variant.getDimensionValues()).combineWith(currentVariant);
if (combinedVariant.isInvalid()) continue;
variants.addAll(collectVariantsFromValues(path, variant.values(), combinedVariant));
for (QueryProfile variantInheritedProfile : variant.inherited())
variants.addAll(collectVariants(path, variantInheritedProfile, combinedVariant));
}
}
return variants;
}
private static Set<DimensionBindingForPath> collectVariantsFromValues(CompoundName path,
Map<String, Object> values,
DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
if ( ! values.isEmpty())
variants.add(new DimensionBindingForPath(currentVariant, path));
for (Map.Entry<String, Object> entry : values.entrySet()) {
if (entry.getValue() instanceof QueryProfile)
variants.addAll(collectVariants(path.append(entry.getKey()), (QueryProfile)entry.getValue(), currentVariant));
}
return variants;
}
private static class DimensionBindingForPath {
private final DimensionBinding binding;
private final CompoundName path;
public DimensionBindingForPath(DimensionBinding binding, CompoundName path) {
this.binding = binding;
this.path = path;
}
public DimensionBinding binding() { return binding; }
public CompoundName path() { return path; }
@Override
public boolean equals(Object o) {
if ( o == this ) return true;
if ( ! (o instanceof DimensionBindingForPath)) return false;
DimensionBindingForPath other = (DimensionBindingForPath)o;
return other.binding.equals(this.binding) && other.path.equals(this.path);
}
@Override
public int hashCode() {
return binding.hashCode() + 17*path.hashCode();
}
@Override
public String toString() {
return binding + " for path " + path;
}
}
} |
I do not think you want these debug statements lying around. | public static CompiledQueryProfile compile(QueryProfile in, CompiledQueryProfileRegistry registry) {
try {
DimensionalMap.Builder<CompoundName, Object> values = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, QueryProfileType> types = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, Object> references = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, Object> unoverridables = new DimensionalMap.Builder<>();
System.out.println("Compiling " + in.toString());
Set<DimensionBindingForPath> variants = collectVariants(CompoundName.empty, in, DimensionBinding.nullBinding);
variants.add(new DimensionBindingForPath(DimensionBinding.nullBinding, CompoundName.empty));
log.fine(() -> "Compiling " + in.toString() + " having " + variants.size() + " variants");
for (DimensionBindingForPath variant : variants) {
log.finer(() -> " Compiling variant " + variant);
System.out.println(" Compiling variant " + variant);
for (Map.Entry<String, Object> entry : in.listValues(variant.path(), variant.binding().getContext(), null).entrySet()) {
values.put(variant.path().append(entry.getKey()), variant.binding(), entry.getValue());
}
for (Map.Entry<CompoundName, QueryProfileType> entry : in.listTypes(variant.path(), variant.binding().getContext()).entrySet())
types.put(variant.path().append(entry.getKey()), variant.binding(), entry.getValue());
for (CompoundName reference : in.listReferences(variant.path(), variant.binding().getContext()))
references.put(variant.path().append(reference), variant.binding(), Boolean.TRUE);
for (CompoundName name : in.listUnoverridable(variant.path(), variant.binding().getContext()))
unoverridables.put(variant.path().append(name), variant.binding(), Boolean.TRUE);
}
return new CompiledQueryProfile(in.getId(), in.getType(),
values.build(), types.build(), references.build(), unoverridables.build(),
registry);
}
catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid " + in, e);
}
} | System.out.println("Compiling " + in.toString()); | public static CompiledQueryProfile compile(QueryProfile in, CompiledQueryProfileRegistry registry) {
try {
DimensionalMap.Builder<CompoundName, Object> values = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, QueryProfileType> types = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, Object> references = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, Object> unoverridables = new DimensionalMap.Builder<>();
System.out.println("Compiling " + in.toString());
Set<DimensionBindingForPath> variants = collectVariants(CompoundName.empty, in, DimensionBinding.nullBinding);
variants.add(new DimensionBindingForPath(DimensionBinding.nullBinding, CompoundName.empty));
log.fine(() -> "Compiling " + in.toString() + " having " + variants.size() + " variants");
for (DimensionBindingForPath variant : variants) {
log.finer(() -> " Compiling variant " + variant);
System.out.println(" Compiling variant " + variant);
for (Map.Entry<String, Object> entry : in.listValues(variant.path(), variant.binding().getContext(), null).entrySet()) {
values.put(variant.path().append(entry.getKey()), variant.binding(), entry.getValue());
}
for (Map.Entry<CompoundName, QueryProfileType> entry : in.listTypes(variant.path(), variant.binding().getContext()).entrySet())
types.put(variant.path().append(entry.getKey()), variant.binding(), entry.getValue());
for (CompoundName reference : in.listReferences(variant.path(), variant.binding().getContext()))
references.put(variant.path().append(reference), variant.binding(), Boolean.TRUE);
for (CompoundName name : in.listUnoverridable(variant.path(), variant.binding().getContext()))
unoverridables.put(variant.path().append(name), variant.binding(), Boolean.TRUE);
}
return new CompiledQueryProfile(in.getId(), in.getType(),
values.build(), types.build(), references.build(), unoverridables.build(),
registry);
}
catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid " + in, e);
}
} | class QueryProfileCompiler {
private static final Logger log = Logger.getLogger(QueryProfileCompiler.class.getName());
public static CompiledQueryProfileRegistry compile(QueryProfileRegistry input) {
CompiledQueryProfileRegistry output = new CompiledQueryProfileRegistry(input.getTypeRegistry());
for (QueryProfile inputProfile : input.allComponents()) {
output.register(compile(inputProfile, output));
}
return output;
}
/**
* Returns all the unique combinations of dimension values which have values reachable from this profile.
*
* @param profile the profile we are collecting the variants of
* @param currentVariant the variant we must have to arrive at this point in the query profile graph
*/
private static Set<DimensionBindingForPath> collectVariants(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
variants.addAll(collectVariantsFromValues(path, profile.getContent(), currentVariant));
variants.addAll(collectVariantsInThis(path, profile, currentVariant));
if (profile instanceof BackedOverridableQueryProfile)
variants.addAll(collectVariantsInThis(path, ((BackedOverridableQueryProfile) profile).getBacking(), currentVariant));
Set<DimensionBindingForPath> parentVariants;
for (QueryProfile inheritedProfile : profile.inherited()) {
parentVariants = collectVariants(path, inheritedProfile, currentVariant);
variants.addAll(parentVariants);
variants.addAll(combined(variants, parentVariants));
}
variants.addAll(wildcardExpanded(variants));
return variants;
}
/**
* For variants which are underspecified we must explicitly resolve each possible combination
* of actual left-side values.
*
* I.e if we have the variants [-,b=b1], [a=a1,-], [a=a2,-],
* this returns the variants [a=a1,b=b1], [a=a2,b=b1]
*
* This is necessary because left-specified values takes precedence, such that resolving [a=a1,b=b1] would
* lead us to the compiled profile [a=a1,-], which may contain default values for properties where
* we should have preferred variant values in [-,b=b1].
*/
private static Set<DimensionBindingForPath> wildcardExpanded(Set<DimensionBindingForPath> variants) {
Set<DimensionBindingForPath> expanded = new HashSet<>();
for (var variant : variants) {
if (hasWildcardBeforeEnd(variant.binding()))
expanded.addAll(wildcardExpanded(variant, variants));
}
return expanded;
}
private static boolean hasWildcardBeforeEnd(DimensionBinding variant) {
for (int i = 0; i < variant.getValues().size() - 1; i++) {
if (variant.getValues().get(i) == null)
return true;
}
return false;
}
private static Set<DimensionBindingForPath> wildcardExpanded(DimensionBindingForPath variantToExpand,
Set<DimensionBindingForPath> variants) {
Set<DimensionBindingForPath> expanded = new HashSet<>();
for (var variant : variants) {
if (variant.binding().isNull()) continue;
DimensionBinding combined = variantToExpand.binding().combineWith(variant.binding());
if ( ! combined.isInvalid() ) {
expanded.add(new DimensionBindingForPath(combined, variantToExpand.path()));
}
}
return expanded;
}
/** Generates a set of all the (legal) combinations of the variants in the given sets */
private static Set<DimensionBindingForPath> combined(Set<DimensionBindingForPath> v1s,
Set<DimensionBindingForPath> v2s) {
Set<DimensionBindingForPath> combinedVariants = new HashSet<>();
for (DimensionBindingForPath v1 : v1s) {
if (v1.binding().isNull()) continue;
for (DimensionBindingForPath v2 : v2s) {
if (v1.binding().isNull()) continue;
DimensionBinding combined = v1.binding().combineWith(v2.binding());
if ( combined.isInvalid() ) continue;
combinedVariants.add(new DimensionBindingForPath(combined, v1.path()));
}
}
return combinedVariants;
}
private static Set<DimensionBindingForPath> collectVariantsInThis(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
QueryProfileVariants profileVariants = profile.getVariants();
Set<DimensionBindingForPath> variants = new HashSet<>();
if (profileVariants != null) {
for (QueryProfileVariant variant : profile.getVariants().getVariants()) {
DimensionBinding combinedVariant =
DimensionBinding.createFrom(profile.getDimensions(), variant.getDimensionValues()).combineWith(currentVariant);
if (combinedVariant.isInvalid()) continue;
variants.addAll(collectVariantsFromValues(path, variant.values(), combinedVariant));
for (QueryProfile variantInheritedProfile : variant.inherited())
variants.addAll(collectVariants(path, variantInheritedProfile, combinedVariant));
}
}
return variants;
}
private static Set<DimensionBindingForPath> collectVariantsFromValues(CompoundName path,
Map<String, Object> values,
DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
if ( ! values.isEmpty())
variants.add(new DimensionBindingForPath(currentVariant, path));
for (Map.Entry<String, Object> entry : values.entrySet()) {
if (entry.getValue() instanceof QueryProfile)
variants.addAll(collectVariants(path.append(entry.getKey()), (QueryProfile)entry.getValue(), currentVariant));
}
return variants;
}
private static class DimensionBindingForPath {
private final DimensionBinding binding;
private final CompoundName path;
public DimensionBindingForPath(DimensionBinding binding, CompoundName path) {
this.binding = binding;
this.path = path;
}
public DimensionBinding binding() { return binding; }
public CompoundName path() { return path; }
@Override
public boolean equals(Object o) {
if ( o == this ) return true;
if ( ! (o instanceof DimensionBindingForPath)) return false;
DimensionBindingForPath other = (DimensionBindingForPath)o;
return other.binding.equals(this.binding) && other.path.equals(this.path);
}
@Override
public int hashCode() {
return binding.hashCode() + 17*path.hashCode();
}
@Override
public String toString() {
return binding + " for path " + path;
}
}
} | class QueryProfileCompiler {
private static final Logger log = Logger.getLogger(QueryProfileCompiler.class.getName());
public static CompiledQueryProfileRegistry compile(QueryProfileRegistry input) {
CompiledQueryProfileRegistry output = new CompiledQueryProfileRegistry(input.getTypeRegistry());
for (QueryProfile inputProfile : input.allComponents()) {
output.register(compile(inputProfile, output));
}
return output;
}
/**
* Returns all the unique combinations of dimension values which have values reachable from this profile.
*
* @param profile the profile we are collecting the variants of
* @param currentVariant the variant we must have to arrive at this point in the query profile graph
*/
private static Set<DimensionBindingForPath> collectVariants(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
variants.addAll(collectVariantsFromValues(path, profile.getContent(), currentVariant));
variants.addAll(collectVariantsInThis(path, profile, currentVariant));
if (profile instanceof BackedOverridableQueryProfile)
variants.addAll(collectVariantsInThis(path, ((BackedOverridableQueryProfile) profile).getBacking(), currentVariant));
Set<DimensionBindingForPath> parentVariants;
for (QueryProfile inheritedProfile : profile.inherited()) {
parentVariants = collectVariants(path, inheritedProfile, currentVariant);
variants.addAll(parentVariants);
variants.addAll(combined(variants, parentVariants));
}
variants.addAll(wildcardExpanded(variants));
return variants;
}
/**
* For variants which are underspecified we must explicitly resolve each possible combination
* of actual left-side values.
*
* I.e if we have the variants [-,b=b1], [a=a1,-], [a=a2,-],
* this returns the variants [a=a1,b=b1], [a=a2,b=b1]
*
* This is necessary because left-specified values takes precedence, such that resolving [a=a1,b=b1] would
* lead us to the compiled profile [a=a1,-], which may contain default values for properties where
* we should have preferred variant values in [-,b=b1].
*/
private static Set<DimensionBindingForPath> wildcardExpanded(Set<DimensionBindingForPath> variants) {
Set<DimensionBindingForPath> expanded = new HashSet<>();
for (var variant : variants) {
if (hasWildcardBeforeEnd(variant.binding()))
expanded.addAll(wildcardExpanded(variant, variants));
}
return expanded;
}
private static boolean hasWildcardBeforeEnd(DimensionBinding variant) {
for (int i = 0; i < variant.getValues().size() - 1; i++) {
if (variant.getValues().get(i) == null)
return true;
}
return false;
}
private static Set<DimensionBindingForPath> wildcardExpanded(DimensionBindingForPath variantToExpand,
Set<DimensionBindingForPath> variants) {
Set<DimensionBindingForPath> expanded = new HashSet<>();
for (var variant : variants) {
if (variant.binding().isNull()) continue;
DimensionBinding combined = variantToExpand.binding().combineWith(variant.binding());
if ( ! combined.isInvalid() ) {
expanded.add(new DimensionBindingForPath(combined, variantToExpand.path()));
}
}
return expanded;
}
/** Generates a set of all the (legal) combinations of the variants in the given sets */
private static Set<DimensionBindingForPath> combined(Set<DimensionBindingForPath> v1s,
Set<DimensionBindingForPath> v2s) {
Set<DimensionBindingForPath> combinedVariants = new HashSet<>();
for (DimensionBindingForPath v1 : v1s) {
if (v1.binding().isNull()) continue;
for (DimensionBindingForPath v2 : v2s) {
if (v1.binding().isNull()) continue;
DimensionBinding combined = v1.binding().combineWith(v2.binding());
if ( combined.isInvalid() ) continue;
combinedVariants.add(new DimensionBindingForPath(combined, v1.path()));
}
}
return combinedVariants;
}
private static Set<DimensionBindingForPath> collectVariantsInThis(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
QueryProfileVariants profileVariants = profile.getVariants();
Set<DimensionBindingForPath> variants = new HashSet<>();
if (profileVariants != null) {
for (QueryProfileVariant variant : profile.getVariants().getVariants()) {
DimensionBinding combinedVariant =
DimensionBinding.createFrom(profile.getDimensions(), variant.getDimensionValues()).combineWith(currentVariant);
if (combinedVariant.isInvalid()) continue;
variants.addAll(collectVariantsFromValues(path, variant.values(), combinedVariant));
for (QueryProfile variantInheritedProfile : variant.inherited())
variants.addAll(collectVariants(path, variantInheritedProfile, combinedVariant));
}
}
return variants;
}
private static Set<DimensionBindingForPath> collectVariantsFromValues(CompoundName path,
Map<String, Object> values,
DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
if ( ! values.isEmpty())
variants.add(new DimensionBindingForPath(currentVariant, path));
for (Map.Entry<String, Object> entry : values.entrySet()) {
if (entry.getValue() instanceof QueryProfile)
variants.addAll(collectVariants(path.append(entry.getKey()), (QueryProfile)entry.getValue(), currentVariant));
}
return variants;
}
private static class DimensionBindingForPath {
private final DimensionBinding binding;
private final CompoundName path;
public DimensionBindingForPath(DimensionBinding binding, CompoundName path) {
this.binding = binding;
this.path = path;
}
public DimensionBinding binding() { return binding; }
public CompoundName path() { return path; }
@Override
public boolean equals(Object o) {
if ( o == this ) return true;
if ( ! (o instanceof DimensionBindingForPath)) return false;
DimensionBindingForPath other = (DimensionBindingForPath)o;
return other.binding.equals(this.binding) && other.path.equals(this.path);
}
@Override
public int hashCode() {
return binding.hashCode() + 17*path.hashCode();
}
@Override
public String toString() {
return binding + " for path " + path;
}
}
} |
Ops, thanks | public static CompiledQueryProfile compile(QueryProfile in, CompiledQueryProfileRegistry registry) {
try {
DimensionalMap.Builder<CompoundName, Object> values = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, QueryProfileType> types = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, Object> references = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, Object> unoverridables = new DimensionalMap.Builder<>();
System.out.println("Compiling " + in.toString());
Set<DimensionBindingForPath> variants = collectVariants(CompoundName.empty, in, DimensionBinding.nullBinding);
variants.add(new DimensionBindingForPath(DimensionBinding.nullBinding, CompoundName.empty));
log.fine(() -> "Compiling " + in.toString() + " having " + variants.size() + " variants");
for (DimensionBindingForPath variant : variants) {
log.finer(() -> " Compiling variant " + variant);
System.out.println(" Compiling variant " + variant);
for (Map.Entry<String, Object> entry : in.listValues(variant.path(), variant.binding().getContext(), null).entrySet()) {
values.put(variant.path().append(entry.getKey()), variant.binding(), entry.getValue());
}
for (Map.Entry<CompoundName, QueryProfileType> entry : in.listTypes(variant.path(), variant.binding().getContext()).entrySet())
types.put(variant.path().append(entry.getKey()), variant.binding(), entry.getValue());
for (CompoundName reference : in.listReferences(variant.path(), variant.binding().getContext()))
references.put(variant.path().append(reference), variant.binding(), Boolean.TRUE);
for (CompoundName name : in.listUnoverridable(variant.path(), variant.binding().getContext()))
unoverridables.put(variant.path().append(name), variant.binding(), Boolean.TRUE);
}
return new CompiledQueryProfile(in.getId(), in.getType(),
values.build(), types.build(), references.build(), unoverridables.build(),
registry);
}
catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid " + in, e);
}
} | System.out.println("Compiling " + in.toString()); | public static CompiledQueryProfile compile(QueryProfile in, CompiledQueryProfileRegistry registry) {
try {
DimensionalMap.Builder<CompoundName, Object> values = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, QueryProfileType> types = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, Object> references = new DimensionalMap.Builder<>();
DimensionalMap.Builder<CompoundName, Object> unoverridables = new DimensionalMap.Builder<>();
System.out.println("Compiling " + in.toString());
Set<DimensionBindingForPath> variants = collectVariants(CompoundName.empty, in, DimensionBinding.nullBinding);
variants.add(new DimensionBindingForPath(DimensionBinding.nullBinding, CompoundName.empty));
log.fine(() -> "Compiling " + in.toString() + " having " + variants.size() + " variants");
for (DimensionBindingForPath variant : variants) {
log.finer(() -> " Compiling variant " + variant);
System.out.println(" Compiling variant " + variant);
for (Map.Entry<String, Object> entry : in.listValues(variant.path(), variant.binding().getContext(), null).entrySet()) {
values.put(variant.path().append(entry.getKey()), variant.binding(), entry.getValue());
}
for (Map.Entry<CompoundName, QueryProfileType> entry : in.listTypes(variant.path(), variant.binding().getContext()).entrySet())
types.put(variant.path().append(entry.getKey()), variant.binding(), entry.getValue());
for (CompoundName reference : in.listReferences(variant.path(), variant.binding().getContext()))
references.put(variant.path().append(reference), variant.binding(), Boolean.TRUE);
for (CompoundName name : in.listUnoverridable(variant.path(), variant.binding().getContext()))
unoverridables.put(variant.path().append(name), variant.binding(), Boolean.TRUE);
}
return new CompiledQueryProfile(in.getId(), in.getType(),
values.build(), types.build(), references.build(), unoverridables.build(),
registry);
}
catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid " + in, e);
}
} | class QueryProfileCompiler {
private static final Logger log = Logger.getLogger(QueryProfileCompiler.class.getName());
public static CompiledQueryProfileRegistry compile(QueryProfileRegistry input) {
CompiledQueryProfileRegistry output = new CompiledQueryProfileRegistry(input.getTypeRegistry());
for (QueryProfile inputProfile : input.allComponents()) {
output.register(compile(inputProfile, output));
}
return output;
}
/**
* Returns all the unique combinations of dimension values which have values reachable from this profile.
*
* @param profile the profile we are collecting the variants of
* @param currentVariant the variant we must have to arrive at this point in the query profile graph
*/
private static Set<DimensionBindingForPath> collectVariants(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
variants.addAll(collectVariantsFromValues(path, profile.getContent(), currentVariant));
variants.addAll(collectVariantsInThis(path, profile, currentVariant));
if (profile instanceof BackedOverridableQueryProfile)
variants.addAll(collectVariantsInThis(path, ((BackedOverridableQueryProfile) profile).getBacking(), currentVariant));
Set<DimensionBindingForPath> parentVariants;
for (QueryProfile inheritedProfile : profile.inherited()) {
parentVariants = collectVariants(path, inheritedProfile, currentVariant);
variants.addAll(parentVariants);
variants.addAll(combined(variants, parentVariants));
}
variants.addAll(wildcardExpanded(variants));
return variants;
}
/**
* For variants which are underspecified we must explicitly resolve each possible combination
* of actual left-side values.
*
* I.e if we have the variants [-,b=b1], [a=a1,-], [a=a2,-],
* this returns the variants [a=a1,b=b1], [a=a2,b=b1]
*
* This is necessary because left-specified values takes precedence, such that resolving [a=a1,b=b1] would
* lead us to the compiled profile [a=a1,-], which may contain default values for properties where
* we should have preferred variant values in [-,b=b1].
*/
private static Set<DimensionBindingForPath> wildcardExpanded(Set<DimensionBindingForPath> variants) {
Set<DimensionBindingForPath> expanded = new HashSet<>();
for (var variant : variants) {
if (hasWildcardBeforeEnd(variant.binding()))
expanded.addAll(wildcardExpanded(variant, variants));
}
return expanded;
}
private static boolean hasWildcardBeforeEnd(DimensionBinding variant) {
for (int i = 0; i < variant.getValues().size() - 1; i++) {
if (variant.getValues().get(i) == null)
return true;
}
return false;
}
private static Set<DimensionBindingForPath> wildcardExpanded(DimensionBindingForPath variantToExpand,
Set<DimensionBindingForPath> variants) {
Set<DimensionBindingForPath> expanded = new HashSet<>();
for (var variant : variants) {
if (variant.binding().isNull()) continue;
DimensionBinding combined = variantToExpand.binding().combineWith(variant.binding());
if ( ! combined.isInvalid() ) {
expanded.add(new DimensionBindingForPath(combined, variantToExpand.path()));
}
}
return expanded;
}
/** Generates a set of all the (legal) combinations of the variants in the given sets */
private static Set<DimensionBindingForPath> combined(Set<DimensionBindingForPath> v1s,
Set<DimensionBindingForPath> v2s) {
Set<DimensionBindingForPath> combinedVariants = new HashSet<>();
for (DimensionBindingForPath v1 : v1s) {
if (v1.binding().isNull()) continue;
for (DimensionBindingForPath v2 : v2s) {
if (v1.binding().isNull()) continue;
DimensionBinding combined = v1.binding().combineWith(v2.binding());
if ( combined.isInvalid() ) continue;
combinedVariants.add(new DimensionBindingForPath(combined, v1.path()));
}
}
return combinedVariants;
}
private static Set<DimensionBindingForPath> collectVariantsInThis(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
QueryProfileVariants profileVariants = profile.getVariants();
Set<DimensionBindingForPath> variants = new HashSet<>();
if (profileVariants != null) {
for (QueryProfileVariant variant : profile.getVariants().getVariants()) {
DimensionBinding combinedVariant =
DimensionBinding.createFrom(profile.getDimensions(), variant.getDimensionValues()).combineWith(currentVariant);
if (combinedVariant.isInvalid()) continue;
variants.addAll(collectVariantsFromValues(path, variant.values(), combinedVariant));
for (QueryProfile variantInheritedProfile : variant.inherited())
variants.addAll(collectVariants(path, variantInheritedProfile, combinedVariant));
}
}
return variants;
}
private static Set<DimensionBindingForPath> collectVariantsFromValues(CompoundName path,
Map<String, Object> values,
DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
if ( ! values.isEmpty())
variants.add(new DimensionBindingForPath(currentVariant, path));
for (Map.Entry<String, Object> entry : values.entrySet()) {
if (entry.getValue() instanceof QueryProfile)
variants.addAll(collectVariants(path.append(entry.getKey()), (QueryProfile)entry.getValue(), currentVariant));
}
return variants;
}
private static class DimensionBindingForPath {
private final DimensionBinding binding;
private final CompoundName path;
public DimensionBindingForPath(DimensionBinding binding, CompoundName path) {
this.binding = binding;
this.path = path;
}
public DimensionBinding binding() { return binding; }
public CompoundName path() { return path; }
@Override
public boolean equals(Object o) {
if ( o == this ) return true;
if ( ! (o instanceof DimensionBindingForPath)) return false;
DimensionBindingForPath other = (DimensionBindingForPath)o;
return other.binding.equals(this.binding) && other.path.equals(this.path);
}
@Override
public int hashCode() {
return binding.hashCode() + 17*path.hashCode();
}
@Override
public String toString() {
return binding + " for path " + path;
}
}
} | class QueryProfileCompiler {
private static final Logger log = Logger.getLogger(QueryProfileCompiler.class.getName());
public static CompiledQueryProfileRegistry compile(QueryProfileRegistry input) {
CompiledQueryProfileRegistry output = new CompiledQueryProfileRegistry(input.getTypeRegistry());
for (QueryProfile inputProfile : input.allComponents()) {
output.register(compile(inputProfile, output));
}
return output;
}
/**
* Returns all the unique combinations of dimension values which have values reachable from this profile.
*
* @param profile the profile we are collecting the variants of
* @param currentVariant the variant we must have to arrive at this point in the query profile graph
*/
private static Set<DimensionBindingForPath> collectVariants(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
variants.addAll(collectVariantsFromValues(path, profile.getContent(), currentVariant));
variants.addAll(collectVariantsInThis(path, profile, currentVariant));
if (profile instanceof BackedOverridableQueryProfile)
variants.addAll(collectVariantsInThis(path, ((BackedOverridableQueryProfile) profile).getBacking(), currentVariant));
Set<DimensionBindingForPath> parentVariants;
for (QueryProfile inheritedProfile : profile.inherited()) {
parentVariants = collectVariants(path, inheritedProfile, currentVariant);
variants.addAll(parentVariants);
variants.addAll(combined(variants, parentVariants));
}
variants.addAll(wildcardExpanded(variants));
return variants;
}
/**
* For variants which are underspecified we must explicitly resolve each possible combination
* of actual left-side values.
*
* I.e if we have the variants [-,b=b1], [a=a1,-], [a=a2,-],
* this returns the variants [a=a1,b=b1], [a=a2,b=b1]
*
* This is necessary because left-specified values takes precedence, such that resolving [a=a1,b=b1] would
* lead us to the compiled profile [a=a1,-], which may contain default values for properties where
* we should have preferred variant values in [-,b=b1].
*/
private static Set<DimensionBindingForPath> wildcardExpanded(Set<DimensionBindingForPath> variants) {
Set<DimensionBindingForPath> expanded = new HashSet<>();
for (var variant : variants) {
if (hasWildcardBeforeEnd(variant.binding()))
expanded.addAll(wildcardExpanded(variant, variants));
}
return expanded;
}
private static boolean hasWildcardBeforeEnd(DimensionBinding variant) {
for (int i = 0; i < variant.getValues().size() - 1; i++) {
if (variant.getValues().get(i) == null)
return true;
}
return false;
}
private static Set<DimensionBindingForPath> wildcardExpanded(DimensionBindingForPath variantToExpand,
Set<DimensionBindingForPath> variants) {
Set<DimensionBindingForPath> expanded = new HashSet<>();
for (var variant : variants) {
if (variant.binding().isNull()) continue;
DimensionBinding combined = variantToExpand.binding().combineWith(variant.binding());
if ( ! combined.isInvalid() ) {
expanded.add(new DimensionBindingForPath(combined, variantToExpand.path()));
}
}
return expanded;
}
/** Generates a set of all the (legal) combinations of the variants in the given sets */
private static Set<DimensionBindingForPath> combined(Set<DimensionBindingForPath> v1s,
Set<DimensionBindingForPath> v2s) {
Set<DimensionBindingForPath> combinedVariants = new HashSet<>();
for (DimensionBindingForPath v1 : v1s) {
if (v1.binding().isNull()) continue;
for (DimensionBindingForPath v2 : v2s) {
if (v1.binding().isNull()) continue;
DimensionBinding combined = v1.binding().combineWith(v2.binding());
if ( combined.isInvalid() ) continue;
combinedVariants.add(new DimensionBindingForPath(combined, v1.path()));
}
}
return combinedVariants;
}
private static Set<DimensionBindingForPath> collectVariantsInThis(CompoundName path, QueryProfile profile, DimensionBinding currentVariant) {
QueryProfileVariants profileVariants = profile.getVariants();
Set<DimensionBindingForPath> variants = new HashSet<>();
if (profileVariants != null) {
for (QueryProfileVariant variant : profile.getVariants().getVariants()) {
DimensionBinding combinedVariant =
DimensionBinding.createFrom(profile.getDimensions(), variant.getDimensionValues()).combineWith(currentVariant);
if (combinedVariant.isInvalid()) continue;
variants.addAll(collectVariantsFromValues(path, variant.values(), combinedVariant));
for (QueryProfile variantInheritedProfile : variant.inherited())
variants.addAll(collectVariants(path, variantInheritedProfile, combinedVariant));
}
}
return variants;
}
private static Set<DimensionBindingForPath> collectVariantsFromValues(CompoundName path,
Map<String, Object> values,
DimensionBinding currentVariant) {
Set<DimensionBindingForPath> variants = new HashSet<>();
if ( ! values.isEmpty())
variants.add(new DimensionBindingForPath(currentVariant, path));
for (Map.Entry<String, Object> entry : values.entrySet()) {
if (entry.getValue() instanceof QueryProfile)
variants.addAll(collectVariants(path.append(entry.getKey()), (QueryProfile)entry.getValue(), currentVariant));
}
return variants;
}
private static class DimensionBindingForPath {
private final DimensionBinding binding;
private final CompoundName path;
public DimensionBindingForPath(DimensionBinding binding, CompoundName path) {
this.binding = binding;
this.path = path;
}
public DimensionBinding binding() { return binding; }
public CompoundName path() { return path; }
@Override
public boolean equals(Object o) {
if ( o == this ) return true;
if ( ! (o instanceof DimensionBindingForPath)) return false;
DimensionBindingForPath other = (DimensionBindingForPath)o;
return other.binding.equals(this.binding) && other.path.equals(this.path);
}
@Override
public int hashCode() {
return binding.hashCode() + 17*path.hashCode();
}
@Override
public String toString() {
return binding + " for path " + path;
}
}
} |
Please use TestUtil.joinLines() to simplify specification of sd string. | public void attribute_combiner_transform_is_set_when_source_is_array_of_struct_with_only_struct_field_attributes() throws ParseException {
String sd = "search structmemorysummary {\n" +
" document structmemorysummary {\n" +
" struct elem {\n" +
" field name type string {}\n" +
" field weight type int {}\n" +
" }\n" +
" field elem_array type array<elem> {\n" +
" indexing: summary\n" +
" struct-field name {\n" +
" indexing: attribute\n" +
" }\n" +
" struct-field weight {\n" +
" indexing: attribute\n" +
" }\n" +
" }\n" +
" }\n" +
" document-summary unfiltered {\n" +
" summary elem_array_unfiltered type array<elem> {\n" +
" source: elem_array\n" +
" }\n" +
" }\n" +
"\n" +
"}";
Search search = SearchBuilder.createFromString(sd).getSearch();
assertEquals(SummaryTransform.ATTRIBUTECOMBINER, search.getSummaryField("elem_array_unfiltered").getTransform());
} | String sd = "search structmemorysummary {\n" + | public void attribute_combiner_transform_is_set_when_source_is_array_of_struct_with_only_struct_field_attributes() throws ParseException {
String sd = joinLines(
"search structmemorysummary {",
" document structmemorysummary {",
" struct elem {",
" field name type string {}",
" field weight type int {}\n",
" }",
" field elem_array type array<elem> {",
" indexing: summary",
" struct-field name {",
" indexing: attribute",
" }",
" struct-field weight {",
" indexing: attribute",
" }",
" }",
" }",
" document-summary unfiltered {",
" summary elem_array_unfiltered type array<elem> {",
" source: elem_array",
" }",
" }",
"",
"}"
);
Search search = SearchBuilder.createFromString(sd).getSearch();
assertEquals(SummaryTransform.ATTRIBUTECOMBINER, search.getSummaryField("elem_array_unfiltered").getTransform());
} | class SummaryConsistencyTestCase {
@Test
} | class SummaryConsistencyTestCase {
@Test
} |
Consider extracting a method for this validation. | 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 +
"]");
}
AthenzService athenzService = new AthenzService(request.getJDiscRequest().getUserPrincipal().getName());
List<String> commonNames = X509CertificateUtils.getCommonNames(instanceRefresh.csr().getSubject());
if(commonNames.size() != 1 && !Objects.equals(commonNames.get(0), athenzService.getFullName())) {
throw new IllegalArgumentException(String.format("Invalid request, trying to refresh service %s using service %s.", instanceRefresh.csr().getSubject().getName(), athenzService.getFullName()));
}
InstanceConfirmation instanceConfirmation = new InstanceConfirmation(provider, athenzService.getDomain().getName(), athenzService.getName(), null);
instanceConfirmation.set(InstanceValidator.SAN_IPS_ATTRNAME, getSubjectAlternativeNames(instanceRefresh.csr(), SubjectAlternativeName.Type.IP_ADDRESS));
instanceConfirmation.set(InstanceValidator.SAN_DNS_ATTRNAME, getSubjectAlternativeNames(instanceRefresh.csr(), SubjectAlternativeName.Type.DNS_NAME));
if(!instanceValidator.isValidRefresh(instanceConfirmation)) {
return ErrorResponse.forbidden("Unable to refresh cert: " + instanceRefresh.csr().getSubject().toString());
}
var certificate = certificates.create(instanceRefresh.csr(), caCertificate(), caPrivateKey());
var identity = new InstanceIdentity(provider, service, instanceIdFromCsr, Optional.of(certificate));
return new SlimeJsonResponse(InstanceSerializer.identityToSlime(identity));
} | throw new IllegalArgumentException(String.format("Invalid request, trying to refresh service %s using service %s.", instanceRefresh.csr().getSubject().getName(), athenzService.getFullName())); | private HttpResponse refreshInstance(HttpRequest request, String provider, String service, String instanceId) {
var instanceRefresh = deserializeRequest(request, InstanceSerializer::refreshFromSlime);
var instanceIdFromCsr = Certificates.instanceIdFrom(instanceRefresh.csr());
var athenzService = new AthenzService(request.getJDiscRequest().getUserPrincipal().getName());
if (!instanceIdFromCsr.equals(instanceId)) {
throw new IllegalArgumentException("Mismatch between instance ID in URL path and instance ID in CSR " +
"[instanceId=" + instanceId + ",instanceIdFromCsr=" + instanceIdFromCsr +
"]");
}
refreshesSameInstanceId(instanceIdFromCsr, request);
refreshesSameService(instanceRefresh, athenzService);
InstanceConfirmation instanceConfirmation = new InstanceConfirmation(provider, athenzService.getDomain().getName(), athenzService.getName(), null);
instanceConfirmation.set(InstanceValidator.SAN_IPS_ATTRNAME, Certificates.getSubjectAlternativeNames(instanceRefresh.csr(), SubjectAlternativeName.Type.IP_ADDRESS));
instanceConfirmation.set(InstanceValidator.SAN_DNS_ATTRNAME, Certificates.getSubjectAlternativeNames(instanceRefresh.csr(), SubjectAlternativeName.Type.DNS_NAME));
if(!instanceValidator.isValidRefresh(instanceConfirmation)) {
return ErrorResponse.forbidden("Unable to refresh cert: " + instanceRefresh.csr().getSubject().toString());
}
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;
private final InstanceValidator instanceValidator;
@Inject
public CertificateAuthorityApiHandler(Context ctx, SecretStore secretStore, AthenzProviderServiceConfig athenzProviderServiceConfig, InstanceValidator instanceValidator) {
this(ctx, secretStore, new Certificates(Clock.systemUTC()), athenzProviderServiceConfig, instanceValidator);
}
CertificateAuthorityApiHandler(Context ctx, SecretStore secretStore, Certificates certificates, AthenzProviderServiceConfig athenzProviderServiceConfig, InstanceValidator instanceValidator) {
super(ctx);
this.secretStore = secretStore;
this.certificates = certificates;
this.caPrivateKeySecretName = athenzProviderServiceConfig.secretName();
this.caCertificateSecretName = athenzProviderServiceConfig.domain() + ".ca.cert";
this.instanceValidator = instanceValidator;
}
@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);
InstanceConfirmation confirmation = new InstanceConfirmation(instanceRegistration.provider(), instanceRegistration.domain(), instanceRegistration.service(), EntityBindingsMapper.toSignedIdentityDocumentEntity(instanceRegistration.attestationData()));
confirmation.set(InstanceValidator.SAN_IPS_ATTRNAME, getSubjectAlternativeNames(instanceRegistration.csr(), SubjectAlternativeName.Type.IP_ADDRESS));
confirmation.set(InstanceValidator.SAN_DNS_ATTRNAME, getSubjectAlternativeNames(instanceRegistration.csr(), SubjectAlternativeName.Type.DNS_NAME));
if (!instanceValidator.isValidInstance(confirmation)) {
log.log(LogLevel.INFO, "Invalid instance registration for " + instanceRegistration.toString());
return ErrorResponse.forbidden("Unable to launch service: " +instanceRegistration.service());
}
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));
}
private String getSubjectAlternativeNames(Pkcs10Csr csr, SubjectAlternativeName.Type sanType) {
return csr.getSubjectAlternativeNames().stream()
.map(SubjectAlternativeName::decode)
.filter(san -> san.getType() == sanType)
.map(SubjectAlternativeName::getValue)
.collect(Collectors.joining(","));
}
/** 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;
private final InstanceValidator instanceValidator;
@Inject
public CertificateAuthorityApiHandler(Context ctx, SecretStore secretStore, AthenzProviderServiceConfig athenzProviderServiceConfig, InstanceValidator instanceValidator) {
this(ctx, secretStore, new Certificates(Clock.systemUTC()), athenzProviderServiceConfig, instanceValidator);
}
CertificateAuthorityApiHandler(Context ctx, SecretStore secretStore, Certificates certificates, AthenzProviderServiceConfig athenzProviderServiceConfig, InstanceValidator instanceValidator) {
super(ctx);
this.secretStore = secretStore;
this.certificates = certificates;
this.caPrivateKeySecretName = athenzProviderServiceConfig.secretName();
this.caCertificateSecretName = athenzProviderServiceConfig.domain() + ".ca.cert";
this.instanceValidator = instanceValidator;
}
@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);
InstanceConfirmation confirmation = new InstanceConfirmation(instanceRegistration.provider(), instanceRegistration.domain(), instanceRegistration.service(), EntityBindingsMapper.toSignedIdentityDocumentEntity(instanceRegistration.attestationData()));
confirmation.set(InstanceValidator.SAN_IPS_ATTRNAME, Certificates.getSubjectAlternativeNames(instanceRegistration.csr(), SubjectAlternativeName.Type.IP_ADDRESS));
confirmation.set(InstanceValidator.SAN_DNS_ATTRNAME, Certificates.getSubjectAlternativeNames(instanceRegistration.csr(), SubjectAlternativeName.Type.DNS_NAME));
if (!instanceValidator.isValidInstance(confirmation)) {
log.log(LogLevel.INFO, "Invalid instance registration for " + instanceRegistration.toString());
return ErrorResponse.forbidden("Unable to launch service: " +instanceRegistration.service());
}
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));
}
public void refreshesSameInstanceId(String csrInstanceId, HttpRequest request) {
String certificateInstanceId = getRequestCertificateChain(request).stream()
.map(Certificates::instanceIdFrom)
.filter(Optional::isPresent)
.map(Optional::get)
.findAny().orElseThrow(() -> new IllegalArgumentException("No client certificate with instance id in request."));
if(! Objects.equals(certificateInstanceId, csrInstanceId)) {
throw new IllegalArgumentException("Mismatch between instance ID in client certificate and instance ID in CSR " +
"[instanceId=" + certificateInstanceId + ",instanceIdFromCsr=" + csrInstanceId +
"]");
}
}
private void refreshesSameService(InstanceRefresh instanceRefresh, AthenzService athenzService) {
List<String> commonNames = X509CertificateUtils.getCommonNames(instanceRefresh.csr().getSubject());
if(commonNames.size() != 1 && !Objects.equals(commonNames.get(0), athenzService.getFullName())) {
throw new IllegalArgumentException(String.format("Invalid request, trying to refresh service %s using service %s.", instanceRefresh.csr().getSubject().getName(), athenzService.getFullName()));
}
}
/** Returns CA certificate from secret store */
private X509Certificate caCertificate() {
return X509CertificateUtils.fromPem(secretStore.getSecret(caCertificateSecretName));
}
private List<X509Certificate> getRequestCertificateChain(HttpRequest request) {
return Optional.ofNullable(request.getJDiscRequest().context().get(ServletRequest.JDISC_REQUEST_X509CERT))
.map(X509Certificate[].class::cast)
.map(Arrays::asList)
.orElse(Collections.emptyList());
}
/** 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);
}
}
} |
Remove. | public void filter(DiscFilterRequest request, ResponseHandler handler) {
String principal = request.getHeader("PRINCIPAL");
System.out.println("principal = " + principal);
request.setUserPrincipal(new AthenzPrincipal(new AthenzService(principal)));
} | System.out.println("principal = " + principal); | public void filter(DiscFilterRequest request, ResponseHandler handler) {
String principal = request.getHeader("PRINCIPAL");
request.setUserPrincipal(new AthenzPrincipal(new AthenzService(principal)));
Optional<String> certificate = Optional.ofNullable(request.getHeader("CERTIFICATE"));
certificate.ifPresent(cert -> {
var x509cert = X509CertificateUtils.fromPem(StringUtilities.unescape(cert));
request.setAttribute(ServletRequest.JDISC_REQUEST_X509CERT, new X509Certificate[]{x509cert});
});
} | class PrincipalFromHeaderFilter implements SecurityRequestFilter {
public PrincipalFromHeaderFilter() {}
@Override
} | class PrincipalFromHeaderFilter implements SecurityRequestFilter {
@Override
} |
💯 | private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
} | if ( e.getErrorCode() == ACTIVATION_CONFLICT | private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return Optional.of(running);
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return Optional.of(running);
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
JobReport report = JobReport.ofJob(run.id().application(),
run.id().type(),
run.id().number(),
! run.hasFailed() ? Optional.empty()
: Optional.of(run.status() == outOfCapacity ? DeploymentJobs.JobError.outOfCapacity
: DeploymentJobs.JobError.unknown));
controller.applications().deploymentTrigger().notifyOfCompletion(report);
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(spec.athenzDomain(), spec.athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("")
+ "/>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return Optional.of(running);
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return Optional.of(running);
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
JobReport report = JobReport.ofJob(run.id().application(),
run.id().type(),
run.id().number(),
! run.hasFailed() ? Optional.empty()
: Optional.of(run.status() == outOfCapacity ? DeploymentJobs.JobError.outOfCapacity
: DeploymentJobs.JobError.unknown));
controller.applications().deploymentTrigger().notifyOfCompletion(report);
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(spec.athenzDomain(), spec.athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("")
+ "/>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} |
Do you know why we do not use the configserver VIPs for non-aws zones? | private List<URI> getConfigserverEndpoints(ZoneId zoneId) {
if (zoneId.region().value().startsWith("aws-") || zoneId.region().value().contains("-aws-")) {
return List.of(zoneRegistry.getConfigServerVipUri(zoneId));
} else {
return new ArrayList<>(zoneRegistry.getConfigServerUris(zoneId));
}
} | private List<URI> getConfigserverEndpoints(ZoneId zoneId) {
if (zoneId.region().value().startsWith("aws-") || zoneId.region().value().contains("-aws-")) {
return List.of(zoneRegistry.getConfigServerVipUri(zoneId));
} else {
return new ArrayList<>(zoneRegistry.getConfigServerUris(zoneId));
}
} | class ConfigServerRestExecutorImpl implements ConfigServerRestExecutor {
private static final Logger log = Logger.getLogger(ConfigServerRestExecutorImpl.class.getName());
private static final Duration PROXY_REQUEST_TIMEOUT = Duration.ofSeconds(10);
private static final Set<String> HEADERS_TO_COPY = Set.of("X-HTTP-Method-Override", "Content-Type");
private final ZoneRegistry zoneRegistry;
private final ServiceIdentityProvider sslContextProvider;
@Inject
public ConfigServerRestExecutorImpl(ZoneRegistry zoneRegistry, ServiceIdentityProvider sslContextProvider) {
this.zoneRegistry = zoneRegistry;
this.sslContextProvider = sslContextProvider;
}
@Override
public ProxyResponse handle(ProxyRequest proxyRequest) throws ProxyException {
HostnameVerifier hostnameVerifier = createHostnameVerifier(proxyRequest.getZoneId());
List<URI> allServers = getConfigserverEndpoints(proxyRequest.getZoneId());
StringBuilder errorBuilder = new StringBuilder();
if (queueFirstServerIfDown(allServers, hostnameVerifier)) {
errorBuilder.append("Change ordering due to failed ping.");
}
for (URI uri : allServers) {
Optional<ProxyResponse> proxyResponse = proxyCall(uri, proxyRequest, hostnameVerifier, errorBuilder);
if (proxyResponse.isPresent()) {
return proxyResponse.get();
}
}
throw new ProxyException(ErrorResponse.internalServerError("Failed talking to config servers: "
+ errorBuilder.toString()));
}
private Optional<ProxyResponse> proxyCall(
URI uri, ProxyRequest proxyRequest, HostnameVerifier hostnameVerifier, StringBuilder errorBuilder)
throws ProxyException {
final HttpRequestBase requestBase = createHttpBaseRequest(
proxyRequest.getMethod(), proxyRequest.createConfigServerRequestUri(uri), proxyRequest.getData());
copyHeaders(proxyRequest.getHeaders(), requestBase);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setConnectionRequestTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setSocketTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis()).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(requestBase)
) {
String content = getContent(response);
int status = response.getStatusLine().getStatusCode();
if (status / 100 == 5) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(", got ").append(status).append(" ")
.append(content).append("\n");
log.log(LogLevel.DEBUG, () -> String.format("Got response from %s with status code %d and content:\n %s",
uri.getHost(), status, content));
return Optional.empty();
}
final Header contentHeader = response.getLastHeader("Content-Type");
final String contentType;
if (contentHeader != null && contentHeader.getValue() != null && ! contentHeader.getValue().isEmpty()) {
contentType = contentHeader.getValue().replace("; charset=UTF-8","");
} else {
contentType = "application/json";
}
return Optional.of(new ProxyResponse(proxyRequest, content, status, uri, contentType));
} catch (Exception e) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(" got exception ").append(e.getMessage());
log.log(LogLevel.DEBUG, e, () -> "Got exception while sending request to " + uri.getHost());
return Optional.empty();
}
}
private static String getContent(CloseableHttpResponse response) {
return Optional.ofNullable(response.getEntity())
.map(entity -> uncheck(() -> EntityUtils.toString(entity)))
.orElse("");
}
private static HttpRequestBase createHttpBaseRequest(Method method, URI uri, InputStream data) throws ProxyException {
switch (method) {
case GET:
return new HttpGet(uri);
case POST:
HttpPost post = new HttpPost(uri);
if (data != null) {
post.setEntity(new InputStreamEntity(data));
}
return post;
case PUT:
HttpPut put = new HttpPut(uri);
if (data != null) {
put.setEntity(new InputStreamEntity(data));
}
return put;
case DELETE:
return new HttpDelete(uri);
case PATCH:
HttpPatch patch = new HttpPatch(uri);
if (data != null) {
patch.setEntity(new InputStreamEntity(data));
}
return patch;
default:
throw new ProxyException(ErrorResponse.methodNotAllowed("Will not proxy such calls."));
}
}
private static void copyHeaders(Map<String, List<String>> headers, HttpRequestBase toRequest) {
for (Map.Entry<String, List<String>> headerEntry : headers.entrySet()) {
if (HEADERS_TO_COPY.contains(headerEntry.getKey())) {
for (String value : headerEntry.getValue()) {
toRequest.addHeader(headerEntry.getKey(), value);
}
}
}
}
/**
* During upgrade, one server can be down, this is normal. Therefor we do a quick ping on the first server,
* if it is not responding, we try the other servers first. False positive/negatives are not critical,
* but will increase latency to some extent.
*/
private boolean queueFirstServerIfDown(List<URI> allServers, HostnameVerifier hostnameVerifier) {
if (allServers.size() < 2) {
return false;
}
URI uri = allServers.get(0);
HttpGet httpget = new HttpGet(uri);
int timeout = 500;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(httpget)
) {
if (response.getStatusLine().getStatusCode() == 200) {
return false;
}
} catch (IOException e) {
}
Collections.rotate(allServers, -1);
return true;
}
private HostnameVerifier createHostnameVerifier(ZoneId zoneId) {
return new AthenzIdentityVerifier(Set.of(zoneRegistry.getConfigServerHttpsIdentity(zoneId)));
}
private static CloseableHttpClient createHttpClient(RequestConfig config,
ServiceIdentityProvider sslContextProvider,
HostnameVerifier hostnameVerifier) {
return HttpClientBuilder.create()
.setUserAgent("config-server-proxy-client")
.setSslcontext(sslContextProvider.getIdentitySslContext())
.setSSLHostnameVerifier(hostnameVerifier)
.setDefaultRequestConfig(config)
.build();
}
} | class ConfigServerRestExecutorImpl implements ConfigServerRestExecutor {
private static final Logger log = Logger.getLogger(ConfigServerRestExecutorImpl.class.getName());
private static final Duration PROXY_REQUEST_TIMEOUT = Duration.ofSeconds(10);
private static final Set<String> HEADERS_TO_COPY = Set.of("X-HTTP-Method-Override", "Content-Type");
private final ZoneRegistry zoneRegistry;
private final ServiceIdentityProvider sslContextProvider;
@Inject
public ConfigServerRestExecutorImpl(ZoneRegistry zoneRegistry, ServiceIdentityProvider sslContextProvider) {
this.zoneRegistry = zoneRegistry;
this.sslContextProvider = sslContextProvider;
}
@Override
public ProxyResponse handle(ProxyRequest proxyRequest) throws ProxyException {
HostnameVerifier hostnameVerifier = createHostnameVerifier(proxyRequest.getZoneId());
List<URI> allServers = getConfigserverEndpoints(proxyRequest.getZoneId());
StringBuilder errorBuilder = new StringBuilder();
if (queueFirstServerIfDown(allServers, hostnameVerifier)) {
errorBuilder.append("Change ordering due to failed ping.");
}
for (URI uri : allServers) {
Optional<ProxyResponse> proxyResponse = proxyCall(uri, proxyRequest, hostnameVerifier, errorBuilder);
if (proxyResponse.isPresent()) {
return proxyResponse.get();
}
}
throw new ProxyException(ErrorResponse.internalServerError("Failed talking to config servers: "
+ errorBuilder.toString()));
}
private Optional<ProxyResponse> proxyCall(
URI uri, ProxyRequest proxyRequest, HostnameVerifier hostnameVerifier, StringBuilder errorBuilder)
throws ProxyException {
final HttpRequestBase requestBase = createHttpBaseRequest(
proxyRequest.getMethod(), proxyRequest.createConfigServerRequestUri(uri), proxyRequest.getData());
copyHeaders(proxyRequest.getHeaders(), requestBase);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setConnectionRequestTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setSocketTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis()).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(requestBase)
) {
String content = getContent(response);
int status = response.getStatusLine().getStatusCode();
if (status / 100 == 5) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(", got ").append(status).append(" ")
.append(content).append("\n");
log.log(LogLevel.DEBUG, () -> String.format("Got response from %s with status code %d and content:\n %s",
uri.getHost(), status, content));
return Optional.empty();
}
final Header contentHeader = response.getLastHeader("Content-Type");
final String contentType;
if (contentHeader != null && contentHeader.getValue() != null && ! contentHeader.getValue().isEmpty()) {
contentType = contentHeader.getValue().replace("; charset=UTF-8","");
} else {
contentType = "application/json";
}
return Optional.of(new ProxyResponse(proxyRequest, content, status, uri, contentType));
} catch (Exception e) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(" got exception ").append(e.getMessage());
log.log(LogLevel.DEBUG, e, () -> "Got exception while sending request to " + uri.getHost());
return Optional.empty();
}
}
private static String getContent(CloseableHttpResponse response) {
return Optional.ofNullable(response.getEntity())
.map(entity -> uncheck(() -> EntityUtils.toString(entity)))
.orElse("");
}
private static HttpRequestBase createHttpBaseRequest(Method method, URI uri, InputStream data) throws ProxyException {
switch (method) {
case GET:
return new HttpGet(uri);
case POST:
HttpPost post = new HttpPost(uri);
if (data != null) {
post.setEntity(new InputStreamEntity(data));
}
return post;
case PUT:
HttpPut put = new HttpPut(uri);
if (data != null) {
put.setEntity(new InputStreamEntity(data));
}
return put;
case DELETE:
return new HttpDelete(uri);
case PATCH:
HttpPatch patch = new HttpPatch(uri);
if (data != null) {
patch.setEntity(new InputStreamEntity(data));
}
return patch;
default:
throw new ProxyException(ErrorResponse.methodNotAllowed("Will not proxy such calls."));
}
}
private static void copyHeaders(Map<String, List<String>> headers, HttpRequestBase toRequest) {
for (Map.Entry<String, List<String>> headerEntry : headers.entrySet()) {
if (HEADERS_TO_COPY.contains(headerEntry.getKey())) {
for (String value : headerEntry.getValue()) {
toRequest.addHeader(headerEntry.getKey(), value);
}
}
}
}
/**
* During upgrade, one server can be down, this is normal. Therefor we do a quick ping on the first server,
* if it is not responding, we try the other servers first. False positive/negatives are not critical,
* but will increase latency to some extent.
*/
private boolean queueFirstServerIfDown(List<URI> allServers, HostnameVerifier hostnameVerifier) {
if (allServers.size() < 2) {
return false;
}
URI uri = allServers.get(0);
HttpGet httpget = new HttpGet(uri);
int timeout = 500;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(httpget)
) {
if (response.getStatusLine().getStatusCode() == 200) {
return false;
}
} catch (IOException e) {
}
Collections.rotate(allServers, -1);
return true;
}
private HostnameVerifier createHostnameVerifier(ZoneId zoneId) {
return new AthenzIdentityVerifier(Set.of(zoneRegistry.getConfigServerHttpsIdentity(zoneId)));
}
private static CloseableHttpClient createHttpClient(RequestConfig config,
ServiceIdentityProvider sslContextProvider,
HostnameVerifier hostnameVerifier) {
return HttpClientBuilder.create()
.setUserAgent("config-server-proxy-client")
.setSslcontext(sslContextProvider.getIdentitySslContext())
.setSSLHostnameVerifier(hostnameVerifier)
.setDefaultRequestConfig(config)
.build();
}
} | |
Note: this hostname verifier will not accept the controller certificate. | private HostnameVerifier createHostnameVerifier(ZoneId zoneId) {
return new AthenzIdentityVerifier(Set.of(zoneRegistry.getConfigServerHttpsIdentity(zoneId)));
} | return new AthenzIdentityVerifier(Set.of(zoneRegistry.getConfigServerHttpsIdentity(zoneId))); | private HostnameVerifier createHostnameVerifier(ZoneId zoneId) {
return new AthenzIdentityVerifier(Set.of(zoneRegistry.getConfigServerHttpsIdentity(zoneId)));
} | class ConfigServerRestExecutorImpl implements ConfigServerRestExecutor {
private static final Logger log = Logger.getLogger(ConfigServerRestExecutorImpl.class.getName());
private static final Duration PROXY_REQUEST_TIMEOUT = Duration.ofSeconds(10);
private static final Set<String> HEADERS_TO_COPY = Set.of("X-HTTP-Method-Override", "Content-Type");
private final ZoneRegistry zoneRegistry;
private final ServiceIdentityProvider sslContextProvider;
@Inject
public ConfigServerRestExecutorImpl(ZoneRegistry zoneRegistry,
ServiceIdentityProvider sslContextProvider) {
this.zoneRegistry = zoneRegistry;
this.sslContextProvider = sslContextProvider;
}
@Override
public ProxyResponse handle(ProxyRequest proxyRequest) throws ProxyException {
ZoneId zoneId = ZoneId.from(proxyRequest.getEnvironment(), proxyRequest.getRegion());
HostnameVerifier hostnameVerifier = createHostnameVerifier(zoneId);
List<URI> allServers = getConfigserverEndpoints(zoneId);
StringBuilder errorBuilder = new StringBuilder();
if (queueFirstServerIfDown(allServers, hostnameVerifier)) {
errorBuilder.append("Change ordering due to failed ping.");
}
for (URI uri : allServers) {
Optional<ProxyResponse> proxyResponse = proxyCall(uri, proxyRequest, hostnameVerifier, errorBuilder);
if (proxyResponse.isPresent()) {
return proxyResponse.get();
}
}
throw new ProxyException(ErrorResponse.internalServerError("Failed talking to config servers: "
+ errorBuilder.toString()));
}
private List<URI> getConfigserverEndpoints(ZoneId zoneId) {
if (zoneId.region().value().startsWith("aws-") || zoneId.region().value().contains("-aws-")) {
return Collections.singletonList(zoneRegistry.getConfigServerVipUri(zoneId));
} else {
return new ArrayList<>(zoneRegistry.getConfigServerUris(zoneId));
}
}
private static String removeFirstSlashIfAny(String url) {
if (url.startsWith("/")) {
return url.substring(1);
}
return url;
}
private Optional<ProxyResponse> proxyCall(
URI uri, ProxyRequest proxyRequest, HostnameVerifier hostnameVerifier, StringBuilder errorBuilder)
throws ProxyException {
String fullUri = uri.toString() + removeFirstSlashIfAny(proxyRequest.getConfigServerRequest());
final HttpRequestBase requestBase = createHttpBaseRequest(
proxyRequest.getMethod(), fullUri, proxyRequest.getData());
copyHeaders(proxyRequest.getHeaders(), requestBase);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setConnectionRequestTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setSocketTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis()).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(requestBase)
) {
String content = getContent(response);
int status = response.getStatusLine().getStatusCode();
if (status / 100 == 5) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(", got ").append(status).append(" ")
.append(content).append("\n");
log.log(LogLevel.DEBUG, () -> String.format("Got response from %s with status code %d and content:\n %s",
uri.getHost(), status, content));
return Optional.empty();
}
final Header contentHeader = response.getLastHeader("Content-Type");
final String contentType;
if (contentHeader != null && contentHeader.getValue() != null && ! contentHeader.getValue().isEmpty()) {
contentType = contentHeader.getValue().replace("; charset=UTF-8","");
} else {
contentType = "application/json";
}
return Optional.of(new ProxyResponse(proxyRequest, content, status, uri, contentType));
} catch (Exception e) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(" got exception ").append(e.getMessage());
log.log(LogLevel.DEBUG, e, () -> "Got exception while sending request to " + uri.getHost());
return Optional.empty();
}
}
private static String getContent(CloseableHttpResponse response) {
return Optional.ofNullable(response.getEntity())
.map(entity ->
{
try {
return EntityUtils.toString(entity);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
).orElse("");
}
private static HttpRequestBase createHttpBaseRequest(String method, String uri, InputStream data) throws ProxyException {
Method enumMethod = Method.valueOf(method);
switch (enumMethod) {
case GET:
return new HttpGet(uri);
case POST:
HttpPost post = new HttpPost(uri);
if (data != null) {
post.setEntity(new InputStreamEntity(data));
}
return post;
case PUT:
HttpPut put = new HttpPut(uri);
if (data != null) {
put.setEntity(new InputStreamEntity(data));
}
return put;
case DELETE:
return new HttpDelete(uri);
case PATCH:
HttpPatch patch = new HttpPatch(uri);
if (data != null) {
patch.setEntity(new InputStreamEntity(data));
}
return patch;
default:
throw new ProxyException(ErrorResponse.methodNotAllowed("Will not proxy such calls."));
}
}
private static void copyHeaders(Map<String, List<String>> headers, HttpRequestBase toRequest) {
for (Map.Entry<String, List<String>> headerEntry : headers.entrySet()) {
if (HEADERS_TO_COPY.contains(headerEntry.getKey())) {
for (String value : headerEntry.getValue()) {
toRequest.addHeader(headerEntry.getKey(), value);
}
}
}
}
/**
* During upgrade, one server can be down, this is normal. Therefor we do a quick ping on the first server,
* if it is not responding, we try the other servers first. False positive/negatives are not critical,
* but will increase latency to some extent.
*/
private boolean queueFirstServerIfDown(List<URI> allServers, HostnameVerifier hostnameVerifier) {
if (allServers.size() < 2) {
return false;
}
URI uri = allServers.get(0);
HttpGet httpget = new HttpGet(uri);
int timeout = 500;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(httpget)
) {
if (response.getStatusLine().getStatusCode() == 200) {
return false;
}
} catch (IOException e) {
}
allServers.remove(0);
allServers.add(uri);
return true;
}
private static CloseableHttpClient createHttpClient(RequestConfig config,
ServiceIdentityProvider sslContextProvider,
HostnameVerifier hostnameVerifier) {
return HttpClientBuilder.create()
.setUserAgent("config-server-proxy-client")
.setSslcontext(sslContextProvider.getIdentitySslContext())
.setSSLHostnameVerifier(hostnameVerifier)
.setDefaultRequestConfig(config)
.build();
}
} | class ConfigServerRestExecutorImpl implements ConfigServerRestExecutor {
private static final Logger log = Logger.getLogger(ConfigServerRestExecutorImpl.class.getName());
private static final Duration PROXY_REQUEST_TIMEOUT = Duration.ofSeconds(10);
private static final Set<String> HEADERS_TO_COPY = Set.of("X-HTTP-Method-Override", "Content-Type");
private final ZoneRegistry zoneRegistry;
private final ServiceIdentityProvider sslContextProvider;
@Inject
public ConfigServerRestExecutorImpl(ZoneRegistry zoneRegistry, ServiceIdentityProvider sslContextProvider) {
this.zoneRegistry = zoneRegistry;
this.sslContextProvider = sslContextProvider;
}
@Override
public ProxyResponse handle(ProxyRequest proxyRequest) throws ProxyException {
HostnameVerifier hostnameVerifier = createHostnameVerifier(proxyRequest.getZoneId());
List<URI> allServers = getConfigserverEndpoints(proxyRequest.getZoneId());
StringBuilder errorBuilder = new StringBuilder();
if (queueFirstServerIfDown(allServers, hostnameVerifier)) {
errorBuilder.append("Change ordering due to failed ping.");
}
for (URI uri : allServers) {
Optional<ProxyResponse> proxyResponse = proxyCall(uri, proxyRequest, hostnameVerifier, errorBuilder);
if (proxyResponse.isPresent()) {
return proxyResponse.get();
}
}
throw new ProxyException(ErrorResponse.internalServerError("Failed talking to config servers: "
+ errorBuilder.toString()));
}
private List<URI> getConfigserverEndpoints(ZoneId zoneId) {
if (zoneId.region().value().startsWith("aws-") || zoneId.region().value().contains("-aws-")) {
return List.of(zoneRegistry.getConfigServerVipUri(zoneId));
} else {
return new ArrayList<>(zoneRegistry.getConfigServerUris(zoneId));
}
}
private Optional<ProxyResponse> proxyCall(
URI uri, ProxyRequest proxyRequest, HostnameVerifier hostnameVerifier, StringBuilder errorBuilder)
throws ProxyException {
final HttpRequestBase requestBase = createHttpBaseRequest(
proxyRequest.getMethod(), proxyRequest.createConfigServerRequestUri(uri), proxyRequest.getData());
copyHeaders(proxyRequest.getHeaders(), requestBase);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setConnectionRequestTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setSocketTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis()).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(requestBase)
) {
String content = getContent(response);
int status = response.getStatusLine().getStatusCode();
if (status / 100 == 5) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(", got ").append(status).append(" ")
.append(content).append("\n");
log.log(LogLevel.DEBUG, () -> String.format("Got response from %s with status code %d and content:\n %s",
uri.getHost(), status, content));
return Optional.empty();
}
final Header contentHeader = response.getLastHeader("Content-Type");
final String contentType;
if (contentHeader != null && contentHeader.getValue() != null && ! contentHeader.getValue().isEmpty()) {
contentType = contentHeader.getValue().replace("; charset=UTF-8","");
} else {
contentType = "application/json";
}
return Optional.of(new ProxyResponse(proxyRequest, content, status, uri, contentType));
} catch (Exception e) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(" got exception ").append(e.getMessage());
log.log(LogLevel.DEBUG, e, () -> "Got exception while sending request to " + uri.getHost());
return Optional.empty();
}
}
private static String getContent(CloseableHttpResponse response) {
return Optional.ofNullable(response.getEntity())
.map(entity -> uncheck(() -> EntityUtils.toString(entity)))
.orElse("");
}
private static HttpRequestBase createHttpBaseRequest(Method method, URI uri, InputStream data) throws ProxyException {
switch (method) {
case GET:
return new HttpGet(uri);
case POST:
HttpPost post = new HttpPost(uri);
if (data != null) {
post.setEntity(new InputStreamEntity(data));
}
return post;
case PUT:
HttpPut put = new HttpPut(uri);
if (data != null) {
put.setEntity(new InputStreamEntity(data));
}
return put;
case DELETE:
return new HttpDelete(uri);
case PATCH:
HttpPatch patch = new HttpPatch(uri);
if (data != null) {
patch.setEntity(new InputStreamEntity(data));
}
return patch;
default:
throw new ProxyException(ErrorResponse.methodNotAllowed("Will not proxy such calls."));
}
}
private static void copyHeaders(Map<String, List<String>> headers, HttpRequestBase toRequest) {
for (Map.Entry<String, List<String>> headerEntry : headers.entrySet()) {
if (HEADERS_TO_COPY.contains(headerEntry.getKey())) {
for (String value : headerEntry.getValue()) {
toRequest.addHeader(headerEntry.getKey(), value);
}
}
}
}
/**
* During upgrade, one server can be down, this is normal. Therefor we do a quick ping on the first server,
* if it is not responding, we try the other servers first. False positive/negatives are not critical,
* but will increase latency to some extent.
*/
private boolean queueFirstServerIfDown(List<URI> allServers, HostnameVerifier hostnameVerifier) {
if (allServers.size() < 2) {
return false;
}
URI uri = allServers.get(0);
HttpGet httpget = new HttpGet(uri);
int timeout = 500;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(httpget)
) {
if (response.getStatusLine().getStatusCode() == 200) {
return false;
}
} catch (IOException e) {
}
Collections.rotate(allServers, -1);
return true;
}
private static CloseableHttpClient createHttpClient(RequestConfig config,
ServiceIdentityProvider sslContextProvider,
HostnameVerifier hostnameVerifier) {
return HttpClientBuilder.create()
.setUserAgent("config-server-proxy-client")
.setSslcontext(sslContextProvider.getIdentitySslContext())
.setSSLHostnameVerifier(hostnameVerifier)
.setDefaultRequestConfig(config)
.build();
}
} |
Primarily its because we use /zone/v2 in dashboard to access application config which is only available on the configserver to which the application was deployed (See VESPA-11845). | private List<URI> getConfigserverEndpoints(ZoneId zoneId) {
if (zoneId.region().value().startsWith("aws-") || zoneId.region().value().contains("-aws-")) {
return List.of(zoneRegistry.getConfigServerVipUri(zoneId));
} else {
return new ArrayList<>(zoneRegistry.getConfigServerUris(zoneId));
}
} | private List<URI> getConfigserverEndpoints(ZoneId zoneId) {
if (zoneId.region().value().startsWith("aws-") || zoneId.region().value().contains("-aws-")) {
return List.of(zoneRegistry.getConfigServerVipUri(zoneId));
} else {
return new ArrayList<>(zoneRegistry.getConfigServerUris(zoneId));
}
} | class ConfigServerRestExecutorImpl implements ConfigServerRestExecutor {
private static final Logger log = Logger.getLogger(ConfigServerRestExecutorImpl.class.getName());
private static final Duration PROXY_REQUEST_TIMEOUT = Duration.ofSeconds(10);
private static final Set<String> HEADERS_TO_COPY = Set.of("X-HTTP-Method-Override", "Content-Type");
private final ZoneRegistry zoneRegistry;
private final ServiceIdentityProvider sslContextProvider;
@Inject
public ConfigServerRestExecutorImpl(ZoneRegistry zoneRegistry, ServiceIdentityProvider sslContextProvider) {
this.zoneRegistry = zoneRegistry;
this.sslContextProvider = sslContextProvider;
}
@Override
public ProxyResponse handle(ProxyRequest proxyRequest) throws ProxyException {
HostnameVerifier hostnameVerifier = createHostnameVerifier(proxyRequest.getZoneId());
List<URI> allServers = getConfigserverEndpoints(proxyRequest.getZoneId());
StringBuilder errorBuilder = new StringBuilder();
if (queueFirstServerIfDown(allServers, hostnameVerifier)) {
errorBuilder.append("Change ordering due to failed ping.");
}
for (URI uri : allServers) {
Optional<ProxyResponse> proxyResponse = proxyCall(uri, proxyRequest, hostnameVerifier, errorBuilder);
if (proxyResponse.isPresent()) {
return proxyResponse.get();
}
}
throw new ProxyException(ErrorResponse.internalServerError("Failed talking to config servers: "
+ errorBuilder.toString()));
}
private Optional<ProxyResponse> proxyCall(
URI uri, ProxyRequest proxyRequest, HostnameVerifier hostnameVerifier, StringBuilder errorBuilder)
throws ProxyException {
final HttpRequestBase requestBase = createHttpBaseRequest(
proxyRequest.getMethod(), proxyRequest.createConfigServerRequestUri(uri), proxyRequest.getData());
copyHeaders(proxyRequest.getHeaders(), requestBase);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setConnectionRequestTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setSocketTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis()).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(requestBase)
) {
String content = getContent(response);
int status = response.getStatusLine().getStatusCode();
if (status / 100 == 5) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(", got ").append(status).append(" ")
.append(content).append("\n");
log.log(LogLevel.DEBUG, () -> String.format("Got response from %s with status code %d and content:\n %s",
uri.getHost(), status, content));
return Optional.empty();
}
final Header contentHeader = response.getLastHeader("Content-Type");
final String contentType;
if (contentHeader != null && contentHeader.getValue() != null && ! contentHeader.getValue().isEmpty()) {
contentType = contentHeader.getValue().replace("; charset=UTF-8","");
} else {
contentType = "application/json";
}
return Optional.of(new ProxyResponse(proxyRequest, content, status, uri, contentType));
} catch (Exception e) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(" got exception ").append(e.getMessage());
log.log(LogLevel.DEBUG, e, () -> "Got exception while sending request to " + uri.getHost());
return Optional.empty();
}
}
private static String getContent(CloseableHttpResponse response) {
return Optional.ofNullable(response.getEntity())
.map(entity -> uncheck(() -> EntityUtils.toString(entity)))
.orElse("");
}
private static HttpRequestBase createHttpBaseRequest(Method method, URI uri, InputStream data) throws ProxyException {
switch (method) {
case GET:
return new HttpGet(uri);
case POST:
HttpPost post = new HttpPost(uri);
if (data != null) {
post.setEntity(new InputStreamEntity(data));
}
return post;
case PUT:
HttpPut put = new HttpPut(uri);
if (data != null) {
put.setEntity(new InputStreamEntity(data));
}
return put;
case DELETE:
return new HttpDelete(uri);
case PATCH:
HttpPatch patch = new HttpPatch(uri);
if (data != null) {
patch.setEntity(new InputStreamEntity(data));
}
return patch;
default:
throw new ProxyException(ErrorResponse.methodNotAllowed("Will not proxy such calls."));
}
}
private static void copyHeaders(Map<String, List<String>> headers, HttpRequestBase toRequest) {
for (Map.Entry<String, List<String>> headerEntry : headers.entrySet()) {
if (HEADERS_TO_COPY.contains(headerEntry.getKey())) {
for (String value : headerEntry.getValue()) {
toRequest.addHeader(headerEntry.getKey(), value);
}
}
}
}
/**
* During upgrade, one server can be down, this is normal. Therefor we do a quick ping on the first server,
* if it is not responding, we try the other servers first. False positive/negatives are not critical,
* but will increase latency to some extent.
*/
private boolean queueFirstServerIfDown(List<URI> allServers, HostnameVerifier hostnameVerifier) {
if (allServers.size() < 2) {
return false;
}
URI uri = allServers.get(0);
HttpGet httpget = new HttpGet(uri);
int timeout = 500;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(httpget)
) {
if (response.getStatusLine().getStatusCode() == 200) {
return false;
}
} catch (IOException e) {
}
Collections.rotate(allServers, -1);
return true;
}
private HostnameVerifier createHostnameVerifier(ZoneId zoneId) {
return new AthenzIdentityVerifier(Set.of(zoneRegistry.getConfigServerHttpsIdentity(zoneId)));
}
private static CloseableHttpClient createHttpClient(RequestConfig config,
ServiceIdentityProvider sslContextProvider,
HostnameVerifier hostnameVerifier) {
return HttpClientBuilder.create()
.setUserAgent("config-server-proxy-client")
.setSslcontext(sslContextProvider.getIdentitySslContext())
.setSSLHostnameVerifier(hostnameVerifier)
.setDefaultRequestConfig(config)
.build();
}
} | class ConfigServerRestExecutorImpl implements ConfigServerRestExecutor {
private static final Logger log = Logger.getLogger(ConfigServerRestExecutorImpl.class.getName());
private static final Duration PROXY_REQUEST_TIMEOUT = Duration.ofSeconds(10);
private static final Set<String> HEADERS_TO_COPY = Set.of("X-HTTP-Method-Override", "Content-Type");
private final ZoneRegistry zoneRegistry;
private final ServiceIdentityProvider sslContextProvider;
@Inject
public ConfigServerRestExecutorImpl(ZoneRegistry zoneRegistry, ServiceIdentityProvider sslContextProvider) {
this.zoneRegistry = zoneRegistry;
this.sslContextProvider = sslContextProvider;
}
@Override
public ProxyResponse handle(ProxyRequest proxyRequest) throws ProxyException {
HostnameVerifier hostnameVerifier = createHostnameVerifier(proxyRequest.getZoneId());
List<URI> allServers = getConfigserverEndpoints(proxyRequest.getZoneId());
StringBuilder errorBuilder = new StringBuilder();
if (queueFirstServerIfDown(allServers, hostnameVerifier)) {
errorBuilder.append("Change ordering due to failed ping.");
}
for (URI uri : allServers) {
Optional<ProxyResponse> proxyResponse = proxyCall(uri, proxyRequest, hostnameVerifier, errorBuilder);
if (proxyResponse.isPresent()) {
return proxyResponse.get();
}
}
throw new ProxyException(ErrorResponse.internalServerError("Failed talking to config servers: "
+ errorBuilder.toString()));
}
private Optional<ProxyResponse> proxyCall(
URI uri, ProxyRequest proxyRequest, HostnameVerifier hostnameVerifier, StringBuilder errorBuilder)
throws ProxyException {
final HttpRequestBase requestBase = createHttpBaseRequest(
proxyRequest.getMethod(), proxyRequest.createConfigServerRequestUri(uri), proxyRequest.getData());
copyHeaders(proxyRequest.getHeaders(), requestBase);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setConnectionRequestTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setSocketTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis()).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(requestBase)
) {
String content = getContent(response);
int status = response.getStatusLine().getStatusCode();
if (status / 100 == 5) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(", got ").append(status).append(" ")
.append(content).append("\n");
log.log(LogLevel.DEBUG, () -> String.format("Got response from %s with status code %d and content:\n %s",
uri.getHost(), status, content));
return Optional.empty();
}
final Header contentHeader = response.getLastHeader("Content-Type");
final String contentType;
if (contentHeader != null && contentHeader.getValue() != null && ! contentHeader.getValue().isEmpty()) {
contentType = contentHeader.getValue().replace("; charset=UTF-8","");
} else {
contentType = "application/json";
}
return Optional.of(new ProxyResponse(proxyRequest, content, status, uri, contentType));
} catch (Exception e) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(" got exception ").append(e.getMessage());
log.log(LogLevel.DEBUG, e, () -> "Got exception while sending request to " + uri.getHost());
return Optional.empty();
}
}
private static String getContent(CloseableHttpResponse response) {
return Optional.ofNullable(response.getEntity())
.map(entity -> uncheck(() -> EntityUtils.toString(entity)))
.orElse("");
}
private static HttpRequestBase createHttpBaseRequest(Method method, URI uri, InputStream data) throws ProxyException {
switch (method) {
case GET:
return new HttpGet(uri);
case POST:
HttpPost post = new HttpPost(uri);
if (data != null) {
post.setEntity(new InputStreamEntity(data));
}
return post;
case PUT:
HttpPut put = new HttpPut(uri);
if (data != null) {
put.setEntity(new InputStreamEntity(data));
}
return put;
case DELETE:
return new HttpDelete(uri);
case PATCH:
HttpPatch patch = new HttpPatch(uri);
if (data != null) {
patch.setEntity(new InputStreamEntity(data));
}
return patch;
default:
throw new ProxyException(ErrorResponse.methodNotAllowed("Will not proxy such calls."));
}
}
private static void copyHeaders(Map<String, List<String>> headers, HttpRequestBase toRequest) {
for (Map.Entry<String, List<String>> headerEntry : headers.entrySet()) {
if (HEADERS_TO_COPY.contains(headerEntry.getKey())) {
for (String value : headerEntry.getValue()) {
toRequest.addHeader(headerEntry.getKey(), value);
}
}
}
}
/**
* During upgrade, one server can be down, this is normal. Therefor we do a quick ping on the first server,
* if it is not responding, we try the other servers first. False positive/negatives are not critical,
* but will increase latency to some extent.
*/
private boolean queueFirstServerIfDown(List<URI> allServers, HostnameVerifier hostnameVerifier) {
if (allServers.size() < 2) {
return false;
}
URI uri = allServers.get(0);
HttpGet httpget = new HttpGet(uri);
int timeout = 500;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(httpget)
) {
if (response.getStatusLine().getStatusCode() == 200) {
return false;
}
} catch (IOException e) {
}
Collections.rotate(allServers, -1);
return true;
}
private HostnameVerifier createHostnameVerifier(ZoneId zoneId) {
return new AthenzIdentityVerifier(Set.of(zoneRegistry.getConfigServerHttpsIdentity(zoneId)));
}
private static CloseableHttpClient createHttpClient(RequestConfig config,
ServiceIdentityProvider sslContextProvider,
HostnameVerifier hostnameVerifier) {
return HttpClientBuilder.create()
.setUserAgent("config-server-proxy-client")
.setSslcontext(sslContextProvider.getIdentitySslContext())
.setSSLHostnameVerifier(hostnameVerifier)
.setDefaultRequestConfig(config)
.build();
}
} | |
Ok, thanks. | private List<URI> getConfigserverEndpoints(ZoneId zoneId) {
if (zoneId.region().value().startsWith("aws-") || zoneId.region().value().contains("-aws-")) {
return List.of(zoneRegistry.getConfigServerVipUri(zoneId));
} else {
return new ArrayList<>(zoneRegistry.getConfigServerUris(zoneId));
}
} | private List<URI> getConfigserverEndpoints(ZoneId zoneId) {
if (zoneId.region().value().startsWith("aws-") || zoneId.region().value().contains("-aws-")) {
return List.of(zoneRegistry.getConfigServerVipUri(zoneId));
} else {
return new ArrayList<>(zoneRegistry.getConfigServerUris(zoneId));
}
} | class ConfigServerRestExecutorImpl implements ConfigServerRestExecutor {
private static final Logger log = Logger.getLogger(ConfigServerRestExecutorImpl.class.getName());
private static final Duration PROXY_REQUEST_TIMEOUT = Duration.ofSeconds(10);
private static final Set<String> HEADERS_TO_COPY = Set.of("X-HTTP-Method-Override", "Content-Type");
private final ZoneRegistry zoneRegistry;
private final ServiceIdentityProvider sslContextProvider;
@Inject
public ConfigServerRestExecutorImpl(ZoneRegistry zoneRegistry, ServiceIdentityProvider sslContextProvider) {
this.zoneRegistry = zoneRegistry;
this.sslContextProvider = sslContextProvider;
}
@Override
public ProxyResponse handle(ProxyRequest proxyRequest) throws ProxyException {
HostnameVerifier hostnameVerifier = createHostnameVerifier(proxyRequest.getZoneId());
List<URI> allServers = getConfigserverEndpoints(proxyRequest.getZoneId());
StringBuilder errorBuilder = new StringBuilder();
if (queueFirstServerIfDown(allServers, hostnameVerifier)) {
errorBuilder.append("Change ordering due to failed ping.");
}
for (URI uri : allServers) {
Optional<ProxyResponse> proxyResponse = proxyCall(uri, proxyRequest, hostnameVerifier, errorBuilder);
if (proxyResponse.isPresent()) {
return proxyResponse.get();
}
}
throw new ProxyException(ErrorResponse.internalServerError("Failed talking to config servers: "
+ errorBuilder.toString()));
}
private Optional<ProxyResponse> proxyCall(
URI uri, ProxyRequest proxyRequest, HostnameVerifier hostnameVerifier, StringBuilder errorBuilder)
throws ProxyException {
final HttpRequestBase requestBase = createHttpBaseRequest(
proxyRequest.getMethod(), proxyRequest.createConfigServerRequestUri(uri), proxyRequest.getData());
copyHeaders(proxyRequest.getHeaders(), requestBase);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setConnectionRequestTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setSocketTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis()).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(requestBase)
) {
String content = getContent(response);
int status = response.getStatusLine().getStatusCode();
if (status / 100 == 5) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(", got ").append(status).append(" ")
.append(content).append("\n");
log.log(LogLevel.DEBUG, () -> String.format("Got response from %s with status code %d and content:\n %s",
uri.getHost(), status, content));
return Optional.empty();
}
final Header contentHeader = response.getLastHeader("Content-Type");
final String contentType;
if (contentHeader != null && contentHeader.getValue() != null && ! contentHeader.getValue().isEmpty()) {
contentType = contentHeader.getValue().replace("; charset=UTF-8","");
} else {
contentType = "application/json";
}
return Optional.of(new ProxyResponse(proxyRequest, content, status, uri, contentType));
} catch (Exception e) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(" got exception ").append(e.getMessage());
log.log(LogLevel.DEBUG, e, () -> "Got exception while sending request to " + uri.getHost());
return Optional.empty();
}
}
private static String getContent(CloseableHttpResponse response) {
return Optional.ofNullable(response.getEntity())
.map(entity -> uncheck(() -> EntityUtils.toString(entity)))
.orElse("");
}
private static HttpRequestBase createHttpBaseRequest(Method method, URI uri, InputStream data) throws ProxyException {
switch (method) {
case GET:
return new HttpGet(uri);
case POST:
HttpPost post = new HttpPost(uri);
if (data != null) {
post.setEntity(new InputStreamEntity(data));
}
return post;
case PUT:
HttpPut put = new HttpPut(uri);
if (data != null) {
put.setEntity(new InputStreamEntity(data));
}
return put;
case DELETE:
return new HttpDelete(uri);
case PATCH:
HttpPatch patch = new HttpPatch(uri);
if (data != null) {
patch.setEntity(new InputStreamEntity(data));
}
return patch;
default:
throw new ProxyException(ErrorResponse.methodNotAllowed("Will not proxy such calls."));
}
}
private static void copyHeaders(Map<String, List<String>> headers, HttpRequestBase toRequest) {
for (Map.Entry<String, List<String>> headerEntry : headers.entrySet()) {
if (HEADERS_TO_COPY.contains(headerEntry.getKey())) {
for (String value : headerEntry.getValue()) {
toRequest.addHeader(headerEntry.getKey(), value);
}
}
}
}
/**
* During upgrade, one server can be down, this is normal. Therefor we do a quick ping on the first server,
* if it is not responding, we try the other servers first. False positive/negatives are not critical,
* but will increase latency to some extent.
*/
private boolean queueFirstServerIfDown(List<URI> allServers, HostnameVerifier hostnameVerifier) {
if (allServers.size() < 2) {
return false;
}
URI uri = allServers.get(0);
HttpGet httpget = new HttpGet(uri);
int timeout = 500;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(httpget)
) {
if (response.getStatusLine().getStatusCode() == 200) {
return false;
}
} catch (IOException e) {
}
Collections.rotate(allServers, -1);
return true;
}
private HostnameVerifier createHostnameVerifier(ZoneId zoneId) {
return new AthenzIdentityVerifier(Set.of(zoneRegistry.getConfigServerHttpsIdentity(zoneId)));
}
private static CloseableHttpClient createHttpClient(RequestConfig config,
ServiceIdentityProvider sslContextProvider,
HostnameVerifier hostnameVerifier) {
return HttpClientBuilder.create()
.setUserAgent("config-server-proxy-client")
.setSslcontext(sslContextProvider.getIdentitySslContext())
.setSSLHostnameVerifier(hostnameVerifier)
.setDefaultRequestConfig(config)
.build();
}
} | class ConfigServerRestExecutorImpl implements ConfigServerRestExecutor {
private static final Logger log = Logger.getLogger(ConfigServerRestExecutorImpl.class.getName());
private static final Duration PROXY_REQUEST_TIMEOUT = Duration.ofSeconds(10);
private static final Set<String> HEADERS_TO_COPY = Set.of("X-HTTP-Method-Override", "Content-Type");
private final ZoneRegistry zoneRegistry;
private final ServiceIdentityProvider sslContextProvider;
@Inject
public ConfigServerRestExecutorImpl(ZoneRegistry zoneRegistry, ServiceIdentityProvider sslContextProvider) {
this.zoneRegistry = zoneRegistry;
this.sslContextProvider = sslContextProvider;
}
@Override
public ProxyResponse handle(ProxyRequest proxyRequest) throws ProxyException {
HostnameVerifier hostnameVerifier = createHostnameVerifier(proxyRequest.getZoneId());
List<URI> allServers = getConfigserverEndpoints(proxyRequest.getZoneId());
StringBuilder errorBuilder = new StringBuilder();
if (queueFirstServerIfDown(allServers, hostnameVerifier)) {
errorBuilder.append("Change ordering due to failed ping.");
}
for (URI uri : allServers) {
Optional<ProxyResponse> proxyResponse = proxyCall(uri, proxyRequest, hostnameVerifier, errorBuilder);
if (proxyResponse.isPresent()) {
return proxyResponse.get();
}
}
throw new ProxyException(ErrorResponse.internalServerError("Failed talking to config servers: "
+ errorBuilder.toString()));
}
private Optional<ProxyResponse> proxyCall(
URI uri, ProxyRequest proxyRequest, HostnameVerifier hostnameVerifier, StringBuilder errorBuilder)
throws ProxyException {
final HttpRequestBase requestBase = createHttpBaseRequest(
proxyRequest.getMethod(), proxyRequest.createConfigServerRequestUri(uri), proxyRequest.getData());
copyHeaders(proxyRequest.getHeaders(), requestBase);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setConnectionRequestTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis())
.setSocketTimeout((int) PROXY_REQUEST_TIMEOUT.toMillis()).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(requestBase)
) {
String content = getContent(response);
int status = response.getStatusLine().getStatusCode();
if (status / 100 == 5) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(", got ").append(status).append(" ")
.append(content).append("\n");
log.log(LogLevel.DEBUG, () -> String.format("Got response from %s with status code %d and content:\n %s",
uri.getHost(), status, content));
return Optional.empty();
}
final Header contentHeader = response.getLastHeader("Content-Type");
final String contentType;
if (contentHeader != null && contentHeader.getValue() != null && ! contentHeader.getValue().isEmpty()) {
contentType = contentHeader.getValue().replace("; charset=UTF-8","");
} else {
contentType = "application/json";
}
return Optional.of(new ProxyResponse(proxyRequest, content, status, uri, contentType));
} catch (Exception e) {
errorBuilder.append("Talking to server ").append(uri.getHost());
errorBuilder.append(" got exception ").append(e.getMessage());
log.log(LogLevel.DEBUG, e, () -> "Got exception while sending request to " + uri.getHost());
return Optional.empty();
}
}
private static String getContent(CloseableHttpResponse response) {
return Optional.ofNullable(response.getEntity())
.map(entity -> uncheck(() -> EntityUtils.toString(entity)))
.orElse("");
}
private static HttpRequestBase createHttpBaseRequest(Method method, URI uri, InputStream data) throws ProxyException {
switch (method) {
case GET:
return new HttpGet(uri);
case POST:
HttpPost post = new HttpPost(uri);
if (data != null) {
post.setEntity(new InputStreamEntity(data));
}
return post;
case PUT:
HttpPut put = new HttpPut(uri);
if (data != null) {
put.setEntity(new InputStreamEntity(data));
}
return put;
case DELETE:
return new HttpDelete(uri);
case PATCH:
HttpPatch patch = new HttpPatch(uri);
if (data != null) {
patch.setEntity(new InputStreamEntity(data));
}
return patch;
default:
throw new ProxyException(ErrorResponse.methodNotAllowed("Will not proxy such calls."));
}
}
private static void copyHeaders(Map<String, List<String>> headers, HttpRequestBase toRequest) {
for (Map.Entry<String, List<String>> headerEntry : headers.entrySet()) {
if (HEADERS_TO_COPY.contains(headerEntry.getKey())) {
for (String value : headerEntry.getValue()) {
toRequest.addHeader(headerEntry.getKey(), value);
}
}
}
}
/**
* During upgrade, one server can be down, this is normal. Therefor we do a quick ping on the first server,
* if it is not responding, we try the other servers first. False positive/negatives are not critical,
* but will increase latency to some extent.
*/
private boolean queueFirstServerIfDown(List<URI> allServers, HostnameVerifier hostnameVerifier) {
if (allServers.size() < 2) {
return false;
}
URI uri = allServers.get(0);
HttpGet httpget = new HttpGet(uri);
int timeout = 500;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout).build();
try (
CloseableHttpClient client = createHttpClient(config, sslContextProvider, hostnameVerifier);
CloseableHttpResponse response = client.execute(httpget)
) {
if (response.getStatusLine().getStatusCode() == 200) {
return false;
}
} catch (IOException e) {
}
Collections.rotate(allServers, -1);
return true;
}
private HostnameVerifier createHostnameVerifier(ZoneId zoneId) {
return new AthenzIdentityVerifier(Set.of(zoneRegistry.getConfigServerHttpsIdentity(zoneId)));
}
private static CloseableHttpClient createHttpClient(RequestConfig config,
ServiceIdentityProvider sslContextProvider,
HostnameVerifier hostnameVerifier) {
return HttpClientBuilder.create()
.setUserAgent("config-server-proxy-client")
.setSslcontext(sslContextProvider.getIdentitySslContext())
.setSSLHostnameVerifier(hostnameVerifier)
.setDefaultRequestConfig(config)
.build();
}
} | |
Why does this increase? | public void name_service_queue_size_metric() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("default")
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext()
.deferDnsUpdates();
reporter.maintain();
assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals("Deployment queues name services requests", 15, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
context.flushDnsUpdates();
reporter.maintain();
assertEquals("Queue consumed", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
} | assertEquals("Deployment queues name services requests", 15, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue()); | public void name_service_queue_size_metric() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("default")
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext()
.deferDnsUpdates();
reporter.maintain();
assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals("Deployment queues name services requests", 15, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
context.flushDnsUpdates();
reporter.maintain();
assertEquals("Queue consumed", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
} | class MetricsReporterTest {
private final MetricsMock metrics = new MetricsMock();
@Test
public void deployment_fail_ratio() {
var tester = new InternalDeploymentTester();
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));
var context1 = tester.newDeploymentContext("app1", "tenant1", "default");
var context2 = tester.newDeploymentContext("app2", "tenant1", "default");
var context3 = tester.newDeploymentContext("app3", "tenant1", "default");
var context4 = tester.newDeploymentContext("app4", "tenant1", "default");
context1.submit(applicationPackage).deploy();
context2.submit(applicationPackage).deploy();
context3.submit(applicationPackage).deploy();
context4.submit(applicationPackage).deploy();
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
context1.submit(applicationPackage)
.triggerJobs()
.failDeployment(systemTest);
metricsReporter.maintain();
assertEquals(25.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
}
@Test
public void deployment_average_duration() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext()
.submit(applicationPackage)
.deploy();
reporter.maintain();
assertEquals(Duration.ZERO, getAverageDeploymentDuration(context.instanceId()));
context.submit(applicationPackage);
tester.clock().advance(Duration.ofHours(1));
context.runJob(systemTest);
tester.clock().advance(Duration.ofMinutes(30));
context.runJob(stagingTest);
tester.triggerJobs();
tester.clock().advance(Duration.ofMinutes(90));
context.runJob(productionUsWest1);
reporter.maintain();
assertEquals(Duration.ofMinutes(80), getAverageDeploymentDuration(context.instanceId()));
context.submit(applicationPackage)
.triggerJobs();
tester.clock().advance(Duration.ofHours(12));
reporter.maintain();
assertEquals(Duration.ofHours(12)
.plus(Duration.ofHours(12))
.plus(Duration.ofMinutes(90))
.dividedBy(3),
getAverageDeploymentDuration(context.instanceId()));
}
@Test
public void deployments_failing_upgrade() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext();
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
context.submit(applicationPackage)
.triggerJobs()
.failDeployment(systemTest);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
context.deploy();
assertFalse("Change deployed", context.application().change().hasTargets());
Version version = Version.fromString("7.1");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
context.triggerJobs()
.failDeployment(systemTest)
.failDeployment(stagingTest);
reporter.maintain();
assertEquals(2, getDeploymentsFailingUpgrade(context.instanceId()));
context.runJob(systemTest)
.runJob(stagingTest)
.triggerJobs()
.failDeployment(productionUsWest1);
reporter.maintain();
assertEquals(1, getDeploymentsFailingUpgrade(context.instanceId()));
context.runJob(productionUsWest1);
assertFalse("Upgrade deployed", context.application().change().hasTargets());
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
}
@Test
public void deployment_warnings_metric() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext();
tester.configServer().generateWarnings(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")), 3);
tester.configServer().generateWarnings(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")), 4);
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals(4, getDeploymentWarnings(context.instanceId()));
}
@Test
public void build_time_reporting() {
var tester = new InternalDeploymentTester();
var applicationPackage = new ApplicationPackageBuilder().region("us-west-1").build();
var context = tester.deploymentContext()
.submit(applicationPackage)
.deploy();
assertEquals(1000, context.lastSubmission().get().buildTime().get().toEpochMilli());
MetricsReporter reporter = createReporter(tester.tester().controller());
reporter.maintain();
assertEquals(tester.clock().instant().getEpochSecond() - 1,
getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, context.instanceId()));
}
@Test
@Test
public void nodes_failing_system_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone1 = ZoneApiMock.fromId("prod.eu-west-1");
tester.zoneRegistry().setUpgradePolicy(UpgradePolicy.create().upgrade(zone1));
var systemUpgrader = new SystemUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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
public void nodes_failing_os_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone = ZoneApiMock.fromId("prod.eu-west-1");
var cloud = CloudName.defaultName();
tester.zoneRegistry().setOsUpgradePolicy(cloud, UpgradePolicy.create().upgrade(zone));
var osUpgrader = new OsUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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());
}
}
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 deployment_fail_ratio() {
var tester = new InternalDeploymentTester();
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));
var context1 = tester.newDeploymentContext("app1", "tenant1", "default");
var context2 = tester.newDeploymentContext("app2", "tenant1", "default");
var context3 = tester.newDeploymentContext("app3", "tenant1", "default");
var context4 = tester.newDeploymentContext("app4", "tenant1", "default");
context1.submit(applicationPackage).deploy();
context2.submit(applicationPackage).deploy();
context3.submit(applicationPackage).deploy();
context4.submit(applicationPackage).deploy();
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
context1.submit(applicationPackage)
.triggerJobs()
.failDeployment(systemTest);
metricsReporter.maintain();
assertEquals(25.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
}
@Test
public void deployment_average_duration() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext()
.submit(applicationPackage)
.deploy();
reporter.maintain();
assertEquals(Duration.ZERO, getAverageDeploymentDuration(context.instanceId()));
context.submit(applicationPackage);
tester.clock().advance(Duration.ofHours(1));
context.runJob(systemTest);
tester.clock().advance(Duration.ofMinutes(30));
context.runJob(stagingTest);
tester.triggerJobs();
tester.clock().advance(Duration.ofMinutes(90));
context.runJob(productionUsWest1);
reporter.maintain();
assertEquals(Duration.ofMinutes(80), getAverageDeploymentDuration(context.instanceId()));
context.submit(applicationPackage)
.triggerJobs();
tester.clock().advance(Duration.ofHours(12));
reporter.maintain();
assertEquals(Duration.ofHours(12)
.plus(Duration.ofHours(12))
.plus(Duration.ofMinutes(90))
.dividedBy(3),
getAverageDeploymentDuration(context.instanceId()));
}
@Test
public void deployments_failing_upgrade() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext();
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
context.submit(applicationPackage)
.triggerJobs()
.failDeployment(systemTest);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
context.deploy();
assertFalse("Change deployed", context.application().change().hasTargets());
Version version = Version.fromString("7.1");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
context.triggerJobs()
.failDeployment(systemTest)
.failDeployment(stagingTest);
reporter.maintain();
assertEquals(2, getDeploymentsFailingUpgrade(context.instanceId()));
context.runJob(systemTest)
.runJob(stagingTest)
.triggerJobs()
.failDeployment(productionUsWest1);
reporter.maintain();
assertEquals(1, getDeploymentsFailingUpgrade(context.instanceId()));
context.runJob(productionUsWest1);
assertFalse("Upgrade deployed", context.application().change().hasTargets());
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
}
@Test
public void deployment_warnings_metric() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext();
tester.configServer().generateWarnings(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")), 3);
tester.configServer().generateWarnings(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")), 4);
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals(4, getDeploymentWarnings(context.instanceId()));
}
@Test
public void build_time_reporting() {
var tester = new InternalDeploymentTester();
var applicationPackage = new ApplicationPackageBuilder().region("us-west-1").build();
var context = tester.deploymentContext()
.submit(applicationPackage)
.deploy();
assertEquals(1000, context.lastSubmission().get().buildTime().get().toEpochMilli());
MetricsReporter reporter = createReporter(tester.tester().controller());
reporter.maintain();
assertEquals(tester.clock().instant().getEpochSecond() - 1,
getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, context.instanceId()));
}
@Test
@Test
public void nodes_failing_system_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone1 = ZoneApiMock.fromId("prod.eu-west-1");
tester.zoneRegistry().setUpgradePolicy(UpgradePolicy.create().upgrade(zone1));
var systemUpgrader = new SystemUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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
public void nodes_failing_os_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone = ZoneApiMock.fromId("prod.eu-west-1");
var cloud = CloudName.defaultName();
tester.zoneRegistry().setOsUpgradePolicy(cloud, UpgradePolicy.create().upgrade(zone));
var osUpgrader = new OsUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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());
}
}
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();
}
} |
The application gets a rotation earlier (the first time it rolls out), so deployments in test (x1) and staging (x2) also cause 3 requests. This would previously happen on every subsequent rollout of the application, as well. | public void name_service_queue_size_metric() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("default")
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext()
.deferDnsUpdates();
reporter.maintain();
assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals("Deployment queues name services requests", 15, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
context.flushDnsUpdates();
reporter.maintain();
assertEquals("Queue consumed", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
} | assertEquals("Deployment queues name services requests", 15, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue()); | public void name_service_queue_size_metric() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("default")
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext()
.deferDnsUpdates();
reporter.maintain();
assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals("Deployment queues name services requests", 15, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
context.flushDnsUpdates();
reporter.maintain();
assertEquals("Queue consumed", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
} | class MetricsReporterTest {
private final MetricsMock metrics = new MetricsMock();
@Test
public void deployment_fail_ratio() {
var tester = new InternalDeploymentTester();
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));
var context1 = tester.newDeploymentContext("app1", "tenant1", "default");
var context2 = tester.newDeploymentContext("app2", "tenant1", "default");
var context3 = tester.newDeploymentContext("app3", "tenant1", "default");
var context4 = tester.newDeploymentContext("app4", "tenant1", "default");
context1.submit(applicationPackage).deploy();
context2.submit(applicationPackage).deploy();
context3.submit(applicationPackage).deploy();
context4.submit(applicationPackage).deploy();
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
context1.submit(applicationPackage)
.triggerJobs()
.failDeployment(systemTest);
metricsReporter.maintain();
assertEquals(25.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
}
@Test
public void deployment_average_duration() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext()
.submit(applicationPackage)
.deploy();
reporter.maintain();
assertEquals(Duration.ZERO, getAverageDeploymentDuration(context.instanceId()));
context.submit(applicationPackage);
tester.clock().advance(Duration.ofHours(1));
context.runJob(systemTest);
tester.clock().advance(Duration.ofMinutes(30));
context.runJob(stagingTest);
tester.triggerJobs();
tester.clock().advance(Duration.ofMinutes(90));
context.runJob(productionUsWest1);
reporter.maintain();
assertEquals(Duration.ofMinutes(80), getAverageDeploymentDuration(context.instanceId()));
context.submit(applicationPackage)
.triggerJobs();
tester.clock().advance(Duration.ofHours(12));
reporter.maintain();
assertEquals(Duration.ofHours(12)
.plus(Duration.ofHours(12))
.plus(Duration.ofMinutes(90))
.dividedBy(3),
getAverageDeploymentDuration(context.instanceId()));
}
@Test
public void deployments_failing_upgrade() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext();
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
context.submit(applicationPackage)
.triggerJobs()
.failDeployment(systemTest);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
context.deploy();
assertFalse("Change deployed", context.application().change().hasTargets());
Version version = Version.fromString("7.1");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
context.triggerJobs()
.failDeployment(systemTest)
.failDeployment(stagingTest);
reporter.maintain();
assertEquals(2, getDeploymentsFailingUpgrade(context.instanceId()));
context.runJob(systemTest)
.runJob(stagingTest)
.triggerJobs()
.failDeployment(productionUsWest1);
reporter.maintain();
assertEquals(1, getDeploymentsFailingUpgrade(context.instanceId()));
context.runJob(productionUsWest1);
assertFalse("Upgrade deployed", context.application().change().hasTargets());
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
}
@Test
public void deployment_warnings_metric() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext();
tester.configServer().generateWarnings(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")), 3);
tester.configServer().generateWarnings(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")), 4);
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals(4, getDeploymentWarnings(context.instanceId()));
}
@Test
public void build_time_reporting() {
var tester = new InternalDeploymentTester();
var applicationPackage = new ApplicationPackageBuilder().region("us-west-1").build();
var context = tester.deploymentContext()
.submit(applicationPackage)
.deploy();
assertEquals(1000, context.lastSubmission().get().buildTime().get().toEpochMilli());
MetricsReporter reporter = createReporter(tester.tester().controller());
reporter.maintain();
assertEquals(tester.clock().instant().getEpochSecond() - 1,
getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, context.instanceId()));
}
@Test
@Test
public void nodes_failing_system_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone1 = ZoneApiMock.fromId("prod.eu-west-1");
tester.zoneRegistry().setUpgradePolicy(UpgradePolicy.create().upgrade(zone1));
var systemUpgrader = new SystemUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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
public void nodes_failing_os_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone = ZoneApiMock.fromId("prod.eu-west-1");
var cloud = CloudName.defaultName();
tester.zoneRegistry().setOsUpgradePolicy(cloud, UpgradePolicy.create().upgrade(zone));
var osUpgrader = new OsUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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());
}
}
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 deployment_fail_ratio() {
var tester = new InternalDeploymentTester();
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));
var context1 = tester.newDeploymentContext("app1", "tenant1", "default");
var context2 = tester.newDeploymentContext("app2", "tenant1", "default");
var context3 = tester.newDeploymentContext("app3", "tenant1", "default");
var context4 = tester.newDeploymentContext("app4", "tenant1", "default");
context1.submit(applicationPackage).deploy();
context2.submit(applicationPackage).deploy();
context3.submit(applicationPackage).deploy();
context4.submit(applicationPackage).deploy();
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
context1.submit(applicationPackage)
.triggerJobs()
.failDeployment(systemTest);
metricsReporter.maintain();
assertEquals(25.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
}
@Test
public void deployment_average_duration() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext()
.submit(applicationPackage)
.deploy();
reporter.maintain();
assertEquals(Duration.ZERO, getAverageDeploymentDuration(context.instanceId()));
context.submit(applicationPackage);
tester.clock().advance(Duration.ofHours(1));
context.runJob(systemTest);
tester.clock().advance(Duration.ofMinutes(30));
context.runJob(stagingTest);
tester.triggerJobs();
tester.clock().advance(Duration.ofMinutes(90));
context.runJob(productionUsWest1);
reporter.maintain();
assertEquals(Duration.ofMinutes(80), getAverageDeploymentDuration(context.instanceId()));
context.submit(applicationPackage)
.triggerJobs();
tester.clock().advance(Duration.ofHours(12));
reporter.maintain();
assertEquals(Duration.ofHours(12)
.plus(Duration.ofHours(12))
.plus(Duration.ofMinutes(90))
.dividedBy(3),
getAverageDeploymentDuration(context.instanceId()));
}
@Test
public void deployments_failing_upgrade() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext();
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
context.submit(applicationPackage)
.triggerJobs()
.failDeployment(systemTest);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
context.deploy();
assertFalse("Change deployed", context.application().change().hasTargets());
Version version = Version.fromString("7.1");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
context.triggerJobs()
.failDeployment(systemTest)
.failDeployment(stagingTest);
reporter.maintain();
assertEquals(2, getDeploymentsFailingUpgrade(context.instanceId()));
context.runJob(systemTest)
.runJob(stagingTest)
.triggerJobs()
.failDeployment(productionUsWest1);
reporter.maintain();
assertEquals(1, getDeploymentsFailingUpgrade(context.instanceId()));
context.runJob(productionUsWest1);
assertFalse("Upgrade deployed", context.application().change().hasTargets());
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
}
@Test
public void deployment_warnings_metric() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext();
tester.configServer().generateWarnings(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")), 3);
tester.configServer().generateWarnings(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")), 4);
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals(4, getDeploymentWarnings(context.instanceId()));
}
@Test
public void build_time_reporting() {
var tester = new InternalDeploymentTester();
var applicationPackage = new ApplicationPackageBuilder().region("us-west-1").build();
var context = tester.deploymentContext()
.submit(applicationPackage)
.deploy();
assertEquals(1000, context.lastSubmission().get().buildTime().get().toEpochMilli());
MetricsReporter reporter = createReporter(tester.tester().controller());
reporter.maintain();
assertEquals(tester.clock().instant().getEpochSecond() - 1,
getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, context.instanceId()));
}
@Test
@Test
public void nodes_failing_system_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone1 = ZoneApiMock.fromId("prod.eu-west-1");
tester.zoneRegistry().setUpgradePolicy(UpgradePolicy.create().upgrade(zone1));
var systemUpgrader = new SystemUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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
public void nodes_failing_os_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone = ZoneApiMock.fromId("prod.eu-west-1");
var cloud = CloudName.defaultName();
tester.zoneRegistry().setOsUpgradePolicy(cloud, UpgradePolicy.create().upgrade(zone));
var osUpgrader = new OsUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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());
}
}
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();
}
} |
No, it's an OptionalLong :'( | public boolean triggerAt(Instant instant, JobType job, JobStatus jobStatus, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
if (instance.deploymentJobs().statusOf(job).map(status -> status.pausedUntil().orElse(0)).orElse(0L) > clock.millis()) return false;
if (jobStatus.lastTriggered().isEmpty()) return true;
if (jobStatus.isSuccess()) return true;
if (jobStatus.lastCompleted().isEmpty()) return true;
if (jobStatus.firstFailing().isEmpty()) return true;
if ( ! versions.targetsMatch(jobStatus.lastCompleted().get().versions())) return true;
if (deploymentSpec.requireInstance(instance.name()).upgradePolicy() == DeploymentSpec.UpgradePolicy.canary) return true;
Instant firstFailing = jobStatus.firstFailing().get().end().get();
Instant lastCompleted = jobStatus.lastCompleted().get().end().get();
if (firstFailing.isAfter(instant.minus(Duration.ofMinutes(1)))) return true;
if (job.isTest() && jobStatus.isOutOfCapacity()) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(1)));
}
if (firstFailing.isAfter(instant.minus(Duration.ofHours(1)))) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(10)));
}
return lastCompleted.isBefore(instant.minus(Duration.ofHours(2)));
} | if (instance.deploymentJobs().statusOf(job).map(status -> status.pausedUntil().orElse(0)).orElse(0L) > clock.millis()) return false; | public boolean triggerAt(Instant instant, JobType job, JobStatus jobStatus, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
if (instance.deploymentJobs().statusOf(job).map(status -> status.pausedUntil().orElse(0)).orElse(0L) > clock.millis()) return false;
if (jobStatus.lastTriggered().isEmpty()) return true;
if (jobStatus.isSuccess()) return true;
if (jobStatus.lastCompleted().isEmpty()) return true;
if (jobStatus.firstFailing().isEmpty()) return true;
if ( ! versions.targetsMatch(jobStatus.lastCompleted().get().versions())) return true;
if (deploymentSpec.requireInstance(instance.name()).upgradePolicy() == DeploymentSpec.UpgradePolicy.canary) return true;
Instant firstFailing = jobStatus.firstFailing().get().end().get();
Instant lastCompleted = jobStatus.lastCompleted().get().end().get();
if (firstFailing.isAfter(instant.minus(Duration.ofMinutes(1)))) return true;
if (job.isTest() && jobStatus.isOutOfCapacity()) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(1)));
}
if (firstFailing.isAfter(instant.minus(Duration.ofHours(1)))) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(10)));
}
return lastCompleted.isBefore(instant.minus(Duration.ofHours(2)));
} | class DeploymentTrigger {
/*
* Instance orchestration TODO jonmv.
* Store new production application packages under non-instance path
* Read production packages from non-instance path, with fallback
* Deprecate and redirect some instance qualified paths in application/v4
* Orchestrate deployment across instances.
*/
public static final Duration maxPause = Duration.ofDays(3);
private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName());
private final Controller controller;
private final Clock clock;
private final BuildService buildService;
private final JobController jobs;
public DeploymentTrigger(Controller controller, BuildService buildService, Clock clock) {
this.controller = Objects.requireNonNull(controller, "controller cannot be null");
this.clock = Objects.requireNonNull(clock, "clock cannot be null");
this.buildService = Objects.requireNonNull(buildService, "buildService cannot be null");
this.jobs = controller.jobController();
}
public DeploymentSteps steps(DeploymentInstanceSpec spec) {
return new DeploymentSteps(spec, controller::system);
}
public void notifyOfSubmission(TenantAndApplicationId id, ApplicationVersion version, long projectId) {
if (applications().getApplication(id).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring submission from project '" + projectId +
"': Unknown application '" + id + "'");
return;
}
applications().lockApplicationOrThrow(id, application -> {
if (acceptNewApplicationVersion(application.get())) {
application = application.withChange(application.get().change().with(version))
.withOutstandingChange(Change.empty());
if (application.get().internal())
for (Run run : jobs.active(id))
if ( ! run.id().type().environment().isManuallyDeployed())
jobs.abort(run.id());
}
else
application = application.withOutstandingChange(Change.of(version));
application = application.withProjectId(OptionalLong.of(projectId));
application = application.withNewSubmission(version);
applications().store(application.withChange(remainingChange(application.get())));
});
}
/**
* Records information when a job completes (successfully or not). This information is used when deciding what to
* trigger next.
*/
public void notifyOfCompletion(JobReport report) {
log.log(LogLevel.DEBUG, String.format("Notified of %s for %s of %s (%d)",
report.jobError().map(e -> e.toString() + " error")
.orElse("success"),
report.jobType(),
report.applicationId(),
report.projectId()));
if (applications().getInstance(report.applicationId()).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring completion of job of project '" + report.projectId() +
"': Unknown application '" + report.applicationId() + "'");
return;
}
applications().lockApplicationOrThrow(TenantAndApplicationId.from(report.applicationId()), application -> {
var status = application.get().require(report.applicationId().instance())
.deploymentJobs().statusOf(report.jobType());
var triggering = status.filter(job -> job.lastTriggered().isPresent()
&& job.lastCompleted()
.map(completion -> ! completion.at().isAfter(job.lastTriggered().get().at()))
.orElse(true))
.orElseThrow(() -> new IllegalStateException("Notified of completion of " + report.jobType().jobName() + " for " +
report.applicationId() + ", but that has not been triggered; last was " +
status.flatMap(job -> job.lastTriggered().map(run -> run.at().toString()))
.orElse("never")))
.lastTriggered().get();
application = application.with(report.applicationId().instance(),
instance -> instance.withJobCompletion(report.jobType(),
triggering.completion(report.buildNumber(), clock.instant()),
report.jobError()));
applications().store(application.withChange(remainingChange(application.get())));
});
}
/** Returns a map of jobs that are scheduled to be run, grouped by the job type */
public Map<JobType, ? extends List<? extends BuildJob>> jobsToRun() {
return computeReadyJobs().stream().collect(groupingBy(Job::jobType));
}
/**
* Finds and triggers jobs that can and should run but are currently not, and returns the number of triggered jobs.
*
* Only one job is triggered each run for test jobs, since their environments have limited capacity.
*/
public long triggerReadyJobs() {
return computeReadyJobs().stream()
.collect(partitioningBy(job -> job.jobType().isTest()))
.entrySet().stream()
.flatMap(entry -> (entry.getKey()
? entry.getValue().stream()
.sorted(comparing(Job::isRetry)
.thenComparing(Job::applicationUpgrade)
.reversed()
.thenComparing(Job::availableSince))
.collect(groupingBy(Job::jobType))
: entry.getValue().stream()
.collect(groupingBy(Job::applicationId)))
.values().stream()
.map(jobs -> (Supplier<Long>) jobs.stream()
.filter(this::trigger)
.limit(entry.getKey() ? 1 : Long.MAX_VALUE)::count))
.parallel().map(Supplier::get).reduce(0L, Long::sum);
}
/**
* Attempts to trigger the given job for the given application and returns the outcome.
*
* If the build service can not find the given job, or claims it is illegal to trigger it,
* the project id is removed from the application owning the job, to prevent further trigger attempts.
*/
public boolean trigger(Job job) {
log.log(LogLevel.DEBUG, String.format("Triggering %s: %s", job, job.triggering));
try {
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application -> {
if (application.get().internal())
jobs.start(job.applicationId(), job.jobType, new Versions(job.triggering.platform(),
job.triggering.application(),
job.triggering.sourcePlatform(),
job.triggering.sourceApplication()));
else
buildService.trigger(job);
applications().store(application.with(job.applicationId().instance(),
instance -> instance.withJobTriggering(job.jobType, job.triggering)));
});
return true;
}
catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception triggering " + job + ": " + e);
if (e instanceof NoSuchElementException || e instanceof IllegalArgumentException)
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application ->
applications().store(application.withProjectId(OptionalLong.empty())));
return false;
}
}
/** Force triggering of a job for given instance. */
public List<JobType> forceTrigger(ApplicationId applicationId, JobType jobType, String user) {
Application application = applications().requireApplication(TenantAndApplicationId.from(applicationId));
Instance instance = application.require(applicationId.instance());
Versions versions = Versions.from(application.change(), application, deploymentFor(instance, jobType),
controller.systemVersion());
String reason = "Job triggered manually by " + user;
var jobStatus = jobs.jobStatus(applicationId, application.deploymentSpec());
return (jobType.isProduction() && ! isTested(jobStatus, versions)
? testJobs(application.deploymentSpec(), application.change(), instance, jobStatus, versions, reason, clock.instant(), __ -> true).stream()
: Stream.of(deploymentJob(instance, versions, application.change(), jobType, jobStatus.get(jobType), reason, clock.instant())))
.peek(this::trigger)
.map(Job::jobType).collect(toList());
}
/** Prevents jobs of the given type from starting, until the given time. */
public void pauseJob(ApplicationId id, JobType jobType, Instant until) {
if (until.isAfter(clock.instant().plus(maxPause)))
throw new IllegalArgumentException("Pause only allowed for up to " + maxPause);
applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application ->
applications().store(application.with(id.instance(),
instance -> instance.withJobPause(jobType, OptionalLong.of(until.toEpochMilli())))));
}
/** Triggers a change of this application, unless it already has a change. */
public void triggerChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if ( ! application.get().change().hasTargets())
forceChange(applicationId, change);
});
}
/** Overrides the given application's platform and application changes with any contained in the given change. */
public void forceChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if (change.application().isPresent())
application = application.withOutstandingChange(Change.empty());
applications().store(application.withChange(change.onTopOf(application.get().change())));
});
}
/** Cancels the indicated part of the given application's change. */
public void cancelChange(TenantAndApplicationId applicationId, ChangesToCancel cancellation) {
applications().lockApplicationOrThrow(applicationId, application -> {
Change change;
switch (cancellation) {
case ALL: change = Change.empty(); break;
case VERSIONS: change = Change.empty().withPin(); break;
case PLATFORM: change = application.get().change().withoutPlatform(); break;
case APPLICATION: change = application.get().change().withoutApplication(); break;
case PIN: change = application.get().change().withoutPin(); break;
default: throw new IllegalArgumentException("Unknown cancellation choice '" + cancellation + "'!");
}
applications().store(application.withChange(change));
});
}
public enum ChangesToCancel { ALL, PLATFORM, APPLICATION, VERSIONS, PIN }
private ApplicationController applications() {
return controller.applications();
}
private Optional<Run> successOn(JobStatus status, Versions versions) {
return status.lastSuccess().filter(run -> versions.targetsMatch(run.versions()));
}
private Optional<Deployment> deploymentFor(Instance instance, JobType jobType) {
return Optional.ofNullable(instance.deployments().get(jobType.zone(controller.system())));
}
private static <T extends Comparable<T>> Optional<T> max(Optional<T> o1, Optional<T> o2) {
return o1.isEmpty() ? o2 : o2.isEmpty() ? o1 : o1.get().compareTo(o2.get()) >= 0 ? o1 : o2;
}
/** Returns the set of all jobs which have changes to propagate from the upstream steps. */
private List<Job> computeReadyJobs() {
return ApplicationList.from(applications().asList())
.withProjectId()
.withChanges()
.withDeploymentSpec()
.idList().stream()
.map(this::computeReadyJobs)
.flatMap(Collection::stream)
.collect(toList());
}
/**
* Finds the next step to trigger for the given application, if any, and returns these as a list.
*/
private List<Job> computeReadyJobs(TenantAndApplicationId id) {
List<Job> jobs = new ArrayList<>();
applications().getApplication(id).ifPresent(application -> {
Collection<Instance> instances = application.deploymentSpec().instances().stream()
.flatMap(instance -> application.get(instance.name()).stream())
.collect(Collectors.toUnmodifiableList());
for (Instance instance : instances) {
var jobStatus = this.jobs.jobStatus(instance.id(), application.deploymentSpec());
Change change = application.change();
Optional<Instant> completedAt = max(Optional.ofNullable(jobStatus.get(systemTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())),
Optional.ofNullable(jobStatus.get(stagingTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())));
String reason = "New change available";
List<Job> testJobs = null;
DeploymentSteps steps = steps(application.deploymentSpec().requireInstance(instance.name()));
if (change.hasTargets()) {
for (Step step : steps.production()) {
List<JobType> stepJobs = steps.toJobs(step);
List<JobType> remainingJobs = stepJobs.stream().filter(job -> ! isComplete(change, change, instance, job, jobStatus.get(job))).collect(toList());
if ( ! remainingJobs.isEmpty()) {
for (JobType job : remainingJobs) {
Versions versions = Versions.from(change, application, deploymentFor(instance, job),
controller.systemVersion());
if (isTested(jobStatus, versions)) {
if (completedAt.isPresent() && canTrigger(job, jobStatus, versions, instance, application.deploymentSpec(), stepJobs)) {
jobs.add(deploymentJob(instance, versions, change, job, jobStatus.get(job), reason, completedAt.get()));
}
if ( ! alreadyTriggered(jobStatus, versions) && testJobs == null) {
testJobs = emptyList();
}
}
else if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(),
change, instance, jobStatus, versions,
String.format("Testing deployment for %s (%s)",
job.jobName(), versions.toString()),
completedAt.orElseGet(clock::instant));
}
}
completedAt = Optional.empty();
}
else {
if (stepJobs.isEmpty()) {
completedAt = completedAt.map(at -> at.plus(step.delay())).filter(at -> ! at.isAfter(clock.instant()));
reason += " after a delay of " + step.delay();
}
else {
completedAt = stepJobs.stream().map(job -> jobStatus.get(job).lastCompleted().get().end().get()).max(naturalOrder());
reason = "Available change in " + stepJobs.stream().map(JobType::jobName).collect(joining(", "));
}
}
}
}
if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(), change, instance, jobStatus,
Versions.from(application.outstandingChange().onTopOf(change),
application,
steps.sortedDeployments(instance.productionDeployments().values()).stream().findFirst(),
controller.systemVersion()),
"Testing last changes outside prod", clock.instant());
}
jobs.addAll(testJobs);
}
});
return Collections.unmodifiableList(jobs);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec, List<JobType> parallelJobs) {
if (status.get(job).isRunning()) return false;
if (parallelJobs != null && ! parallelJobs.containsAll(runningProductionJobs(status))) return false;
if (job.isProduction() && isSuspendedInAnotherZone(instance, job.zone(controller.system()))) return false;
return triggerAt(clock.instant(), job, status.get(job), versions, instance, deploymentSpec);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
return canTrigger(job, status, versions, instance, deploymentSpec, null);
}
private boolean isSuspendedInAnotherZone(Instance instance, ZoneId zone) {
for (Deployment deployment : instance.productionDeployments().values()) {
if ( ! deployment.zone().equals(zone)
&& controller.applications().isSuspended(new DeploymentId(instance.id(), deployment.zone())))
return true;
}
return false;
}
/** Returns whether the given job can trigger at the given instant */
private List<JobType> runningProductionJobs(Map<JobType, JobStatus> status) {
return status.values().parallelStream()
.filter(job -> job.isRunning())
.map(job -> job.job().type())
.filter(JobType::isProduction)
.collect(toList());
}
/**
* Returns whether the given change is complete for the given application for the given job.
*
* Any job is complete if the given change is already successful on that job.
* A production job is also considered complete if its current change is strictly dominated by what
* is already deployed in its zone, i.e., no parts of the change are upgrades, and the full current
* change for the application downgrades the deployment, which is an acknowledgement that the deployed
* version is broken somehow, such that the job may be locked in failure until a new version is released.
*
* Additionally, if the application is pinned to a Vespa version, and the given change has a (this) platform,
* the deployment for the job must be on the pinned version.
*/
public boolean isComplete(Change change, Change fullChange, Instance instance, JobType jobType,
JobStatus status) {
Optional<Deployment> existingDeployment = deploymentFor(instance, jobType);
if ( change.isPinned()
&& change.platform().isPresent()
&& ! existingDeployment.map(Deployment::version).equals(change.platform()))
return false;
return status.lastSuccess()
.map(run -> change.platform().map(run.versions().targetPlatform()::equals).orElse(true)
&& change.application().map(run.versions().targetApplication()::equals).orElse(true))
.orElse(false)
|| jobType.isProduction()
&& existingDeployment.map(deployment -> ! isUpgrade(change, deployment) && isDowngrade(fullChange, deployment))
.orElse(false);
}
private static boolean isUpgrade(Change change, Deployment deployment) {
return change.upgrades(deployment.version()) || change.upgrades(deployment.applicationVersion());
}
private static boolean isDowngrade(Change change, Deployment deployment) {
return change.downgrades(deployment.version()) || change.downgrades(deployment.applicationVersion());
}
private boolean isTested(Map<JobType, JobStatus> status, Versions versions) {
return testedIn(systemTest, status.get(systemTest), versions)
&& testedIn(stagingTest, status.get(stagingTest), versions)
|| alreadyTriggered(status, versions);
}
public boolean testedIn(JobType testType, JobStatus status, Versions versions) {
if (testType == systemTest)
return successOn(status, versions).isPresent();
if (testType == stagingTest)
return successOn(status, versions).map(Run::versions).filter(versions::sourcesMatchIfPresent).isPresent();
throw new IllegalArgumentException(testType + " is not a test job!");
}
public boolean alreadyTriggered(Map<JobType, JobStatus> status, Versions versions) {
return status.values().stream()
.filter(job -> job.job().type().isProduction())
.anyMatch(job -> job.lastTriggered()
.map(Run::versions)
.filter(versions::targetsMatch)
.filter(versions::sourcesMatchIfPresent)
.isPresent());
}
private boolean acceptNewApplicationVersion(Application application) {
if ( ! application.deploymentSpec().instances().stream()
.allMatch(instance -> instance.canChangeRevisionAt(clock.instant()))) return false;
if (application.change().application().isPresent()) return true;
for (Instance instance : application.instances().values())
if (instance.deploymentJobs().hasFailures()) return true;
return application.change().platform().isEmpty();
}
private Change remainingChange(Application application) {
Change change = application.change();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutApplication(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutPlatform();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutPlatform(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutApplication();
return change;
}
/**
* Returns the list of test jobs that should run now, and that need to succeed on the given versions for it to be considered tested.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince) {
return testJobs(deploymentSpec, change, instance, status, versions, reason, availableSince,
jobType -> canTrigger(jobType, status, versions, instance, deploymentSpec));
}
/**
* Returns the list of test jobs that need to succeed on the given versions for it to be considered tested, filtered by the given condition.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince, Predicate<JobType> condition) {
List<Job> jobs = new ArrayList<>();
for (JobType jobType : new DeploymentSteps(deploymentSpec.requireInstance(instance.name()), controller::system).testJobs()) {
Optional<Run> completion = successOn(status.get(jobType), versions)
.filter(run -> versions.sourcesMatchIfPresent(run.versions()) || jobType == systemTest);
if (completion.isEmpty() && condition.test(jobType))
jobs.add(deploymentJob(instance, versions, change, jobType, status.get(jobType), reason, availableSince));
}
return jobs;
}
private Job deploymentJob(Instance instance, Versions versions, Change change, JobType jobType, JobStatus jobStatus, String reason, Instant availableSince) {
if (jobStatus.isOutOfCapacity()) reason += "; retrying on out of capacity";
var triggering = JobRun.triggering(versions.targetPlatform(), versions.targetApplication(),
versions.sourcePlatform(), versions.sourceApplication(),
reason, clock.instant());
return new Job(instance, triggering, jobType, availableSince, jobStatus.isOutOfCapacity(), change.application().isPresent());
}
private static class Job extends BuildJob {
private final JobType jobType;
private final JobRun triggering;
private final Instant availableSince;
private final boolean isRetry;
private final boolean isApplicationUpgrade;
private Job(Instance instance, JobRun triggering, JobType jobType, Instant availableSince,
boolean isRetry, boolean isApplicationUpgrade) {
super(instance.id(), 0L, jobType.jobName());
this.jobType = jobType;
this.triggering = triggering;
this.availableSince = availableSince;
this.isRetry = isRetry;
this.isApplicationUpgrade = isApplicationUpgrade;
}
JobType jobType() { return jobType; }
Instant availableSince() { return availableSince; }
boolean isRetry() { return isRetry; }
boolean applicationUpgrade() { return isApplicationUpgrade; }
}
} | class DeploymentTrigger {
public static final Duration maxPause = Duration.ofDays(3);
private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName());
private final Controller controller;
private final Clock clock;
private final JobController jobs;
public DeploymentTrigger(Controller controller, Clock clock) {
this.controller = Objects.requireNonNull(controller, "controller cannot be null");
this.clock = Objects.requireNonNull(clock, "clock cannot be null");
this.jobs = controller.jobController();
}
public DeploymentSteps steps(DeploymentInstanceSpec spec) {
return new DeploymentSteps(spec, controller::system);
}
public void notifyOfSubmission(TenantAndApplicationId id, ApplicationVersion version, long projectId) {
if (applications().getApplication(id).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring submission from project '" + projectId +
"': Unknown application '" + id + "'");
return;
}
applications().lockApplicationOrThrow(id, application -> {
if (acceptNewApplicationVersion(application.get())) {
application = application.withChange(application.get().change().with(version))
.withOutstandingChange(Change.empty());
for (Run run : jobs.active(id))
if ( ! run.id().type().environment().isManuallyDeployed())
jobs.abort(run.id());
}
else
application = application.withOutstandingChange(Change.of(version));
application = application.withProjectId(OptionalLong.of(projectId));
application = application.withNewSubmission(version);
applications().store(application.withChange(remainingChange(application.get())));
});
}
/**
* Records information when a job completes (successfully or not). This information is used when deciding what to
* trigger next.
*/
public void notifyOfCompletion(JobReport report) {
log.log(LogLevel.DEBUG, String.format("Notified of %s for %s of %s (%d)",
report.jobError().map(e -> e.toString() + " error")
.orElse("success"),
report.jobType(),
report.applicationId(),
report.projectId()));
if (applications().getInstance(report.applicationId()).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring completion of job of project '" + report.projectId() +
"': Unknown application '" + report.applicationId() + "'");
return;
}
applications().lockApplicationOrThrow(TenantAndApplicationId.from(report.applicationId()), application -> {
var status = application.get().require(report.applicationId().instance())
.deploymentJobs().statusOf(report.jobType());
var triggering = status.filter(job -> job.lastTriggered().isPresent()
&& job.lastCompleted()
.map(completion -> ! completion.at().isAfter(job.lastTriggered().get().at()))
.orElse(true))
.orElseThrow(() -> new IllegalStateException("Notified of completion of " + report.jobType().jobName() + " for " +
report.applicationId() + ", but that has not been triggered; last was " +
status.flatMap(job -> job.lastTriggered().map(run -> run.at().toString()))
.orElse("never")))
.lastTriggered().get();
application = application.with(report.applicationId().instance(),
instance -> instance.withJobCompletion(report.jobType(),
triggering.completion(report.buildNumber(), clock.instant()),
report.jobError()));
applications().store(application.withChange(remainingChange(application.get())));
});
}
/**
* Finds and triggers jobs that can and should run but are currently not, and returns the number of triggered jobs.
*
* Only one job is triggered each run for test jobs, since their environments have limited capacity.
*/
public long triggerReadyJobs() {
return computeReadyJobs().stream()
.collect(partitioningBy(job -> job.jobType().isTest()))
.entrySet().stream()
.flatMap(entry -> (entry.getKey()
? entry.getValue().stream()
.sorted(comparing(Job::isRetry)
.thenComparing(Job::applicationUpgrade)
.reversed()
.thenComparing(Job::availableSince))
.collect(groupingBy(Job::jobType))
: entry.getValue().stream()
.collect(groupingBy(Job::applicationId)))
.values().stream()
.map(jobs -> (Supplier<Long>) jobs.stream()
.filter(this::trigger)
.limit(entry.getKey() ? 1 : Long.MAX_VALUE)::count))
.parallel().map(Supplier::get).reduce(0L, Long::sum);
}
/**
* Attempts to trigger the given job for the given application and returns the outcome.
*
* If the build service can not find the given job, or claims it is illegal to trigger it,
* the project id is removed from the application owning the job, to prevent further trigger attempts.
*/
public boolean trigger(Job job) {
log.log(LogLevel.DEBUG, String.format("Triggering %s: %s", job, job.triggering));
try {
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application -> {
jobs.start(job.applicationId(), job.jobType, new Versions(job.triggering.platform(),
job.triggering.application(),
job.triggering.sourcePlatform(),
job.triggering.sourceApplication()));
applications().store(application.with(job.applicationId().instance(),
instance -> instance.withJobTriggering(job.jobType, job.triggering)));
});
return true;
}
catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception triggering " + job + ": " + e);
if (e instanceof NoSuchElementException || e instanceof IllegalArgumentException)
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application ->
applications().store(application.withProjectId(OptionalLong.empty())));
return false;
}
}
/** Force triggering of a job for given instance. */
public List<JobType> forceTrigger(ApplicationId applicationId, JobType jobType, String user) {
Application application = applications().requireApplication(TenantAndApplicationId.from(applicationId));
Instance instance = application.require(applicationId.instance());
Versions versions = Versions.from(application.change(), application, deploymentFor(instance, jobType),
controller.systemVersion());
String reason = "Job triggered manually by " + user;
var jobStatus = jobs.deploymentStatus(application).instanceJobs(instance.name());
return (jobType.isProduction() && ! isTested(jobStatus, versions)
? testJobs(application.deploymentSpec(), application.change(), instance, jobStatus, versions, reason, clock.instant(), __ -> true).stream()
: Stream.of(deploymentJob(instance, versions, application.change(), jobType, jobStatus.get(jobType), reason, clock.instant())))
.peek(this::trigger)
.map(Job::jobType).collect(toList());
}
/** Prevents jobs of the given type from starting, until the given time. */
public void pauseJob(ApplicationId id, JobType jobType, Instant until) {
if (until.isAfter(clock.instant().plus(maxPause)))
throw new IllegalArgumentException("Pause only allowed for up to " + maxPause);
applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application ->
applications().store(application.with(id.instance(),
instance -> instance.withJobPause(jobType, OptionalLong.of(until.toEpochMilli())))));
}
/** Triggers a change of this application, unless it already has a change. */
public void triggerChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if ( ! application.get().change().hasTargets())
forceChange(applicationId, change);
});
}
/** Overrides the given application's platform and application changes with any contained in the given change. */
public void forceChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if (change.application().isPresent())
application = application.withOutstandingChange(Change.empty());
applications().store(application.withChange(change.onTopOf(application.get().change())));
});
}
/** Cancels the indicated part of the given application's change. */
public void cancelChange(TenantAndApplicationId applicationId, ChangesToCancel cancellation) {
applications().lockApplicationOrThrow(applicationId, application -> {
Change change;
switch (cancellation) {
case ALL: change = Change.empty(); break;
case VERSIONS: change = Change.empty().withPin(); break;
case PLATFORM: change = application.get().change().withoutPlatform(); break;
case APPLICATION: change = application.get().change().withoutApplication(); break;
case PIN: change = application.get().change().withoutPin(); break;
default: throw new IllegalArgumentException("Unknown cancellation choice '" + cancellation + "'!");
}
applications().store(application.withChange(change));
});
}
public enum ChangesToCancel { ALL, PLATFORM, APPLICATION, VERSIONS, PIN }
private ApplicationController applications() {
return controller.applications();
}
private Optional<Run> successOn(JobStatus status, Versions versions) {
return status.lastSuccess().filter(run -> versions.targetsMatch(run.versions()));
}
private Optional<Deployment> deploymentFor(Instance instance, JobType jobType) {
return Optional.ofNullable(instance.deployments().get(jobType.zone(controller.system())));
}
private static <T extends Comparable<T>> Optional<T> max(Optional<T> o1, Optional<T> o2) {
return o1.isEmpty() ? o2 : o2.isEmpty() ? o1 : o1.get().compareTo(o2.get()) >= 0 ? o1 : o2;
}
/** Returns the set of all jobs which have changes to propagate from the upstream steps. */
private List<Job> computeReadyJobs() {
return ApplicationList.from(applications().asList())
.withProjectId()
.withChanges()
.withDeploymentSpec()
.idList().stream()
.map(this::computeReadyJobs)
.flatMap(Collection::stream)
.collect(toList());
}
/**
* Finds the next step to trigger for the given application, if any, and returns these as a list.
*/
private List<Job> computeReadyJobs(TenantAndApplicationId id) {
List<Job> jobs = new ArrayList<>();
applications().getApplication(id).ifPresent(application -> {
Collection<Instance> instances = application.deploymentSpec().instances().stream()
.flatMap(instance -> application.get(instance.name()).stream())
.collect(Collectors.toUnmodifiableList());
DeploymentStatus deploymentStatus = this.jobs.deploymentStatus(application);
for (Instance instance : instances) {
var jobStatus = deploymentStatus.instanceJobs(instance.name());
Change change = application.change();
Optional<Instant> completedAt = max(Optional.ofNullable(jobStatus.get(systemTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())),
Optional.ofNullable(jobStatus.get(stagingTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())));
String reason = "New change available";
List<Job> testJobs = null;
DeploymentSteps steps = steps(application.deploymentSpec().requireInstance(instance.name()));
if (change.hasTargets()) {
for (Step step : steps.production()) {
List<JobType> stepJobs = steps.toJobs(step);
List<JobType> remainingJobs = stepJobs.stream().filter(job -> ! isComplete(change, change, instance, job, jobStatus.get(job))).collect(toList());
if ( ! remainingJobs.isEmpty()) {
for (JobType job : remainingJobs) {
Versions versions = Versions.from(change, application, deploymentFor(instance, job),
controller.systemVersion());
if (isTested(jobStatus, versions)) {
if (completedAt.isPresent() && canTrigger(job, jobStatus, versions, instance, application.deploymentSpec(), stepJobs)) {
jobs.add(deploymentJob(instance, versions, change, job, jobStatus.get(job), reason, completedAt.get()));
}
if ( ! alreadyTriggered(jobStatus, versions) && testJobs == null) {
testJobs = emptyList();
}
}
else if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(),
change, instance, jobStatus, versions,
String.format("Testing deployment for %s (%s)",
job.jobName(), versions.toString()),
completedAt.orElseGet(clock::instant));
}
}
completedAt = Optional.empty();
}
else {
if (stepJobs.isEmpty()) {
completedAt = completedAt.map(at -> at.plus(step.delay())).filter(at -> ! at.isAfter(clock.instant()));
reason += " after a delay of " + step.delay();
}
else {
completedAt = stepJobs.stream().map(job -> jobStatus.get(job).lastCompleted().get().end().get()).max(naturalOrder());
reason = "Available change in " + stepJobs.stream().map(JobType::jobName).collect(joining(", "));
}
}
}
}
if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(), change, instance, jobStatus,
Versions.from(application.outstandingChange().onTopOf(change),
application,
steps.sortedDeployments(instance.productionDeployments().values()).stream().findFirst(),
controller.systemVersion()),
"Testing last changes outside prod", clock.instant());
}
jobs.addAll(testJobs);
}
});
return Collections.unmodifiableList(jobs);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec, List<JobType> parallelJobs) {
if (status.get(job).isRunning()) return false;
if (parallelJobs != null && ! parallelJobs.containsAll(runningProductionJobs(status))) return false;
if (job.isProduction() && isSuspendedInAnotherZone(instance, job.zone(controller.system()))) return false;
return triggerAt(clock.instant(), job, status.get(job), versions, instance, deploymentSpec);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
return canTrigger(job, status, versions, instance, deploymentSpec, null);
}
private boolean isSuspendedInAnotherZone(Instance instance, ZoneId zone) {
for (Deployment deployment : instance.productionDeployments().values()) {
if ( ! deployment.zone().equals(zone)
&& controller.applications().isSuspended(new DeploymentId(instance.id(), deployment.zone())))
return true;
}
return false;
}
/** Returns whether the given job can trigger at the given instant */
private List<JobType> runningProductionJobs(Map<JobType, JobStatus> status) {
return status.values().parallelStream()
.filter(job -> job.isRunning())
.map(job -> job.id().type())
.filter(JobType::isProduction)
.collect(toList());
}
/**
* Returns whether the given change is complete for the given application for the given job.
*
* Any job is complete if the given change is already successful on that job.
* A production job is also considered complete if its current change is strictly dominated by what
* is already deployed in its zone, i.e., no parts of the change are upgrades, and the full current
* change for the application downgrades the deployment, which is an acknowledgement that the deployed
* version is broken somehow, such that the job may be locked in failure until a new version is released.
*
* Additionally, if the application is pinned to a Vespa version, and the given change has a (this) platform,
* the deployment for the job must be on the pinned version.
*/
public boolean isComplete(Change change, Change fullChange, Instance instance, JobType jobType,
JobStatus status) {
Optional<Deployment> existingDeployment = deploymentFor(instance, jobType);
if ( change.isPinned()
&& change.platform().isPresent()
&& ! existingDeployment.map(Deployment::version).equals(change.platform()))
return false;
return status.lastSuccess()
.map(run -> change.platform().map(run.versions().targetPlatform()::equals).orElse(true)
&& change.application().map(run.versions().targetApplication()::equals).orElse(true))
.orElse(false)
|| jobType.isProduction()
&& existingDeployment.map(deployment -> ! isUpgrade(change, deployment) && isDowngrade(fullChange, deployment))
.orElse(false);
}
private static boolean isUpgrade(Change change, Deployment deployment) {
return change.upgrades(deployment.version()) || change.upgrades(deployment.applicationVersion());
}
private static boolean isDowngrade(Change change, Deployment deployment) {
return change.downgrades(deployment.version()) || change.downgrades(deployment.applicationVersion());
}
private boolean isTested(Map<JobType, JobStatus> status, Versions versions) {
return testedIn(systemTest, status.get(systemTest), versions)
&& testedIn(stagingTest, status.get(stagingTest), versions)
|| alreadyTriggered(status, versions);
}
public boolean testedIn(JobType testType, JobStatus status, Versions versions) {
if (testType == systemTest)
return successOn(status, versions).isPresent();
if (testType == stagingTest)
return successOn(status, versions).map(Run::versions).filter(versions::sourcesMatchIfPresent).isPresent();
throw new IllegalArgumentException(testType + " is not a test job!");
}
public boolean alreadyTriggered(Map<JobType, JobStatus> status, Versions versions) {
return status.values().stream()
.filter(job -> job.id().type().isProduction())
.anyMatch(job -> job.lastTriggered()
.map(Run::versions)
.filter(versions::targetsMatch)
.filter(versions::sourcesMatchIfPresent)
.isPresent());
}
private boolean acceptNewApplicationVersion(Application application) {
if ( ! application.deploymentSpec().instances().stream()
.allMatch(instance -> instance.canChangeRevisionAt(clock.instant()))) return false;
if (application.change().application().isPresent()) return true;
for (Instance instance : application.instances().values())
if (instance.deploymentJobs().hasFailures()) return true;
return application.change().platform().isEmpty();
}
private Change remainingChange(Application application) {
Change change = application.change();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutApplication(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutPlatform();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutPlatform(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutApplication();
return change;
}
/**
* Returns the list of test jobs that should run now, and that need to succeed on the given versions for it to be considered tested.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince) {
return testJobs(deploymentSpec, change, instance, status, versions, reason, availableSince,
jobType -> canTrigger(jobType, status, versions, instance, deploymentSpec));
}
/**
* Returns the list of test jobs that need to succeed on the given versions for it to be considered tested, filtered by the given condition.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince, Predicate<JobType> condition) {
List<Job> jobs = new ArrayList<>();
for (JobType jobType : new DeploymentSteps(deploymentSpec.requireInstance(instance.name()), controller::system).testJobs()) {
Optional<Run> completion = successOn(status.get(jobType), versions)
.filter(run -> versions.sourcesMatchIfPresent(run.versions()) || jobType == systemTest);
if (completion.isEmpty() && condition.test(jobType))
jobs.add(deploymentJob(instance, versions, change, jobType, status.get(jobType), reason, availableSince));
}
return jobs;
}
private Job deploymentJob(Instance instance, Versions versions, Change change, JobType jobType, JobStatus jobStatus, String reason, Instant availableSince) {
if (jobStatus.isOutOfCapacity()) reason += "; retrying on out of capacity";
var triggering = JobRun.triggering(versions.targetPlatform(), versions.targetApplication(),
versions.sourcePlatform(), versions.sourceApplication(),
reason, clock.instant());
return new Job(instance, triggering, jobType, availableSince, jobStatus.isOutOfCapacity(), change.application().isPresent());
}
private static class Job {
private final ApplicationId instanceId;
private final JobType jobType;
private final JobRun triggering;
private final Instant availableSince;
private final boolean isRetry;
private final boolean isApplicationUpgrade;
private Job(Instance instance, JobRun triggering, JobType jobType, Instant availableSince,
boolean isRetry, boolean isApplicationUpgrade) {
this.instanceId = instance.id();
this.jobType = jobType;
this.triggering = triggering;
this.availableSince = availableSince;
this.isRetry = isRetry;
this.isApplicationUpgrade = isApplicationUpgrade;
}
ApplicationId applicationId() { return instanceId; }
JobType jobType() { return jobType; }
Instant availableSince() { return availableSince; }
boolean isRetry() { return isRetry; }
boolean applicationUpgrade() { return isApplicationUpgrade; }
}
} |
That is, it would be 6 only the first time an application fully deployed, and 15 on every following rollout. | public void name_service_queue_size_metric() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("default")
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext()
.deferDnsUpdates();
reporter.maintain();
assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals("Deployment queues name services requests", 15, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
context.flushDnsUpdates();
reporter.maintain();
assertEquals("Queue consumed", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
} | assertEquals("Deployment queues name services requests", 15, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue()); | public void name_service_queue_size_metric() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.globalServiceId("default")
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext()
.deferDnsUpdates();
reporter.maintain();
assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals("Deployment queues name services requests", 15, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
context.flushDnsUpdates();
reporter.maintain();
assertEquals("Queue consumed", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
} | class MetricsReporterTest {
private final MetricsMock metrics = new MetricsMock();
@Test
public void deployment_fail_ratio() {
var tester = new InternalDeploymentTester();
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));
var context1 = tester.newDeploymentContext("app1", "tenant1", "default");
var context2 = tester.newDeploymentContext("app2", "tenant1", "default");
var context3 = tester.newDeploymentContext("app3", "tenant1", "default");
var context4 = tester.newDeploymentContext("app4", "tenant1", "default");
context1.submit(applicationPackage).deploy();
context2.submit(applicationPackage).deploy();
context3.submit(applicationPackage).deploy();
context4.submit(applicationPackage).deploy();
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
context1.submit(applicationPackage)
.triggerJobs()
.failDeployment(systemTest);
metricsReporter.maintain();
assertEquals(25.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
}
@Test
public void deployment_average_duration() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext()
.submit(applicationPackage)
.deploy();
reporter.maintain();
assertEquals(Duration.ZERO, getAverageDeploymentDuration(context.instanceId()));
context.submit(applicationPackage);
tester.clock().advance(Duration.ofHours(1));
context.runJob(systemTest);
tester.clock().advance(Duration.ofMinutes(30));
context.runJob(stagingTest);
tester.triggerJobs();
tester.clock().advance(Duration.ofMinutes(90));
context.runJob(productionUsWest1);
reporter.maintain();
assertEquals(Duration.ofMinutes(80), getAverageDeploymentDuration(context.instanceId()));
context.submit(applicationPackage)
.triggerJobs();
tester.clock().advance(Duration.ofHours(12));
reporter.maintain();
assertEquals(Duration.ofHours(12)
.plus(Duration.ofHours(12))
.plus(Duration.ofMinutes(90))
.dividedBy(3),
getAverageDeploymentDuration(context.instanceId()));
}
@Test
public void deployments_failing_upgrade() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext();
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
context.submit(applicationPackage)
.triggerJobs()
.failDeployment(systemTest);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
context.deploy();
assertFalse("Change deployed", context.application().change().hasTargets());
Version version = Version.fromString("7.1");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
context.triggerJobs()
.failDeployment(systemTest)
.failDeployment(stagingTest);
reporter.maintain();
assertEquals(2, getDeploymentsFailingUpgrade(context.instanceId()));
context.runJob(systemTest)
.runJob(stagingTest)
.triggerJobs()
.failDeployment(productionUsWest1);
reporter.maintain();
assertEquals(1, getDeploymentsFailingUpgrade(context.instanceId()));
context.runJob(productionUsWest1);
assertFalse("Upgrade deployed", context.application().change().hasTargets());
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
}
@Test
public void deployment_warnings_metric() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext();
tester.configServer().generateWarnings(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")), 3);
tester.configServer().generateWarnings(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")), 4);
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals(4, getDeploymentWarnings(context.instanceId()));
}
@Test
public void build_time_reporting() {
var tester = new InternalDeploymentTester();
var applicationPackage = new ApplicationPackageBuilder().region("us-west-1").build();
var context = tester.deploymentContext()
.submit(applicationPackage)
.deploy();
assertEquals(1000, context.lastSubmission().get().buildTime().get().toEpochMilli());
MetricsReporter reporter = createReporter(tester.tester().controller());
reporter.maintain();
assertEquals(tester.clock().instant().getEpochSecond() - 1,
getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, context.instanceId()));
}
@Test
@Test
public void nodes_failing_system_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone1 = ZoneApiMock.fromId("prod.eu-west-1");
tester.zoneRegistry().setUpgradePolicy(UpgradePolicy.create().upgrade(zone1));
var systemUpgrader = new SystemUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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
public void nodes_failing_os_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone = ZoneApiMock.fromId("prod.eu-west-1");
var cloud = CloudName.defaultName();
tester.zoneRegistry().setOsUpgradePolicy(cloud, UpgradePolicy.create().upgrade(zone));
var osUpgrader = new OsUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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());
}
}
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 deployment_fail_ratio() {
var tester = new InternalDeploymentTester();
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));
var context1 = tester.newDeploymentContext("app1", "tenant1", "default");
var context2 = tester.newDeploymentContext("app2", "tenant1", "default");
var context3 = tester.newDeploymentContext("app3", "tenant1", "default");
var context4 = tester.newDeploymentContext("app4", "tenant1", "default");
context1.submit(applicationPackage).deploy();
context2.submit(applicationPackage).deploy();
context3.submit(applicationPackage).deploy();
context4.submit(applicationPackage).deploy();
metricsReporter.maintain();
assertEquals(0.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
context1.submit(applicationPackage)
.triggerJobs()
.failDeployment(systemTest);
metricsReporter.maintain();
assertEquals(25.0, metrics.getMetric(MetricsReporter.DEPLOYMENT_FAIL_METRIC));
}
@Test
public void deployment_average_duration() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext()
.submit(applicationPackage)
.deploy();
reporter.maintain();
assertEquals(Duration.ZERO, getAverageDeploymentDuration(context.instanceId()));
context.submit(applicationPackage);
tester.clock().advance(Duration.ofHours(1));
context.runJob(systemTest);
tester.clock().advance(Duration.ofMinutes(30));
context.runJob(stagingTest);
tester.triggerJobs();
tester.clock().advance(Duration.ofMinutes(90));
context.runJob(productionUsWest1);
reporter.maintain();
assertEquals(Duration.ofMinutes(80), getAverageDeploymentDuration(context.instanceId()));
context.submit(applicationPackage)
.triggerJobs();
tester.clock().advance(Duration.ofHours(12));
reporter.maintain();
assertEquals(Duration.ofHours(12)
.plus(Duration.ofHours(12))
.plus(Duration.ofMinutes(90))
.dividedBy(3),
getAverageDeploymentDuration(context.instanceId()));
}
@Test
public void deployments_failing_upgrade() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext();
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
context.submit(applicationPackage)
.triggerJobs()
.failDeployment(systemTest);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
context.deploy();
assertFalse("Change deployed", context.application().change().hasTargets());
Version version = Version.fromString("7.1");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
context.triggerJobs()
.failDeployment(systemTest)
.failDeployment(stagingTest);
reporter.maintain();
assertEquals(2, getDeploymentsFailingUpgrade(context.instanceId()));
context.runJob(systemTest)
.runJob(stagingTest)
.triggerJobs()
.failDeployment(productionUsWest1);
reporter.maintain();
assertEquals(1, getDeploymentsFailingUpgrade(context.instanceId()));
context.runJob(productionUsWest1);
assertFalse("Upgrade deployed", context.application().change().hasTargets());
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
}
@Test
public void deployment_warnings_metric() {
var tester = new InternalDeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.deploymentContext();
tester.configServer().generateWarnings(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")), 3);
tester.configServer().generateWarnings(context.deploymentIdIn(ZoneId.from("prod", "us-west-1")), 4);
context.submit(applicationPackage).deploy();
reporter.maintain();
assertEquals(4, getDeploymentWarnings(context.instanceId()));
}
@Test
public void build_time_reporting() {
var tester = new InternalDeploymentTester();
var applicationPackage = new ApplicationPackageBuilder().region("us-west-1").build();
var context = tester.deploymentContext()
.submit(applicationPackage)
.deploy();
assertEquals(1000, context.lastSubmission().get().buildTime().get().toEpochMilli());
MetricsReporter reporter = createReporter(tester.tester().controller());
reporter.maintain();
assertEquals(tester.clock().instant().getEpochSecond() - 1,
getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, context.instanceId()));
}
@Test
@Test
public void nodes_failing_system_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone1 = ZoneApiMock.fromId("prod.eu-west-1");
tester.zoneRegistry().setUpgradePolicy(UpgradePolicy.create().upgrade(zone1));
var systemUpgrader = new SystemUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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
public void nodes_failing_os_upgrade() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone = ZoneApiMock.fromId("prod.eu-west-1");
var cloud = CloudName.defaultName();
tester.zoneRegistry().setOsUpgradePolicy(cloud, UpgradePolicy.create().upgrade(zone));
var osUpgrader = new OsUpgrader(tester.controller(), Duration.ofDays(1),
new JobControl(tester.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());
}
}
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();
}
} |
bandwithGgps -> bandwidthGbps | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwithGgps", resources.bandwidthGbps());
object.setString("disk-speed", serializer.toString(resources.diskSpeed()));
} | object.setDouble("bandwithGgps", resources.bandwidthGbps()); | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} |
Stick to camel case for key names? | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwithGgps", resources.bandwidthGbps());
object.setString("disk-speed", serializer.toString(resources.diskSpeed()));
} | object.setString("disk-speed", serializer.toString(resources.diskSpeed())); | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} |
There's still a typo here.. :laughing: | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwithGbps", resources.bandwidthGbps());
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
} | object.setDouble("bandwithGbps", resources.bandwidthGbps()); | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} |
You want absolutely no typos in the entire word? High bar :-( | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwithGbps", resources.bandwidthGbps());
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
} | object.setDouble("bandwithGbps", resources.bandwidthGbps()); | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} |
Nit: If you access it through `controllerTester.serviceRegistry()` you can get rid of the cast. | 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);
((ManualClock) controllerTester.controller().clock()).advance(Duration.ofSeconds(1));
job.type(JobType.systemTest).submit();
var request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(asJson(job.type(JobType.systemTest).report()))
.userIdentity(HOSTED_VESPA_OPERATOR);
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);
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.systemTest);
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());
} | ((ManualClock) controllerTester.controller().clock()).advance(Duration.ofSeconds(1)); | 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);
((ManualClock) controllerTester.controller().clock()).advance(Duration.ofSeconds(1));
job.type(JobType.systemTest).submit();
var request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(asJson(job.type(JobType.systemTest).report()))
.userIdentity(HOSTED_VESPA_OPERATOR);
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);
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.systemTest);
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());
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private 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).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
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"));
tester.assertResponse(request("/application/v4/tenant/tenant1/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/2018-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"month\":\"2018-01\",\"items\":[]}");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("instance-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(DeploymentContext.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(DeploymentContext.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")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId 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).oktaIdentityToken(OKTA_IT),
"{\"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("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(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("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/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.serviceRegistry().configServerMock().nodeRepository().addFixedNodes(ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart?hostname=hostA", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-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.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "default"), ZoneId.from("prod", "us-central-1")),
List.of(new RoutingEndpoint("https:
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "my-user"), ZoneId.from("dev", "us-east-1")),
List.of(new RoutingEndpoint("https:
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
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/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackage, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\"message\":\"Deactivated tenant1.application1.otheruser in dev.us-east-1\"}");
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\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build43.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackage.zippedContent(), response.getBody());
},
200);
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")
.globalServiceId("foo")
.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/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build44.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=43", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build43.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackage.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService)),
"{\"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\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Only single-instance deployment specs are currently supported\"}", 400);
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(),
DeploymentContext.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' 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(),
DeploymentContext.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/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.my-user\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.otheruser\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
}
private void addIssues(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
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);
}
@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).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
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("instance-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), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
public void testTenantCostResponse() {
ApplicationId applicationId = createTenantAndApplication();
MockTenantCost mockTenantCost = (MockTenantCost) controllerTester.containerTester().serviceRegistry().tenantCost();
mockTenantCost.setMonthsWithMetering(
new TreeSet<>(Set.of(
YearMonth.of(2019, 10),
YearMonth.of(2019, 9)
))
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[\"2019-09\",\"2019-10\"]}");
CostInfo costInfo1 = new CostInfo(applicationId, ZoneId.from("prod", "us-south-1"),
new BigDecimal("7.0"),
new BigDecimal("600.0"),
new BigDecimal("1000.0"),
35, 23, 10);
CostInfo costInfo2 = new CostInfo(applicationId, ZoneId.from("prod", "us-north-1"),
new BigDecimal("2.0"),
new BigDecimal("3.0"),
new BigDecimal("4.0"),
10, 20, 30);
mockTenantCost.setCostInfoList(
List.of(costInfo1, costInfo2)
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost/2019-09", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("cost-report.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).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=42", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=foobar", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", 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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost/2018-01-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/not-a-valid-date", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not parse year-month 'not-a-valid-date'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void 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
@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/instance/default", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/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).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN,
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));
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)
.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 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 OktaIdentityToken oktaIdentityToken;
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 oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { 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 (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private 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).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
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"));
tester.assertResponse(request("/application/v4/tenant/tenant1/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/2018-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"month\":\"2018-01\",\"items\":[]}");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("instance-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(DeploymentContext.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(DeploymentContext.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")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId 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).oktaIdentityToken(OKTA_IT),
"{\"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("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(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("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/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.serviceRegistry().configServerMock().nodeRepository().addFixedNodes(ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart?hostname=hostA", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-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.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "default"), ZoneId.from("prod", "us-central-1")),
List.of(new RoutingEndpoint("https:
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "my-user"), ZoneId.from("dev", "us-east-1")),
List.of(new RoutingEndpoint("https:
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
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/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackage, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\"message\":\"Deactivated tenant1.application1.otheruser in dev.us-east-1\"}");
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\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build43.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackage.zippedContent(), response.getBody());
},
200);
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")
.globalServiceId("foo")
.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/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build44.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=43", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build43.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackage.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService)),
"{\"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\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Only single-instance deployment specs are currently supported\"}", 400);
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(),
DeploymentContext.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' 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(),
DeploymentContext.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/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.my-user\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.otheruser\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
}
private void addIssues(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
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);
}
@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).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
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("instance-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), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
public void testTenantCostResponse() {
ApplicationId applicationId = createTenantAndApplication();
MockTenantCost mockTenantCost = (MockTenantCost) controllerTester.containerTester().serviceRegistry().tenantCost();
mockTenantCost.setMonthsWithMetering(
new TreeSet<>(Set.of(
YearMonth.of(2019, 10),
YearMonth.of(2019, 9)
))
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[\"2019-09\",\"2019-10\"]}");
CostInfo costInfo1 = new CostInfo(applicationId, ZoneId.from("prod", "us-south-1"),
new BigDecimal("7.0"),
new BigDecimal("600.0"),
new BigDecimal("1000.0"),
35, 23, 10);
CostInfo costInfo2 = new CostInfo(applicationId, ZoneId.from("prod", "us-north-1"),
new BigDecimal("2.0"),
new BigDecimal("3.0"),
new BigDecimal("4.0"),
10, 20, 30);
mockTenantCost.setCostInfoList(
List.of(costInfo1, costInfo2)
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost/2019-09", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("cost-report.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).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=42", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=foobar", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", 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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost/2018-01-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/not-a-valid-date", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not parse year-month 'not-a-valid-date'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void 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
@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/instance/default", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/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).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN,
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));
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)
.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 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 OktaIdentityToken oktaIdentityToken;
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 oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { 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 (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} |
Hehe, yes. | 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);
((ManualClock) controllerTester.controller().clock()).advance(Duration.ofSeconds(1));
job.type(JobType.systemTest).submit();
var request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(asJson(job.type(JobType.systemTest).report()))
.userIdentity(HOSTED_VESPA_OPERATOR);
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);
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.systemTest);
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());
} | ((ManualClock) controllerTester.controller().clock()).advance(Duration.ofSeconds(1)); | 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);
((ManualClock) controllerTester.controller().clock()).advance(Duration.ofSeconds(1));
job.type(JobType.systemTest).submit();
var request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(asJson(job.type(JobType.systemTest).report()))
.userIdentity(HOSTED_VESPA_OPERATOR);
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);
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.systemTest);
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());
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private 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).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
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"));
tester.assertResponse(request("/application/v4/tenant/tenant1/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/2018-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"month\":\"2018-01\",\"items\":[]}");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("instance-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(DeploymentContext.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(DeploymentContext.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")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId 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).oktaIdentityToken(OKTA_IT),
"{\"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("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(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("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/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.serviceRegistry().configServerMock().nodeRepository().addFixedNodes(ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart?hostname=hostA", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-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.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "default"), ZoneId.from("prod", "us-central-1")),
List.of(new RoutingEndpoint("https:
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "my-user"), ZoneId.from("dev", "us-east-1")),
List.of(new RoutingEndpoint("https:
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
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/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackage, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\"message\":\"Deactivated tenant1.application1.otheruser in dev.us-east-1\"}");
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\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build43.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackage.zippedContent(), response.getBody());
},
200);
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")
.globalServiceId("foo")
.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/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build44.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=43", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build43.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackage.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService)),
"{\"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\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Only single-instance deployment specs are currently supported\"}", 400);
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(),
DeploymentContext.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' 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(),
DeploymentContext.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/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.my-user\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.otheruser\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
}
private void addIssues(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
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);
}
@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).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
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("instance-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), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
public void testTenantCostResponse() {
ApplicationId applicationId = createTenantAndApplication();
MockTenantCost mockTenantCost = (MockTenantCost) controllerTester.containerTester().serviceRegistry().tenantCost();
mockTenantCost.setMonthsWithMetering(
new TreeSet<>(Set.of(
YearMonth.of(2019, 10),
YearMonth.of(2019, 9)
))
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[\"2019-09\",\"2019-10\"]}");
CostInfo costInfo1 = new CostInfo(applicationId, ZoneId.from("prod", "us-south-1"),
new BigDecimal("7.0"),
new BigDecimal("600.0"),
new BigDecimal("1000.0"),
35, 23, 10);
CostInfo costInfo2 = new CostInfo(applicationId, ZoneId.from("prod", "us-north-1"),
new BigDecimal("2.0"),
new BigDecimal("3.0"),
new BigDecimal("4.0"),
10, 20, 30);
mockTenantCost.setCostInfoList(
List.of(costInfo1, costInfo2)
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost/2019-09", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("cost-report.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).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=42", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=foobar", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", 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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost/2018-01-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/not-a-valid-date", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not parse year-month 'not-a-valid-date'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void 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
@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/instance/default", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/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).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN,
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));
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)
.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 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 OktaIdentityToken oktaIdentityToken;
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 oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { 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 (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private 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).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
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"));
tester.assertResponse(request("/application/v4/tenant/tenant1/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/2018-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"month\":\"2018-01\",\"items\":[]}");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("instance-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(DeploymentContext.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(DeploymentContext.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")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId 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).oktaIdentityToken(OKTA_IT),
"{\"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("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(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("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/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.serviceRegistry().configServerMock().nodeRepository().addFixedNodes(ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart?hostname=hostA", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-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.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "default"), ZoneId.from("prod", "us-central-1")),
List.of(new RoutingEndpoint("https:
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "my-user"), ZoneId.from("dev", "us-east-1")),
List.of(new RoutingEndpoint("https:
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
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/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackage, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\"message\":\"Deactivated tenant1.application1.otheruser in dev.us-east-1\"}");
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\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build43.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackage.zippedContent(), response.getBody());
},
200);
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")
.globalServiceId("foo")
.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/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build44.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=43", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build43.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackage.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService)),
"{\"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\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Only single-instance deployment specs are currently supported\"}", 400);
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(),
DeploymentContext.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' 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(),
DeploymentContext.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/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.my-user\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.otheruser\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
}
private void addIssues(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
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);
}
@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).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
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("instance-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), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
public void testTenantCostResponse() {
ApplicationId applicationId = createTenantAndApplication();
MockTenantCost mockTenantCost = (MockTenantCost) controllerTester.containerTester().serviceRegistry().tenantCost();
mockTenantCost.setMonthsWithMetering(
new TreeSet<>(Set.of(
YearMonth.of(2019, 10),
YearMonth.of(2019, 9)
))
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[\"2019-09\",\"2019-10\"]}");
CostInfo costInfo1 = new CostInfo(applicationId, ZoneId.from("prod", "us-south-1"),
new BigDecimal("7.0"),
new BigDecimal("600.0"),
new BigDecimal("1000.0"),
35, 23, 10);
CostInfo costInfo2 = new CostInfo(applicationId, ZoneId.from("prod", "us-north-1"),
new BigDecimal("2.0"),
new BigDecimal("3.0"),
new BigDecimal("4.0"),
10, 20, 30);
mockTenantCost.setCostInfoList(
List.of(costInfo1, costInfo2)
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost/2019-09", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("cost-report.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).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=42", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=foobar", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", 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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost/2018-01-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/not-a-valid-date", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not parse year-month 'not-a-valid-date'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void 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
@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/instance/default", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/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).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN,
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));
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)
.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 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 OktaIdentityToken oktaIdentityToken;
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 oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { 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 (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} |
This should be `<=` | public String makeSnippet(String text, int sizeHint) {
if (text.length() < sizeHint) return text;
int maxSuffixLength = Math.max(0, (sizeHint - ASSUMED_OMIT_TEXT_LENGTH) / 2);
int maxPrefixLength = Math.max(0, sizeHint - ASSUMED_OMIT_TEXT_LENGTH - maxSuffixLength);
String snippet =
text.substring(0, maxPrefixLength) +
omitText(text.length() - maxPrefixLength - maxSuffixLength) +
text.substring(text.length() - maxSuffixLength);
if (text.length() <= 1.05 * snippet.length() + 5) return text;
return snippet;
} | if (text.length() < sizeHint) return text; | public String makeSnippet(String text, int sizeHint) {
if (text.length() <= Math.max(sizeHint, ASSUMED_OMIT_TEXT_LENGTH)) return text;
int maxSuffixLength = Math.max(0, (sizeHint - ASSUMED_OMIT_TEXT_LENGTH) / 2);
int maxPrefixLength = Math.max(0, sizeHint - ASSUMED_OMIT_TEXT_LENGTH - maxSuffixLength);
String sizeString = Integer.toString(text.length() - maxPrefixLength - maxSuffixLength);
int snippetLength = maxPrefixLength + OMIT_PREFIX.length() + sizeString.length() + OMIT_SUFFIX.length() + maxSuffixLength;
if (text.length() <= 1.05 * snippetLength + 5) return text;
return text.substring(0, maxPrefixLength) +
OMIT_PREFIX +
sizeString +
OMIT_SUFFIX +
text.substring(text.length() - maxSuffixLength);
} | class SnippetGenerator {
private static final int ASSUMED_OMIT_TEXT_LENGTH = omitText(1234).length();
private static String omitText(int omittedLength) { return "[..." + omittedLength + " chars omitted]"; }
/** Returns a snippet of approximate size. */
} | class SnippetGenerator {
private static final String OMIT_PREFIX = "[...";
private static final String OMIT_SUFFIX = " chars omitted]";
private static final int ASSUMED_OMIT_TEXT_LENGTH = OMIT_PREFIX.length() + 4 + OMIT_SUFFIX.length();
/** Returns a snippet of approximate size. */
} |
This could be done without generating the snippet first? | public String makeSnippet(String text, int sizeHint) {
if (text.length() < sizeHint) return text;
int maxSuffixLength = Math.max(0, (sizeHint - ASSUMED_OMIT_TEXT_LENGTH) / 2);
int maxPrefixLength = Math.max(0, sizeHint - ASSUMED_OMIT_TEXT_LENGTH - maxSuffixLength);
String snippet =
text.substring(0, maxPrefixLength) +
omitText(text.length() - maxPrefixLength - maxSuffixLength) +
text.substring(text.length() - maxSuffixLength);
if (text.length() <= 1.05 * snippet.length() + 5) return text;
return snippet;
} | if (text.length() <= 1.05 * snippet.length() + 5) return text; | public String makeSnippet(String text, int sizeHint) {
if (text.length() <= Math.max(sizeHint, ASSUMED_OMIT_TEXT_LENGTH)) return text;
int maxSuffixLength = Math.max(0, (sizeHint - ASSUMED_OMIT_TEXT_LENGTH) / 2);
int maxPrefixLength = Math.max(0, sizeHint - ASSUMED_OMIT_TEXT_LENGTH - maxSuffixLength);
String sizeString = Integer.toString(text.length() - maxPrefixLength - maxSuffixLength);
int snippetLength = maxPrefixLength + OMIT_PREFIX.length() + sizeString.length() + OMIT_SUFFIX.length() + maxSuffixLength;
if (text.length() <= 1.05 * snippetLength + 5) return text;
return text.substring(0, maxPrefixLength) +
OMIT_PREFIX +
sizeString +
OMIT_SUFFIX +
text.substring(text.length() - maxSuffixLength);
} | class SnippetGenerator {
private static final int ASSUMED_OMIT_TEXT_LENGTH = omitText(1234).length();
private static String omitText(int omittedLength) { return "[..." + omittedLength + " chars omitted]"; }
/** Returns a snippet of approximate size. */
} | class SnippetGenerator {
private static final String OMIT_PREFIX = "[...";
private static final String OMIT_SUFFIX = " chars omitted]";
private static final int ASSUMED_OMIT_TEXT_LENGTH = OMIT_PREFIX.length() + 4 + OMIT_SUFFIX.length();
/** Returns a snippet of approximate size. */
} |
Also you're better off returning `text` if it smaller than omit text length. | public String makeSnippet(String text, int sizeHint) {
if (text.length() < sizeHint) return text;
int maxSuffixLength = Math.max(0, (sizeHint - ASSUMED_OMIT_TEXT_LENGTH) / 2);
int maxPrefixLength = Math.max(0, sizeHint - ASSUMED_OMIT_TEXT_LENGTH - maxSuffixLength);
String snippet =
text.substring(0, maxPrefixLength) +
omitText(text.length() - maxPrefixLength - maxSuffixLength) +
text.substring(text.length() - maxSuffixLength);
if (text.length() <= 1.05 * snippet.length() + 5) return text;
return snippet;
} | if (text.length() < sizeHint) return text; | public String makeSnippet(String text, int sizeHint) {
if (text.length() <= Math.max(sizeHint, ASSUMED_OMIT_TEXT_LENGTH)) return text;
int maxSuffixLength = Math.max(0, (sizeHint - ASSUMED_OMIT_TEXT_LENGTH) / 2);
int maxPrefixLength = Math.max(0, sizeHint - ASSUMED_OMIT_TEXT_LENGTH - maxSuffixLength);
String sizeString = Integer.toString(text.length() - maxPrefixLength - maxSuffixLength);
int snippetLength = maxPrefixLength + OMIT_PREFIX.length() + sizeString.length() + OMIT_SUFFIX.length() + maxSuffixLength;
if (text.length() <= 1.05 * snippetLength + 5) return text;
return text.substring(0, maxPrefixLength) +
OMIT_PREFIX +
sizeString +
OMIT_SUFFIX +
text.substring(text.length() - maxSuffixLength);
} | class SnippetGenerator {
private static final int ASSUMED_OMIT_TEXT_LENGTH = omitText(1234).length();
private static String omitText(int omittedLength) { return "[..." + omittedLength + " chars omitted]"; }
/** Returns a snippet of approximate size. */
} | class SnippetGenerator {
private static final String OMIT_PREFIX = "[...";
private static final String OMIT_SUFFIX = " chars omitted]";
private static final int ASSUMED_OMIT_TEXT_LENGTH = OMIT_PREFIX.length() + 4 + OMIT_SUFFIX.length();
/** Returns a snippet of approximate size. */
} |
Done By "omit text length" I take it you mean ASSUMED_OMIT_TEXT_LENGTH and not omitText(text.length).length(). Done. | public String makeSnippet(String text, int sizeHint) {
if (text.length() < sizeHint) return text;
int maxSuffixLength = Math.max(0, (sizeHint - ASSUMED_OMIT_TEXT_LENGTH) / 2);
int maxPrefixLength = Math.max(0, sizeHint - ASSUMED_OMIT_TEXT_LENGTH - maxSuffixLength);
String snippet =
text.substring(0, maxPrefixLength) +
omitText(text.length() - maxPrefixLength - maxSuffixLength) +
text.substring(text.length() - maxSuffixLength);
if (text.length() <= 1.05 * snippet.length() + 5) return text;
return snippet;
} | if (text.length() < sizeHint) return text; | public String makeSnippet(String text, int sizeHint) {
if (text.length() <= Math.max(sizeHint, ASSUMED_OMIT_TEXT_LENGTH)) return text;
int maxSuffixLength = Math.max(0, (sizeHint - ASSUMED_OMIT_TEXT_LENGTH) / 2);
int maxPrefixLength = Math.max(0, sizeHint - ASSUMED_OMIT_TEXT_LENGTH - maxSuffixLength);
String sizeString = Integer.toString(text.length() - maxPrefixLength - maxSuffixLength);
int snippetLength = maxPrefixLength + OMIT_PREFIX.length() + sizeString.length() + OMIT_SUFFIX.length() + maxSuffixLength;
if (text.length() <= 1.05 * snippetLength + 5) return text;
return text.substring(0, maxPrefixLength) +
OMIT_PREFIX +
sizeString +
OMIT_SUFFIX +
text.substring(text.length() - maxSuffixLength);
} | class SnippetGenerator {
private static final int ASSUMED_OMIT_TEXT_LENGTH = omitText(1234).length();
private static String omitText(int omittedLength) { return "[..." + omittedLength + " chars omitted]"; }
/** Returns a snippet of approximate size. */
} | class SnippetGenerator {
private static final String OMIT_PREFIX = "[...";
private static final String OMIT_SUFFIX = " chars omitted]";
private static final int ASSUMED_OMIT_TEXT_LENGTH = OMIT_PREFIX.length() + 4 + OMIT_SUFFIX.length();
/** Returns a snippet of approximate size. */
} |
Yes but the implementation will complicate the code. I'll do it. | public String makeSnippet(String text, int sizeHint) {
if (text.length() < sizeHint) return text;
int maxSuffixLength = Math.max(0, (sizeHint - ASSUMED_OMIT_TEXT_LENGTH) / 2);
int maxPrefixLength = Math.max(0, sizeHint - ASSUMED_OMIT_TEXT_LENGTH - maxSuffixLength);
String snippet =
text.substring(0, maxPrefixLength) +
omitText(text.length() - maxPrefixLength - maxSuffixLength) +
text.substring(text.length() - maxSuffixLength);
if (text.length() <= 1.05 * snippet.length() + 5) return text;
return snippet;
} | if (text.length() <= 1.05 * snippet.length() + 5) return text; | public String makeSnippet(String text, int sizeHint) {
if (text.length() <= Math.max(sizeHint, ASSUMED_OMIT_TEXT_LENGTH)) return text;
int maxSuffixLength = Math.max(0, (sizeHint - ASSUMED_OMIT_TEXT_LENGTH) / 2);
int maxPrefixLength = Math.max(0, sizeHint - ASSUMED_OMIT_TEXT_LENGTH - maxSuffixLength);
String sizeString = Integer.toString(text.length() - maxPrefixLength - maxSuffixLength);
int snippetLength = maxPrefixLength + OMIT_PREFIX.length() + sizeString.length() + OMIT_SUFFIX.length() + maxSuffixLength;
if (text.length() <= 1.05 * snippetLength + 5) return text;
return text.substring(0, maxPrefixLength) +
OMIT_PREFIX +
sizeString +
OMIT_SUFFIX +
text.substring(text.length() - maxSuffixLength);
} | class SnippetGenerator {
private static final int ASSUMED_OMIT_TEXT_LENGTH = omitText(1234).length();
private static String omitText(int omittedLength) { return "[..." + omittedLength + " chars omitted]"; }
/** Returns a snippet of approximate size. */
} | class SnippetGenerator {
private static final String OMIT_PREFIX = "[...";
private static final String OMIT_SUFFIX = " chars omitted]";
private static final int ASSUMED_OMIT_TEXT_LENGTH = OMIT_PREFIX.length() + 4 + OMIT_SUFFIX.length();
/** Returns a snippet of approximate size. */
} |
Code ended up being just fine. | public String makeSnippet(String text, int sizeHint) {
if (text.length() < sizeHint) return text;
int maxSuffixLength = Math.max(0, (sizeHint - ASSUMED_OMIT_TEXT_LENGTH) / 2);
int maxPrefixLength = Math.max(0, sizeHint - ASSUMED_OMIT_TEXT_LENGTH - maxSuffixLength);
String snippet =
text.substring(0, maxPrefixLength) +
omitText(text.length() - maxPrefixLength - maxSuffixLength) +
text.substring(text.length() - maxSuffixLength);
if (text.length() <= 1.05 * snippet.length() + 5) return text;
return snippet;
} | if (text.length() <= 1.05 * snippet.length() + 5) return text; | public String makeSnippet(String text, int sizeHint) {
if (text.length() <= Math.max(sizeHint, ASSUMED_OMIT_TEXT_LENGTH)) return text;
int maxSuffixLength = Math.max(0, (sizeHint - ASSUMED_OMIT_TEXT_LENGTH) / 2);
int maxPrefixLength = Math.max(0, sizeHint - ASSUMED_OMIT_TEXT_LENGTH - maxSuffixLength);
String sizeString = Integer.toString(text.length() - maxPrefixLength - maxSuffixLength);
int snippetLength = maxPrefixLength + OMIT_PREFIX.length() + sizeString.length() + OMIT_SUFFIX.length() + maxSuffixLength;
if (text.length() <= 1.05 * snippetLength + 5) return text;
return text.substring(0, maxPrefixLength) +
OMIT_PREFIX +
sizeString +
OMIT_SUFFIX +
text.substring(text.length() - maxSuffixLength);
} | class SnippetGenerator {
private static final int ASSUMED_OMIT_TEXT_LENGTH = omitText(1234).length();
private static String omitText(int omittedLength) { return "[..." + omittedLength + " chars omitted]"; }
/** Returns a snippet of approximate size. */
} | class SnippetGenerator {
private static final String OMIT_PREFIX = "[...";
private static final String OMIT_SUFFIX = " chars omitted]";
private static final int ASSUMED_OMIT_TEXT_LENGTH = OMIT_PREFIX.length() + 4 + OMIT_SUFFIX.length();
/** Returns a snippet of approximate size. */
} |
Is there a test that verifies endpoint configuration combined with multiple instances? | public void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
new File("root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
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"));
tester.assertResponse(request("/application/v4/tenant/tenant1/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/2018-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"month\":\"2018-01\",\"items\":[]}");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
var app1 = deploymentTester.newDeploymentContext(id);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.devUsEast1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\"message\":\"Deactivated tenant1.application1.otheruser in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.otheruser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
id.application());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsCentral1);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 666)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1 with version 1.0.666-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
entity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
id2.application());
deploymentTester.applications().deploymentTrigger().triggerChange(TenantAndApplicationId.from(id2), Change.of(Version.fromString("7.0")));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage, 1000)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", 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/instance/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant2.application2.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant2.application2\"}");
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
deploymentTester.controllerTester().computeVersionStatus();
setDeploymentMaintainedInfo();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("deployment"),
new File("recursive-root.json"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("tenant"),
new File("recursive-until-tenant-root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("tenant1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-central-1/instance/default/logs?from=1233&to=3214", GET)
.userIdentity(USER_ID),
"INFO - All good");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Changed deployment from 'application change to 1.0.1-commit1' to 'no change' for 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\"}");
deploymentTester.configServer().nodeRepository().addFixedNodes(ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart?hostname=hostA", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "default"), ZoneId.from("prod", "us-central-1")),
List.of(new RoutingEndpoint("https:
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "my-user"), ZoneId.from("dev", "us-east-1")),
List.of(new RoutingEndpoint("https:
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
ApplicationPackage packageWithServiceForWrongDomain = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN_2.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"message\":\"Application package version: 1.0.2-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=1", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
.data(streamer),
"{\"message\":\"Application package version: 1.0.3-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.systemTest()
.stagingTest()
.environment(Environment.prod)
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec, 123)),
"{\"message\":\"Application package version: 1.0.4-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
.userIdentity(USER_ID),
new File("jobs.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
.userIdentity(USER_ID),
new File("system-test-job.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
.userIdentity(USER_ID),
new File("system-test-details.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Unregistered 'tenant1.application1' from internal deployment pipeline.\"}");
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/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.my-user\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance2\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
} | .region("us-central-1") | public void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
new File("root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
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"));
tester.assertResponse(request("/application/v4/tenant/tenant1/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/2018-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"month\":\"2018-01\",\"items\":[]}");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
var app1 = deploymentTester.newDeploymentContext(id);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.devUsEast1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\"message\":\"Deactivated tenant1.application1.otheruser in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.otheruser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
id.application());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsCentral1);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 666)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1 with version 1.0.666-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
entity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
id2.application());
deploymentTester.applications().deploymentTrigger().triggerChange(TenantAndApplicationId.from(id2), Change.of(Version.fromString("7.0")));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage, 1000)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", 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/instance/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant2.application2.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant2.application2\"}");
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
deploymentTester.controllerTester().computeVersionStatus();
setDeploymentMaintainedInfo();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("deployment"),
new File("recursive-root.json"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("tenant"),
new File("recursive-until-tenant-root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("tenant1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-central-1/instance/default/logs?from=1233&to=3214", GET)
.userIdentity(USER_ID),
"INFO - All good");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Changed deployment from 'application change to 1.0.1-commit1' to 'no change' for 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\"}");
deploymentTester.configServer().nodeRepository().addFixedNodes(ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart?hostname=hostA", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "default"), ZoneId.from("prod", "us-central-1")),
List.of(new RoutingEndpoint("https:
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "my-user"), ZoneId.from("dev", "us-east-1")),
List.of(new RoutingEndpoint("https:
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
ApplicationPackage packageWithServiceForWrongDomain = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN_2.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"message\":\"Application package version: 1.0.2-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=1", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
.data(streamer),
"{\"message\":\"Application package version: 1.0.3-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.environment(Environment.prod)
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec, 123)),
"{\"message\":\"Application package version: 1.0.4-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
.userIdentity(USER_ID),
new File("jobs.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
.userIdentity(USER_ID),
new File("system-test-job.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
.userIdentity(USER_ID),
new File("system-test-details.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Unregistered 'tenant1.application1' from internal deployment pipeline.\"}");
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/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.my-user\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance2\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private ContainerTester tester;
private DeploymentTester deploymentTester;
@Before
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().computeVersionStatus();
}
@Test
private void addIssues(DeploymentTester tester, TenantAndApplicationId id) {
tester.applications().lockApplicationOrThrow(id, application ->
tester.controller().applications().store(application.withDeploymentIssueId(IssueId.from("123"))
.withOwnershipIssueId(IssueId.from("321"))
.withOwner(User.from("owner-username"))));
}
@Test
public void testRotationOverride() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
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
public void multiple_endpoints() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-west-1"));
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-east-3"));
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "eu-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation?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);
}
@Test
public void testDeployDirectly() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST).userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
ApplicationName.from("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);
deploymentTester.controllerTester().upgradeSystem(deploymentTester.controller().versionStatus().controllerVersion().get().versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/proxy-host/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-no-deployment.json"), 400);
}
@Test
public void testSortsDeploymentsAndJobs() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
app.runJob(JobType.stagingTest).runJob(JobType.productionUsEast3);
setDeploymentMaintainedInfo();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-without-change-multiple-deployments.json"));
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = tester.serviceRegistry().meteringService();
ResourceAllocation currentSnapshot = new ResourceAllocation(1, 2, 3);
ResourceAllocation thisMonth = new ResourceAllocation(12, 24, 1000);
ResourceAllocation lastMonth = new ResourceAllocation(24, 48, 2000);
ApplicationId applicationId = ApplicationId.from("doesnotexist", "doesnotexist", "default");
Map<ApplicationId, List<ResourceSnapshot>> snapshotHistory = Map.of(applicationId, List.of(
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(123), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
public void testTenantCostResponse() {
ApplicationId applicationId = createTenantAndApplication();
MockTenantCost mockTenantCost = deploymentTester.controllerTester().serviceRegistry().tenantCost();
mockTenantCost.setMonthsWithMetering(
new TreeSet<>(Set.of(
YearMonth.of(2019, 10),
YearMonth.of(2019, 9)
))
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[\"2019-09\",\"2019-10\"]}");
CostInfo costInfo1 = new CostInfo(applicationId, ZoneId.from("prod", "us-south-1"),
new BigDecimal("7.0"),
new BigDecimal("600.0"),
new BigDecimal("1000.0"),
35, 23, 10);
CostInfo costInfo2 = new CostInfo(applicationId, ZoneId.from("prod", "us-north-1"),
new BigDecimal("2.0"),
new BigDecimal("3.0"),
new BigDecimal("4.0"),
10, 20, 30);
mockTenantCost.setCostInfoList(
List.of(costInfo1, costInfo2)
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost/2019-09", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("cost-report.json"));
}
@Test
public void testErrorResponses() throws Exception {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=42", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=foobar", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", 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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost/2018-01-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/not-a-valid-date", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not parse year-month 'not-a-valid-date'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 1234L);
var application = deploymentTester.newDeploymentContext("tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId("123");
addScrewdriverUserToDeployRole(screwdriverId, ATHENZ_TENANT_DOMAIN, application.instanceId().application());
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
400);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
public void personal_deployment_with_athenz_service_requires_user_is_admin() {
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.userIdentity(userId),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.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);
createTenantAndApplication();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
expectedResult,
400);
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
.admin(HostedAthenzIdentities.from(userId));
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(userId),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
@Test
public void testJobStatusReporting() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
Version vespaVersion = tester.configServer().initialVersion();
app.submit(applicationPackageInstance1);
String data = "{\"jobName\":\"system-test\",\"instance\":\"instance1\"}";
var request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(data)
.userIdentity(HOSTED_VESPA_OPERATOR);
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of system-test for tenant1.application1.instance1, but that has not been triggered; last was never\"}",
400);
deploymentTester.triggerJobs();
tester.assertResponse(request, "{\"message\":\"ok\"}");
JobStatus recordedStatus = app.instance().deploymentJobs().jobStatus().get(JobType.systemTest);
assertNotNull("Status was recorded", recordedStatus);
assertTrue(recordedStatus.isSuccess());
assertEquals(vespaVersion, recordedStatus.lastCompleted().get().platform());
}
@Test
public void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.instances("instance1")
.region("us-west-1")
.build();
app.submit(applicationPackage).deploy();
RoutingPolicy policy = new RoutingPolicy(app.instanceId(),
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.instanceId(), Set.of(policy));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private MultiPartStreamer createApplicationDeployData(ApplicationPackage applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(Optional.of(applicationPackage), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(applicationPackage, Optional.empty(), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage,
Optional<ApplicationVersion> applicationVersion, boolean deployDirectly) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", deployOptions(deployDirectly, applicationVersion));
applicationPackage.ifPresent(ap -> streamer.addBytes("applicationZip", ap.zippedContent()));
return streamer;
}
private MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage, long projectId) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repository1\",\"branch\":\"master\",\"commit\":\"commit1\","
+ "\"projectId\":" + projectId + ",\"authorEmail\":\"a@b\"}")
.addBytes(EnvironmentResource.APPLICATION_ZIP, applicationPackage.zippedContent())
.addBytes(EnvironmentResource.APPLICATION_TEST_ZIP, "content".getBytes());
}
private String deployOptions(boolean deployDirectly, Optional<ApplicationVersion> applicationVersion) {
return "{\"vespaVersion\":null," +
"\"ignoreValidationErrors\":false," +
"\"deployDirectly\":" + deployDirectly +
applicationVersion.map(version ->
"," +
"\"buildNumber\":" + version.buildNumber().getAsLong() + "," +
"\"sourceRevision\":{" +
"\"repository\":\"" + version.source().get().repository() + "\"," +
"\"branch\":\"" + version.source().get().branch() + "\"," +
"\"commit\":\"" + version.source().get().commit() + "\"" +
"}"
).orElse("") +
"}";
}
/** Make a request with (athens) user domain1.mytenant */
private RequestBuilder request(String path, Request.Method method) {
return new RequestBuilder(path, method);
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void createAthenzDomainWithAdmin(AthenzDomain domain, UserId userId) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(domain);
domainMock.markAsVespaTenant();
domainMock.admin(AthenzUser.fromUserId(userId.id()));
}
/**
* Mock athenz service identity configuration. Simulates that configserver is allowed to launch a service
*/
private void allowLaunchOfService(com.yahoo.vespa.athenz.api.AthenzService service) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(service.getDomain());
domainMock.services.put(service.getName(), new AthenzDbMock.Service(true));
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void addScrewdriverUserToDeployRole(ScrewdriverId screwdriverId,
AthenzDomain domain,
ApplicationName application) {
tester.authorize(domain, HostedAthenzIdentities.from(screwdriverId), ApplicationAction.deploy, application);
}
private ApplicationId createTenantAndApplication() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
/**
* Cluster info, utilization and application and deployment metrics are maintained async by maintainers.
*
* This sets these values as if the maintainers has been ran.
*/
private void setDeploymentMaintainedInfo() {
for (Application application : deploymentTester.applications().asList()) {
deploymentTester.applications().lockApplicationOrThrow(application.id(), lockedApplication -> {
lockedApplication = lockedApplication.with(new ApplicationMetrics(0.5, 0.7));
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.deployments().values()) {
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));
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)
.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
deploymentTester.applications().store(lockedApplication);
}
});
}
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
tester.serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator())).run();
}
private void updateContactInformation() {
Contact contact = new Contact(URI.create("www.contacts.tld/1234"),
URI.create("www.properties.tld/1234"),
URI.create("www.issues.tld/1234"),
List.of(List.of("alice"), List.of("bob")), "queue", Optional.empty());
tester.controller().tenants().lockIfPresent(TenantName.from("tenant2"),
LockedTenant.Athenz.class,
lockedTenant -> tester.controller().tenants().store(lockedTenant.with(contact)));
}
private void registerContact(long propertyId) {
PropertyId p = new PropertyId(String.valueOf(propertyId));
tester.serviceRegistry().contactRetrieverMock().addContact(p, new Contact(URI.create("www.issues.tld/" + p.id()),
URI.create("www.contacts.tld/" + p.id()),
URI.create("www.properties.tld/" + p.id()),
List.of(Collections.singletonList("alice"),
Collections.singletonList("bob")),
"queue", Optional.empty()));
}
private static class RequestBuilder implements Supplier<Request> {
private final String path;
private final Request.Method method;
private byte[] data = new byte[0];
private AthenzIdentity identity;
private OktaIdentityToken oktaIdentityToken;
private OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private 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 oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { 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 (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private ContainerTester tester;
private DeploymentTester deploymentTester;
@Before
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().computeVersionStatus();
}
@Test
private void addIssues(DeploymentTester tester, TenantAndApplicationId id) {
tester.applications().lockApplicationOrThrow(id, application ->
tester.controller().applications().store(application.withDeploymentIssueId(IssueId.from("123"))
.withOwnershipIssueId(IssueId.from("321"))
.withOwner(User.from("owner-username"))));
}
@Test
public void testRotationOverride() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
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
public void multiple_endpoints() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-west-1"));
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-east-3"));
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "eu-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation?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);
}
@Test
public void testDeployDirectly() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST).userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
ApplicationName.from("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);
deploymentTester.controllerTester().upgradeSystem(deploymentTester.controller().versionStatus().controllerVersion().get().versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/proxy-host/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-no-deployment.json"), 400);
}
@Test
public void testSortsDeploymentsAndJobs() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
app.runJob(JobType.stagingTest).runJob(JobType.productionUsEast3);
setDeploymentMaintainedInfo();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-without-change-multiple-deployments.json"));
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = tester.serviceRegistry().meteringService();
ResourceAllocation currentSnapshot = new ResourceAllocation(1, 2, 3);
ResourceAllocation thisMonth = new ResourceAllocation(12, 24, 1000);
ResourceAllocation lastMonth = new ResourceAllocation(24, 48, 2000);
ApplicationId applicationId = ApplicationId.from("doesnotexist", "doesnotexist", "default");
Map<ApplicationId, List<ResourceSnapshot>> snapshotHistory = Map.of(applicationId, List.of(
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(123), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
public void testTenantCostResponse() {
ApplicationId applicationId = createTenantAndApplication();
MockTenantCost mockTenantCost = deploymentTester.controllerTester().serviceRegistry().tenantCost();
mockTenantCost.setMonthsWithMetering(
new TreeSet<>(Set.of(
YearMonth.of(2019, 10),
YearMonth.of(2019, 9)
))
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[\"2019-09\",\"2019-10\"]}");
CostInfo costInfo1 = new CostInfo(applicationId, ZoneId.from("prod", "us-south-1"),
new BigDecimal("7.0"),
new BigDecimal("600.0"),
new BigDecimal("1000.0"),
35, 23, 10);
CostInfo costInfo2 = new CostInfo(applicationId, ZoneId.from("prod", "us-north-1"),
new BigDecimal("2.0"),
new BigDecimal("3.0"),
new BigDecimal("4.0"),
10, 20, 30);
mockTenantCost.setCostInfoList(
List.of(costInfo1, costInfo2)
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost/2019-09", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("cost-report.json"));
}
@Test
public void testErrorResponses() throws Exception {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=42", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=foobar", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", 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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost/2018-01-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/not-a-valid-date", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not parse year-month 'not-a-valid-date'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 1234L);
var application = deploymentTester.newDeploymentContext("tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId("123");
addScrewdriverUserToDeployRole(screwdriverId, ATHENZ_TENANT_DOMAIN, application.instanceId().application());
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
400);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
public void personal_deployment_with_athenz_service_requires_user_is_admin() {
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.userIdentity(userId),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.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);
createTenantAndApplication();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
expectedResult,
400);
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
.admin(HostedAthenzIdentities.from(userId));
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(userId),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
@Test
public void testJobStatusReporting() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
Version vespaVersion = tester.configServer().initialVersion();
app.submit(applicationPackageInstance1);
String data = "{\"jobName\":\"system-test\",\"instance\":\"instance1\"}";
var request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(data)
.userIdentity(HOSTED_VESPA_OPERATOR);
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of system-test for tenant1.application1.instance1, but that has not been triggered; last was never\"}",
400);
deploymentTester.triggerJobs();
tester.assertResponse(request, "{\"message\":\"ok\"}");
JobStatus recordedStatus = app.instance().deploymentJobs().jobStatus().get(JobType.systemTest);
assertNotNull("Status was recorded", recordedStatus);
assertTrue(recordedStatus.isSuccess());
assertEquals(vespaVersion, recordedStatus.lastCompleted().get().platform());
}
@Test
public void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.instances("instance1")
.region("us-west-1")
.build();
app.submit(applicationPackage).deploy();
RoutingPolicy policy = new RoutingPolicy(app.instanceId(),
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.instanceId(), Set.of(policy));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private MultiPartStreamer createApplicationDeployData(ApplicationPackage applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(Optional.of(applicationPackage), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(applicationPackage, Optional.empty(), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage,
Optional<ApplicationVersion> applicationVersion, boolean deployDirectly) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", deployOptions(deployDirectly, applicationVersion));
applicationPackage.ifPresent(ap -> streamer.addBytes("applicationZip", ap.zippedContent()));
return streamer;
}
private MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage, long projectId) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repository1\",\"branch\":\"master\",\"commit\":\"commit1\","
+ "\"projectId\":" + projectId + ",\"authorEmail\":\"a@b\"}")
.addBytes(EnvironmentResource.APPLICATION_ZIP, applicationPackage.zippedContent())
.addBytes(EnvironmentResource.APPLICATION_TEST_ZIP, "content".getBytes());
}
private String deployOptions(boolean deployDirectly, Optional<ApplicationVersion> applicationVersion) {
return "{\"vespaVersion\":null," +
"\"ignoreValidationErrors\":false," +
"\"deployDirectly\":" + deployDirectly +
applicationVersion.map(version ->
"," +
"\"buildNumber\":" + version.buildNumber().getAsLong() + "," +
"\"sourceRevision\":{" +
"\"repository\":\"" + version.source().get().repository() + "\"," +
"\"branch\":\"" + version.source().get().branch() + "\"," +
"\"commit\":\"" + version.source().get().commit() + "\"" +
"}"
).orElse("") +
"}";
}
/** Make a request with (athens) user domain1.mytenant */
private RequestBuilder request(String path, Request.Method method) {
return new RequestBuilder(path, method);
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void createAthenzDomainWithAdmin(AthenzDomain domain, UserId userId) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(domain);
domainMock.markAsVespaTenant();
domainMock.admin(AthenzUser.fromUserId(userId.id()));
}
/**
* Mock athenz service identity configuration. Simulates that configserver is allowed to launch a service
*/
private void allowLaunchOfService(com.yahoo.vespa.athenz.api.AthenzService service) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(service.getDomain());
domainMock.services.put(service.getName(), new AthenzDbMock.Service(true));
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void addScrewdriverUserToDeployRole(ScrewdriverId screwdriverId,
AthenzDomain domain,
ApplicationName application) {
tester.authorize(domain, HostedAthenzIdentities.from(screwdriverId), ApplicationAction.deploy, application);
}
private ApplicationId createTenantAndApplication() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
/**
* Cluster info, utilization and application and deployment metrics are maintained async by maintainers.
*
* This sets these values as if the maintainers has been ran.
*/
private void setDeploymentMaintainedInfo() {
for (Application application : deploymentTester.applications().asList()) {
deploymentTester.applications().lockApplicationOrThrow(application.id(), lockedApplication -> {
lockedApplication = lockedApplication.with(new ApplicationMetrics(0.5, 0.7));
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.deployments().values()) {
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));
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)
.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
deploymentTester.applications().store(lockedApplication);
}
});
}
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
tester.serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator())).run();
}
private void updateContactInformation() {
Contact contact = new Contact(URI.create("www.contacts.tld/1234"),
URI.create("www.properties.tld/1234"),
URI.create("www.issues.tld/1234"),
List.of(List.of("alice"), List.of("bob")), "queue", Optional.empty());
tester.controller().tenants().lockIfPresent(TenantName.from("tenant2"),
LockedTenant.Athenz.class,
lockedTenant -> tester.controller().tenants().store(lockedTenant.with(contact)));
}
private void registerContact(long propertyId) {
PropertyId p = new PropertyId(String.valueOf(propertyId));
tester.serviceRegistry().contactRetrieverMock().addContact(p, new Contact(URI.create("www.issues.tld/" + p.id()),
URI.create("www.contacts.tld/" + p.id()),
URI.create("www.properties.tld/" + p.id()),
List.of(Collections.singletonList("alice"),
Collections.singletonList("bob")),
"queue", Optional.empty()));
}
private static class RequestBuilder implements Supplier<Request> {
private final String path;
private final Request.Method method;
private byte[] data = new byte[0];
private AthenzIdentity identity;
private OktaIdentityToken oktaIdentityToken;
private OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private 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 oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { 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 (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} |
What calls are made against the rotation repository? | public void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
new File("root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
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"));
tester.assertResponse(request("/application/v4/tenant/tenant1/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/2018-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"month\":\"2018-01\",\"items\":[]}");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
var app1 = deploymentTester.newDeploymentContext(id);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.devUsEast1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\"message\":\"Deactivated tenant1.application1.otheruser in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.otheruser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
id.application());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsCentral1);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 666)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1 with version 1.0.666-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
entity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
id2.application());
deploymentTester.applications().deploymentTrigger().triggerChange(TenantAndApplicationId.from(id2), Change.of(Version.fromString("7.0")));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage, 1000)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", 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/instance/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant2.application2.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant2.application2\"}");
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
deploymentTester.controllerTester().computeVersionStatus();
setDeploymentMaintainedInfo();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("deployment"),
new File("recursive-root.json"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("tenant"),
new File("recursive-until-tenant-root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("tenant1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-central-1/instance/default/logs?from=1233&to=3214", GET)
.userIdentity(USER_ID),
"INFO - All good");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Changed deployment from 'application change to 1.0.1-commit1' to 'no change' for 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\"}");
deploymentTester.configServer().nodeRepository().addFixedNodes(ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart?hostname=hostA", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "default"), ZoneId.from("prod", "us-central-1")),
List.of(new RoutingEndpoint("https:
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "my-user"), ZoneId.from("dev", "us-east-1")),
List.of(new RoutingEndpoint("https:
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
ApplicationPackage packageWithServiceForWrongDomain = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN_2.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"message\":\"Application package version: 1.0.2-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=1", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
.data(streamer),
"{\"message\":\"Application package version: 1.0.3-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.systemTest()
.stagingTest()
.environment(Environment.prod)
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec, 123)),
"{\"message\":\"Application package version: 1.0.4-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
.userIdentity(USER_ID),
new File("jobs.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
.userIdentity(USER_ID),
new File("system-test-job.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
.userIdentity(USER_ID),
new File("system-test-details.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Unregistered 'tenant1.application1' from internal deployment pipeline.\"}");
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/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.my-user\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance2\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
} | .region("us-central-1") | public void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
new File("root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
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"));
tester.assertResponse(request("/application/v4/tenant/tenant1/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/2018-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"month\":\"2018-01\",\"items\":[]}");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
var app1 = deploymentTester.newDeploymentContext(id);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.devUsEast1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\"message\":\"Deactivated tenant1.application1.otheruser in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.otheruser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
id.application());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsCentral1);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 666)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1 with version 1.0.666-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
entity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
id2.application());
deploymentTester.applications().deploymentTrigger().triggerChange(TenantAndApplicationId.from(id2), Change.of(Version.fromString("7.0")));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage, 1000)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", 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/instance/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant2.application2.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant2.application2\"}");
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
deploymentTester.controllerTester().computeVersionStatus();
setDeploymentMaintainedInfo();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("deployment"),
new File("recursive-root.json"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("tenant"),
new File("recursive-until-tenant-root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("tenant1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-central-1/instance/default/logs?from=1233&to=3214", GET)
.userIdentity(USER_ID),
"INFO - All good");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Changed deployment from 'application change to 1.0.1-commit1' to 'no change' for 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\"}");
deploymentTester.configServer().nodeRepository().addFixedNodes(ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart?hostname=hostA", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "default"), ZoneId.from("prod", "us-central-1")),
List.of(new RoutingEndpoint("https:
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "my-user"), ZoneId.from("dev", "us-east-1")),
List.of(new RoutingEndpoint("https:
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
ApplicationPackage packageWithServiceForWrongDomain = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN_2.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"message\":\"Application package version: 1.0.2-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=1", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
.data(streamer),
"{\"message\":\"Application package version: 1.0.3-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.environment(Environment.prod)
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec, 123)),
"{\"message\":\"Application package version: 1.0.4-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
.userIdentity(USER_ID),
new File("jobs.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
.userIdentity(USER_ID),
new File("system-test-job.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
.userIdentity(USER_ID),
new File("system-test-details.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Unregistered 'tenant1.application1' from internal deployment pipeline.\"}");
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/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.my-user\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance2\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private ContainerTester tester;
private DeploymentTester deploymentTester;
@Before
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().computeVersionStatus();
}
@Test
private void addIssues(DeploymentTester tester, TenantAndApplicationId id) {
tester.applications().lockApplicationOrThrow(id, application ->
tester.controller().applications().store(application.withDeploymentIssueId(IssueId.from("123"))
.withOwnershipIssueId(IssueId.from("321"))
.withOwner(User.from("owner-username"))));
}
@Test
public void testRotationOverride() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
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
public void multiple_endpoints() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-west-1"));
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-east-3"));
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "eu-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation?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);
}
@Test
public void testDeployDirectly() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST).userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
ApplicationName.from("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);
deploymentTester.controllerTester().upgradeSystem(deploymentTester.controller().versionStatus().controllerVersion().get().versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/proxy-host/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-no-deployment.json"), 400);
}
@Test
public void testSortsDeploymentsAndJobs() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
app.runJob(JobType.stagingTest).runJob(JobType.productionUsEast3);
setDeploymentMaintainedInfo();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-without-change-multiple-deployments.json"));
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = tester.serviceRegistry().meteringService();
ResourceAllocation currentSnapshot = new ResourceAllocation(1, 2, 3);
ResourceAllocation thisMonth = new ResourceAllocation(12, 24, 1000);
ResourceAllocation lastMonth = new ResourceAllocation(24, 48, 2000);
ApplicationId applicationId = ApplicationId.from("doesnotexist", "doesnotexist", "default");
Map<ApplicationId, List<ResourceSnapshot>> snapshotHistory = Map.of(applicationId, List.of(
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(123), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
public void testTenantCostResponse() {
ApplicationId applicationId = createTenantAndApplication();
MockTenantCost mockTenantCost = deploymentTester.controllerTester().serviceRegistry().tenantCost();
mockTenantCost.setMonthsWithMetering(
new TreeSet<>(Set.of(
YearMonth.of(2019, 10),
YearMonth.of(2019, 9)
))
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[\"2019-09\",\"2019-10\"]}");
CostInfo costInfo1 = new CostInfo(applicationId, ZoneId.from("prod", "us-south-1"),
new BigDecimal("7.0"),
new BigDecimal("600.0"),
new BigDecimal("1000.0"),
35, 23, 10);
CostInfo costInfo2 = new CostInfo(applicationId, ZoneId.from("prod", "us-north-1"),
new BigDecimal("2.0"),
new BigDecimal("3.0"),
new BigDecimal("4.0"),
10, 20, 30);
mockTenantCost.setCostInfoList(
List.of(costInfo1, costInfo2)
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost/2019-09", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("cost-report.json"));
}
@Test
public void testErrorResponses() throws Exception {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=42", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=foobar", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", 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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost/2018-01-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/not-a-valid-date", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not parse year-month 'not-a-valid-date'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 1234L);
var application = deploymentTester.newDeploymentContext("tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId("123");
addScrewdriverUserToDeployRole(screwdriverId, ATHENZ_TENANT_DOMAIN, application.instanceId().application());
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
400);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
public void personal_deployment_with_athenz_service_requires_user_is_admin() {
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.userIdentity(userId),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.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);
createTenantAndApplication();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
expectedResult,
400);
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
.admin(HostedAthenzIdentities.from(userId));
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(userId),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
@Test
public void testJobStatusReporting() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
Version vespaVersion = tester.configServer().initialVersion();
app.submit(applicationPackageInstance1);
String data = "{\"jobName\":\"system-test\",\"instance\":\"instance1\"}";
var request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(data)
.userIdentity(HOSTED_VESPA_OPERATOR);
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of system-test for tenant1.application1.instance1, but that has not been triggered; last was never\"}",
400);
deploymentTester.triggerJobs();
tester.assertResponse(request, "{\"message\":\"ok\"}");
JobStatus recordedStatus = app.instance().deploymentJobs().jobStatus().get(JobType.systemTest);
assertNotNull("Status was recorded", recordedStatus);
assertTrue(recordedStatus.isSuccess());
assertEquals(vespaVersion, recordedStatus.lastCompleted().get().platform());
}
@Test
public void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.instances("instance1")
.region("us-west-1")
.build();
app.submit(applicationPackage).deploy();
RoutingPolicy policy = new RoutingPolicy(app.instanceId(),
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.instanceId(), Set.of(policy));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private MultiPartStreamer createApplicationDeployData(ApplicationPackage applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(Optional.of(applicationPackage), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(applicationPackage, Optional.empty(), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage,
Optional<ApplicationVersion> applicationVersion, boolean deployDirectly) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", deployOptions(deployDirectly, applicationVersion));
applicationPackage.ifPresent(ap -> streamer.addBytes("applicationZip", ap.zippedContent()));
return streamer;
}
private MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage, long projectId) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repository1\",\"branch\":\"master\",\"commit\":\"commit1\","
+ "\"projectId\":" + projectId + ",\"authorEmail\":\"a@b\"}")
.addBytes(EnvironmentResource.APPLICATION_ZIP, applicationPackage.zippedContent())
.addBytes(EnvironmentResource.APPLICATION_TEST_ZIP, "content".getBytes());
}
private String deployOptions(boolean deployDirectly, Optional<ApplicationVersion> applicationVersion) {
return "{\"vespaVersion\":null," +
"\"ignoreValidationErrors\":false," +
"\"deployDirectly\":" + deployDirectly +
applicationVersion.map(version ->
"," +
"\"buildNumber\":" + version.buildNumber().getAsLong() + "," +
"\"sourceRevision\":{" +
"\"repository\":\"" + version.source().get().repository() + "\"," +
"\"branch\":\"" + version.source().get().branch() + "\"," +
"\"commit\":\"" + version.source().get().commit() + "\"" +
"}"
).orElse("") +
"}";
}
/** Make a request with (athens) user domain1.mytenant */
private RequestBuilder request(String path, Request.Method method) {
return new RequestBuilder(path, method);
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void createAthenzDomainWithAdmin(AthenzDomain domain, UserId userId) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(domain);
domainMock.markAsVespaTenant();
domainMock.admin(AthenzUser.fromUserId(userId.id()));
}
/**
* Mock athenz service identity configuration. Simulates that configserver is allowed to launch a service
*/
private void allowLaunchOfService(com.yahoo.vespa.athenz.api.AthenzService service) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(service.getDomain());
domainMock.services.put(service.getName(), new AthenzDbMock.Service(true));
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void addScrewdriverUserToDeployRole(ScrewdriverId screwdriverId,
AthenzDomain domain,
ApplicationName application) {
tester.authorize(domain, HostedAthenzIdentities.from(screwdriverId), ApplicationAction.deploy, application);
}
private ApplicationId createTenantAndApplication() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
/**
* Cluster info, utilization and application and deployment metrics are maintained async by maintainers.
*
* This sets these values as if the maintainers has been ran.
*/
private void setDeploymentMaintainedInfo() {
for (Application application : deploymentTester.applications().asList()) {
deploymentTester.applications().lockApplicationOrThrow(application.id(), lockedApplication -> {
lockedApplication = lockedApplication.with(new ApplicationMetrics(0.5, 0.7));
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.deployments().values()) {
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));
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)
.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
deploymentTester.applications().store(lockedApplication);
}
});
}
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
tester.serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator())).run();
}
private void updateContactInformation() {
Contact contact = new Contact(URI.create("www.contacts.tld/1234"),
URI.create("www.properties.tld/1234"),
URI.create("www.issues.tld/1234"),
List.of(List.of("alice"), List.of("bob")), "queue", Optional.empty());
tester.controller().tenants().lockIfPresent(TenantName.from("tenant2"),
LockedTenant.Athenz.class,
lockedTenant -> tester.controller().tenants().store(lockedTenant.with(contact)));
}
private void registerContact(long propertyId) {
PropertyId p = new PropertyId(String.valueOf(propertyId));
tester.serviceRegistry().contactRetrieverMock().addContact(p, new Contact(URI.create("www.issues.tld/" + p.id()),
URI.create("www.contacts.tld/" + p.id()),
URI.create("www.properties.tld/" + p.id()),
List.of(Collections.singletonList("alice"),
Collections.singletonList("bob")),
"queue", Optional.empty()));
}
private static class RequestBuilder implements Supplier<Request> {
private final String path;
private final Request.Method method;
private byte[] data = new byte[0];
private AthenzIdentity identity;
private OktaIdentityToken oktaIdentityToken;
private OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private 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 oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { 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 (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private ContainerTester tester;
private DeploymentTester deploymentTester;
@Before
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().computeVersionStatus();
}
@Test
private void addIssues(DeploymentTester tester, TenantAndApplicationId id) {
tester.applications().lockApplicationOrThrow(id, application ->
tester.controller().applications().store(application.withDeploymentIssueId(IssueId.from("123"))
.withOwnershipIssueId(IssueId.from("321"))
.withOwner(User.from("owner-username"))));
}
@Test
public void testRotationOverride() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
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
public void multiple_endpoints() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-west-1"));
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-east-3"));
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "eu-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation?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);
}
@Test
public void testDeployDirectly() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST).userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
ApplicationName.from("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);
deploymentTester.controllerTester().upgradeSystem(deploymentTester.controller().versionStatus().controllerVersion().get().versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/proxy-host/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-no-deployment.json"), 400);
}
@Test
public void testSortsDeploymentsAndJobs() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
app.runJob(JobType.stagingTest).runJob(JobType.productionUsEast3);
setDeploymentMaintainedInfo();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-without-change-multiple-deployments.json"));
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = tester.serviceRegistry().meteringService();
ResourceAllocation currentSnapshot = new ResourceAllocation(1, 2, 3);
ResourceAllocation thisMonth = new ResourceAllocation(12, 24, 1000);
ResourceAllocation lastMonth = new ResourceAllocation(24, 48, 2000);
ApplicationId applicationId = ApplicationId.from("doesnotexist", "doesnotexist", "default");
Map<ApplicationId, List<ResourceSnapshot>> snapshotHistory = Map.of(applicationId, List.of(
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(123), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
public void testTenantCostResponse() {
ApplicationId applicationId = createTenantAndApplication();
MockTenantCost mockTenantCost = deploymentTester.controllerTester().serviceRegistry().tenantCost();
mockTenantCost.setMonthsWithMetering(
new TreeSet<>(Set.of(
YearMonth.of(2019, 10),
YearMonth.of(2019, 9)
))
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[\"2019-09\",\"2019-10\"]}");
CostInfo costInfo1 = new CostInfo(applicationId, ZoneId.from("prod", "us-south-1"),
new BigDecimal("7.0"),
new BigDecimal("600.0"),
new BigDecimal("1000.0"),
35, 23, 10);
CostInfo costInfo2 = new CostInfo(applicationId, ZoneId.from("prod", "us-north-1"),
new BigDecimal("2.0"),
new BigDecimal("3.0"),
new BigDecimal("4.0"),
10, 20, 30);
mockTenantCost.setCostInfoList(
List.of(costInfo1, costInfo2)
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost/2019-09", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("cost-report.json"));
}
@Test
public void testErrorResponses() throws Exception {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=42", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=foobar", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", 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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost/2018-01-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/not-a-valid-date", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not parse year-month 'not-a-valid-date'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 1234L);
var application = deploymentTester.newDeploymentContext("tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId("123");
addScrewdriverUserToDeployRole(screwdriverId, ATHENZ_TENANT_DOMAIN, application.instanceId().application());
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
400);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
public void personal_deployment_with_athenz_service_requires_user_is_admin() {
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.userIdentity(userId),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.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);
createTenantAndApplication();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
expectedResult,
400);
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
.admin(HostedAthenzIdentities.from(userId));
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(userId),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
@Test
public void testJobStatusReporting() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
Version vespaVersion = tester.configServer().initialVersion();
app.submit(applicationPackageInstance1);
String data = "{\"jobName\":\"system-test\",\"instance\":\"instance1\"}";
var request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(data)
.userIdentity(HOSTED_VESPA_OPERATOR);
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of system-test for tenant1.application1.instance1, but that has not been triggered; last was never\"}",
400);
deploymentTester.triggerJobs();
tester.assertResponse(request, "{\"message\":\"ok\"}");
JobStatus recordedStatus = app.instance().deploymentJobs().jobStatus().get(JobType.systemTest);
assertNotNull("Status was recorded", recordedStatus);
assertTrue(recordedStatus.isSuccess());
assertEquals(vespaVersion, recordedStatus.lastCompleted().get().platform());
}
@Test
public void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.instances("instance1")
.region("us-west-1")
.build();
app.submit(applicationPackage).deploy();
RoutingPolicy policy = new RoutingPolicy(app.instanceId(),
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.instanceId(), Set.of(policy));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private MultiPartStreamer createApplicationDeployData(ApplicationPackage applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(Optional.of(applicationPackage), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(applicationPackage, Optional.empty(), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage,
Optional<ApplicationVersion> applicationVersion, boolean deployDirectly) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", deployOptions(deployDirectly, applicationVersion));
applicationPackage.ifPresent(ap -> streamer.addBytes("applicationZip", ap.zippedContent()));
return streamer;
}
private MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage, long projectId) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repository1\",\"branch\":\"master\",\"commit\":\"commit1\","
+ "\"projectId\":" + projectId + ",\"authorEmail\":\"a@b\"}")
.addBytes(EnvironmentResource.APPLICATION_ZIP, applicationPackage.zippedContent())
.addBytes(EnvironmentResource.APPLICATION_TEST_ZIP, "content".getBytes());
}
private String deployOptions(boolean deployDirectly, Optional<ApplicationVersion> applicationVersion) {
return "{\"vespaVersion\":null," +
"\"ignoreValidationErrors\":false," +
"\"deployDirectly\":" + deployDirectly +
applicationVersion.map(version ->
"," +
"\"buildNumber\":" + version.buildNumber().getAsLong() + "," +
"\"sourceRevision\":{" +
"\"repository\":\"" + version.source().get().repository() + "\"," +
"\"branch\":\"" + version.source().get().branch() + "\"," +
"\"commit\":\"" + version.source().get().commit() + "\"" +
"}"
).orElse("") +
"}";
}
/** Make a request with (athens) user domain1.mytenant */
private RequestBuilder request(String path, Request.Method method) {
return new RequestBuilder(path, method);
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void createAthenzDomainWithAdmin(AthenzDomain domain, UserId userId) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(domain);
domainMock.markAsVespaTenant();
domainMock.admin(AthenzUser.fromUserId(userId.id()));
}
/**
* Mock athenz service identity configuration. Simulates that configserver is allowed to launch a service
*/
private void allowLaunchOfService(com.yahoo.vespa.athenz.api.AthenzService service) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(service.getDomain());
domainMock.services.put(service.getName(), new AthenzDbMock.Service(true));
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void addScrewdriverUserToDeployRole(ScrewdriverId screwdriverId,
AthenzDomain domain,
ApplicationName application) {
tester.authorize(domain, HostedAthenzIdentities.from(screwdriverId), ApplicationAction.deploy, application);
}
private ApplicationId createTenantAndApplication() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
/**
* Cluster info, utilization and application and deployment metrics are maintained async by maintainers.
*
* This sets these values as if the maintainers has been ran.
*/
private void setDeploymentMaintainedInfo() {
for (Application application : deploymentTester.applications().asList()) {
deploymentTester.applications().lockApplicationOrThrow(application.id(), lockedApplication -> {
lockedApplication = lockedApplication.with(new ApplicationMetrics(0.5, 0.7));
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.deployments().values()) {
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));
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)
.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
deploymentTester.applications().store(lockedApplication);
}
});
}
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
tester.serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator())).run();
}
private void updateContactInformation() {
Contact contact = new Contact(URI.create("www.contacts.tld/1234"),
URI.create("www.properties.tld/1234"),
URI.create("www.issues.tld/1234"),
List.of(List.of("alice"), List.of("bob")), "queue", Optional.empty());
tester.controller().tenants().lockIfPresent(TenantName.from("tenant2"),
LockedTenant.Athenz.class,
lockedTenant -> tester.controller().tenants().store(lockedTenant.with(contact)));
}
private void registerContact(long propertyId) {
PropertyId p = new PropertyId(String.valueOf(propertyId));
tester.serviceRegistry().contactRetrieverMock().addContact(p, new Contact(URI.create("www.issues.tld/" + p.id()),
URI.create("www.contacts.tld/" + p.id()),
URI.create("www.properties.tld/" + p.id()),
List.of(Collections.singletonList("alice"),
Collections.singletonList("bob")),
"queue", Optional.empty()));
}
private static class RequestBuilder implements Supplier<Request> {
private final String path;
private final Request.Method method;
private byte[] data = new byte[0];
private AthenzIdentity identity;
private OktaIdentityToken oktaIdentityToken;
private OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private 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 oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { 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 (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} |
We haven't really supported multiple instances in the deployment spec before, so no. I'll add one. Can you think of other places such tests are needed? | public void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
new File("root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
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"));
tester.assertResponse(request("/application/v4/tenant/tenant1/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/2018-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"month\":\"2018-01\",\"items\":[]}");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
var app1 = deploymentTester.newDeploymentContext(id);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.devUsEast1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\"message\":\"Deactivated tenant1.application1.otheruser in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.otheruser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
id.application());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsCentral1);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 666)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1 with version 1.0.666-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
entity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
id2.application());
deploymentTester.applications().deploymentTrigger().triggerChange(TenantAndApplicationId.from(id2), Change.of(Version.fromString("7.0")));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage, 1000)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", 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/instance/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant2.application2.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant2.application2\"}");
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
deploymentTester.controllerTester().computeVersionStatus();
setDeploymentMaintainedInfo();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("deployment"),
new File("recursive-root.json"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("tenant"),
new File("recursive-until-tenant-root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("tenant1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-central-1/instance/default/logs?from=1233&to=3214", GET)
.userIdentity(USER_ID),
"INFO - All good");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Changed deployment from 'application change to 1.0.1-commit1' to 'no change' for 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\"}");
deploymentTester.configServer().nodeRepository().addFixedNodes(ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart?hostname=hostA", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "default"), ZoneId.from("prod", "us-central-1")),
List.of(new RoutingEndpoint("https:
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "my-user"), ZoneId.from("dev", "us-east-1")),
List.of(new RoutingEndpoint("https:
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
ApplicationPackage packageWithServiceForWrongDomain = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN_2.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"message\":\"Application package version: 1.0.2-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=1", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
.data(streamer),
"{\"message\":\"Application package version: 1.0.3-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.systemTest()
.stagingTest()
.environment(Environment.prod)
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec, 123)),
"{\"message\":\"Application package version: 1.0.4-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
.userIdentity(USER_ID),
new File("jobs.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
.userIdentity(USER_ID),
new File("system-test-job.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
.userIdentity(USER_ID),
new File("system-test-details.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Unregistered 'tenant1.application1' from internal deployment pipeline.\"}");
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/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.my-user\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance2\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
} | .region("us-central-1") | public void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
new File("root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
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"));
tester.assertResponse(request("/application/v4/tenant/tenant1/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/2018-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"month\":\"2018-01\",\"items\":[]}");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
var app1 = deploymentTester.newDeploymentContext(id);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.devUsEast1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\"message\":\"Deactivated tenant1.application1.otheruser in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.otheruser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
id.application());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsCentral1);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 666)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1 with version 1.0.666-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
entity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
id2.application());
deploymentTester.applications().deploymentTrigger().triggerChange(TenantAndApplicationId.from(id2), Change.of(Version.fromString("7.0")));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage, 1000)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", 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/instance/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant2.application2.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant2.application2\"}");
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
deploymentTester.controllerTester().computeVersionStatus();
setDeploymentMaintainedInfo();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("deployment"),
new File("recursive-root.json"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("tenant"),
new File("recursive-until-tenant-root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("tenant1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-central-1/instance/default/logs?from=1233&to=3214", GET)
.userIdentity(USER_ID),
"INFO - All good");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Changed deployment from 'application change to 1.0.1-commit1' to 'no change' for 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\"}");
deploymentTester.configServer().nodeRepository().addFixedNodes(ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart?hostname=hostA", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "default"), ZoneId.from("prod", "us-central-1")),
List.of(new RoutingEndpoint("https:
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "my-user"), ZoneId.from("dev", "us-east-1")),
List.of(new RoutingEndpoint("https:
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
ApplicationPackage packageWithServiceForWrongDomain = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN_2.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"message\":\"Application package version: 1.0.2-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=1", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
.data(streamer),
"{\"message\":\"Application package version: 1.0.3-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.environment(Environment.prod)
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec, 123)),
"{\"message\":\"Application package version: 1.0.4-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
.userIdentity(USER_ID),
new File("jobs.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
.userIdentity(USER_ID),
new File("system-test-job.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
.userIdentity(USER_ID),
new File("system-test-details.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Unregistered 'tenant1.application1' from internal deployment pipeline.\"}");
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/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.my-user\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance2\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private ContainerTester tester;
private DeploymentTester deploymentTester;
@Before
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().computeVersionStatus();
}
@Test
private void addIssues(DeploymentTester tester, TenantAndApplicationId id) {
tester.applications().lockApplicationOrThrow(id, application ->
tester.controller().applications().store(application.withDeploymentIssueId(IssueId.from("123"))
.withOwnershipIssueId(IssueId.from("321"))
.withOwner(User.from("owner-username"))));
}
@Test
public void testRotationOverride() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
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
public void multiple_endpoints() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-west-1"));
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-east-3"));
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "eu-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation?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);
}
@Test
public void testDeployDirectly() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST).userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
ApplicationName.from("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);
deploymentTester.controllerTester().upgradeSystem(deploymentTester.controller().versionStatus().controllerVersion().get().versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/proxy-host/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-no-deployment.json"), 400);
}
@Test
public void testSortsDeploymentsAndJobs() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
app.runJob(JobType.stagingTest).runJob(JobType.productionUsEast3);
setDeploymentMaintainedInfo();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-without-change-multiple-deployments.json"));
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = tester.serviceRegistry().meteringService();
ResourceAllocation currentSnapshot = new ResourceAllocation(1, 2, 3);
ResourceAllocation thisMonth = new ResourceAllocation(12, 24, 1000);
ResourceAllocation lastMonth = new ResourceAllocation(24, 48, 2000);
ApplicationId applicationId = ApplicationId.from("doesnotexist", "doesnotexist", "default");
Map<ApplicationId, List<ResourceSnapshot>> snapshotHistory = Map.of(applicationId, List.of(
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(123), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
public void testTenantCostResponse() {
ApplicationId applicationId = createTenantAndApplication();
MockTenantCost mockTenantCost = deploymentTester.controllerTester().serviceRegistry().tenantCost();
mockTenantCost.setMonthsWithMetering(
new TreeSet<>(Set.of(
YearMonth.of(2019, 10),
YearMonth.of(2019, 9)
))
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[\"2019-09\",\"2019-10\"]}");
CostInfo costInfo1 = new CostInfo(applicationId, ZoneId.from("prod", "us-south-1"),
new BigDecimal("7.0"),
new BigDecimal("600.0"),
new BigDecimal("1000.0"),
35, 23, 10);
CostInfo costInfo2 = new CostInfo(applicationId, ZoneId.from("prod", "us-north-1"),
new BigDecimal("2.0"),
new BigDecimal("3.0"),
new BigDecimal("4.0"),
10, 20, 30);
mockTenantCost.setCostInfoList(
List.of(costInfo1, costInfo2)
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost/2019-09", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("cost-report.json"));
}
@Test
public void testErrorResponses() throws Exception {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=42", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=foobar", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", 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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost/2018-01-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/not-a-valid-date", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not parse year-month 'not-a-valid-date'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 1234L);
var application = deploymentTester.newDeploymentContext("tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId("123");
addScrewdriverUserToDeployRole(screwdriverId, ATHENZ_TENANT_DOMAIN, application.instanceId().application());
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
400);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
public void personal_deployment_with_athenz_service_requires_user_is_admin() {
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.userIdentity(userId),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.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);
createTenantAndApplication();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
expectedResult,
400);
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
.admin(HostedAthenzIdentities.from(userId));
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(userId),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
@Test
public void testJobStatusReporting() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
Version vespaVersion = tester.configServer().initialVersion();
app.submit(applicationPackageInstance1);
String data = "{\"jobName\":\"system-test\",\"instance\":\"instance1\"}";
var request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(data)
.userIdentity(HOSTED_VESPA_OPERATOR);
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of system-test for tenant1.application1.instance1, but that has not been triggered; last was never\"}",
400);
deploymentTester.triggerJobs();
tester.assertResponse(request, "{\"message\":\"ok\"}");
JobStatus recordedStatus = app.instance().deploymentJobs().jobStatus().get(JobType.systemTest);
assertNotNull("Status was recorded", recordedStatus);
assertTrue(recordedStatus.isSuccess());
assertEquals(vespaVersion, recordedStatus.lastCompleted().get().platform());
}
@Test
public void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.instances("instance1")
.region("us-west-1")
.build();
app.submit(applicationPackage).deploy();
RoutingPolicy policy = new RoutingPolicy(app.instanceId(),
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.instanceId(), Set.of(policy));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private MultiPartStreamer createApplicationDeployData(ApplicationPackage applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(Optional.of(applicationPackage), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(applicationPackage, Optional.empty(), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage,
Optional<ApplicationVersion> applicationVersion, boolean deployDirectly) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", deployOptions(deployDirectly, applicationVersion));
applicationPackage.ifPresent(ap -> streamer.addBytes("applicationZip", ap.zippedContent()));
return streamer;
}
private MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage, long projectId) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repository1\",\"branch\":\"master\",\"commit\":\"commit1\","
+ "\"projectId\":" + projectId + ",\"authorEmail\":\"a@b\"}")
.addBytes(EnvironmentResource.APPLICATION_ZIP, applicationPackage.zippedContent())
.addBytes(EnvironmentResource.APPLICATION_TEST_ZIP, "content".getBytes());
}
private String deployOptions(boolean deployDirectly, Optional<ApplicationVersion> applicationVersion) {
return "{\"vespaVersion\":null," +
"\"ignoreValidationErrors\":false," +
"\"deployDirectly\":" + deployDirectly +
applicationVersion.map(version ->
"," +
"\"buildNumber\":" + version.buildNumber().getAsLong() + "," +
"\"sourceRevision\":{" +
"\"repository\":\"" + version.source().get().repository() + "\"," +
"\"branch\":\"" + version.source().get().branch() + "\"," +
"\"commit\":\"" + version.source().get().commit() + "\"" +
"}"
).orElse("") +
"}";
}
/** Make a request with (athens) user domain1.mytenant */
private RequestBuilder request(String path, Request.Method method) {
return new RequestBuilder(path, method);
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void createAthenzDomainWithAdmin(AthenzDomain domain, UserId userId) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(domain);
domainMock.markAsVespaTenant();
domainMock.admin(AthenzUser.fromUserId(userId.id()));
}
/**
* Mock athenz service identity configuration. Simulates that configserver is allowed to launch a service
*/
private void allowLaunchOfService(com.yahoo.vespa.athenz.api.AthenzService service) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(service.getDomain());
domainMock.services.put(service.getName(), new AthenzDbMock.Service(true));
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void addScrewdriverUserToDeployRole(ScrewdriverId screwdriverId,
AthenzDomain domain,
ApplicationName application) {
tester.authorize(domain, HostedAthenzIdentities.from(screwdriverId), ApplicationAction.deploy, application);
}
private ApplicationId createTenantAndApplication() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
/**
* Cluster info, utilization and application and deployment metrics are maintained async by maintainers.
*
* This sets these values as if the maintainers has been ran.
*/
private void setDeploymentMaintainedInfo() {
for (Application application : deploymentTester.applications().asList()) {
deploymentTester.applications().lockApplicationOrThrow(application.id(), lockedApplication -> {
lockedApplication = lockedApplication.with(new ApplicationMetrics(0.5, 0.7));
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.deployments().values()) {
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));
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)
.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
deploymentTester.applications().store(lockedApplication);
}
});
}
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
tester.serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator())).run();
}
private void updateContactInformation() {
Contact contact = new Contact(URI.create("www.contacts.tld/1234"),
URI.create("www.properties.tld/1234"),
URI.create("www.issues.tld/1234"),
List.of(List.of("alice"), List.of("bob")), "queue", Optional.empty());
tester.controller().tenants().lockIfPresent(TenantName.from("tenant2"),
LockedTenant.Athenz.class,
lockedTenant -> tester.controller().tenants().store(lockedTenant.with(contact)));
}
private void registerContact(long propertyId) {
PropertyId p = new PropertyId(String.valueOf(propertyId));
tester.serviceRegistry().contactRetrieverMock().addContact(p, new Contact(URI.create("www.issues.tld/" + p.id()),
URI.create("www.contacts.tld/" + p.id()),
URI.create("www.properties.tld/" + p.id()),
List.of(Collections.singletonList("alice"),
Collections.singletonList("bob")),
"queue", Optional.empty()));
}
private static class RequestBuilder implements Supplier<Request> {
private final String path;
private final Request.Method method;
private byte[] data = new byte[0];
private AthenzIdentity identity;
private OktaIdentityToken oktaIdentityToken;
private OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private 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 oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { 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 (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private ContainerTester tester;
private DeploymentTester deploymentTester;
@Before
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().computeVersionStatus();
}
@Test
private void addIssues(DeploymentTester tester, TenantAndApplicationId id) {
tester.applications().lockApplicationOrThrow(id, application ->
tester.controller().applications().store(application.withDeploymentIssueId(IssueId.from("123"))
.withOwnershipIssueId(IssueId.from("321"))
.withOwner(User.from("owner-username"))));
}
@Test
public void testRotationOverride() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
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
public void multiple_endpoints() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-west-1"));
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-east-3"));
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "eu-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation?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);
}
@Test
public void testDeployDirectly() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST).userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
ApplicationName.from("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);
deploymentTester.controllerTester().upgradeSystem(deploymentTester.controller().versionStatus().controllerVersion().get().versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/proxy-host/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-no-deployment.json"), 400);
}
@Test
public void testSortsDeploymentsAndJobs() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
app.runJob(JobType.stagingTest).runJob(JobType.productionUsEast3);
setDeploymentMaintainedInfo();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-without-change-multiple-deployments.json"));
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = tester.serviceRegistry().meteringService();
ResourceAllocation currentSnapshot = new ResourceAllocation(1, 2, 3);
ResourceAllocation thisMonth = new ResourceAllocation(12, 24, 1000);
ResourceAllocation lastMonth = new ResourceAllocation(24, 48, 2000);
ApplicationId applicationId = ApplicationId.from("doesnotexist", "doesnotexist", "default");
Map<ApplicationId, List<ResourceSnapshot>> snapshotHistory = Map.of(applicationId, List.of(
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(123), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
public void testTenantCostResponse() {
ApplicationId applicationId = createTenantAndApplication();
MockTenantCost mockTenantCost = deploymentTester.controllerTester().serviceRegistry().tenantCost();
mockTenantCost.setMonthsWithMetering(
new TreeSet<>(Set.of(
YearMonth.of(2019, 10),
YearMonth.of(2019, 9)
))
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[\"2019-09\",\"2019-10\"]}");
CostInfo costInfo1 = new CostInfo(applicationId, ZoneId.from("prod", "us-south-1"),
new BigDecimal("7.0"),
new BigDecimal("600.0"),
new BigDecimal("1000.0"),
35, 23, 10);
CostInfo costInfo2 = new CostInfo(applicationId, ZoneId.from("prod", "us-north-1"),
new BigDecimal("2.0"),
new BigDecimal("3.0"),
new BigDecimal("4.0"),
10, 20, 30);
mockTenantCost.setCostInfoList(
List.of(costInfo1, costInfo2)
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost/2019-09", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("cost-report.json"));
}
@Test
public void testErrorResponses() throws Exception {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=42", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=foobar", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", 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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost/2018-01-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/not-a-valid-date", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not parse year-month 'not-a-valid-date'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 1234L);
var application = deploymentTester.newDeploymentContext("tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId("123");
addScrewdriverUserToDeployRole(screwdriverId, ATHENZ_TENANT_DOMAIN, application.instanceId().application());
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
400);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
public void personal_deployment_with_athenz_service_requires_user_is_admin() {
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.userIdentity(userId),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.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);
createTenantAndApplication();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
expectedResult,
400);
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
.admin(HostedAthenzIdentities.from(userId));
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(userId),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
@Test
public void testJobStatusReporting() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
Version vespaVersion = tester.configServer().initialVersion();
app.submit(applicationPackageInstance1);
String data = "{\"jobName\":\"system-test\",\"instance\":\"instance1\"}";
var request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(data)
.userIdentity(HOSTED_VESPA_OPERATOR);
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of system-test for tenant1.application1.instance1, but that has not been triggered; last was never\"}",
400);
deploymentTester.triggerJobs();
tester.assertResponse(request, "{\"message\":\"ok\"}");
JobStatus recordedStatus = app.instance().deploymentJobs().jobStatus().get(JobType.systemTest);
assertNotNull("Status was recorded", recordedStatus);
assertTrue(recordedStatus.isSuccess());
assertEquals(vespaVersion, recordedStatus.lastCompleted().get().platform());
}
@Test
public void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.instances("instance1")
.region("us-west-1")
.build();
app.submit(applicationPackage).deploy();
RoutingPolicy policy = new RoutingPolicy(app.instanceId(),
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.instanceId(), Set.of(policy));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private MultiPartStreamer createApplicationDeployData(ApplicationPackage applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(Optional.of(applicationPackage), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(applicationPackage, Optional.empty(), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage,
Optional<ApplicationVersion> applicationVersion, boolean deployDirectly) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", deployOptions(deployDirectly, applicationVersion));
applicationPackage.ifPresent(ap -> streamer.addBytes("applicationZip", ap.zippedContent()));
return streamer;
}
private MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage, long projectId) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repository1\",\"branch\":\"master\",\"commit\":\"commit1\","
+ "\"projectId\":" + projectId + ",\"authorEmail\":\"a@b\"}")
.addBytes(EnvironmentResource.APPLICATION_ZIP, applicationPackage.zippedContent())
.addBytes(EnvironmentResource.APPLICATION_TEST_ZIP, "content".getBytes());
}
private String deployOptions(boolean deployDirectly, Optional<ApplicationVersion> applicationVersion) {
return "{\"vespaVersion\":null," +
"\"ignoreValidationErrors\":false," +
"\"deployDirectly\":" + deployDirectly +
applicationVersion.map(version ->
"," +
"\"buildNumber\":" + version.buildNumber().getAsLong() + "," +
"\"sourceRevision\":{" +
"\"repository\":\"" + version.source().get().repository() + "\"," +
"\"branch\":\"" + version.source().get().branch() + "\"," +
"\"commit\":\"" + version.source().get().commit() + "\"" +
"}"
).orElse("") +
"}";
}
/** Make a request with (athens) user domain1.mytenant */
private RequestBuilder request(String path, Request.Method method) {
return new RequestBuilder(path, method);
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void createAthenzDomainWithAdmin(AthenzDomain domain, UserId userId) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(domain);
domainMock.markAsVespaTenant();
domainMock.admin(AthenzUser.fromUserId(userId.id()));
}
/**
* Mock athenz service identity configuration. Simulates that configserver is allowed to launch a service
*/
private void allowLaunchOfService(com.yahoo.vespa.athenz.api.AthenzService service) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(service.getDomain());
domainMock.services.put(service.getName(), new AthenzDbMock.Service(true));
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void addScrewdriverUserToDeployRole(ScrewdriverId screwdriverId,
AthenzDomain domain,
ApplicationName application) {
tester.authorize(domain, HostedAthenzIdentities.from(screwdriverId), ApplicationAction.deploy, application);
}
private ApplicationId createTenantAndApplication() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
/**
* Cluster info, utilization and application and deployment metrics are maintained async by maintainers.
*
* This sets these values as if the maintainers has been ran.
*/
private void setDeploymentMaintainedInfo() {
for (Application application : deploymentTester.applications().asList()) {
deploymentTester.applications().lockApplicationOrThrow(application.id(), lockedApplication -> {
lockedApplication = lockedApplication.with(new ApplicationMetrics(0.5, 0.7));
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.deployments().values()) {
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));
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)
.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
deploymentTester.applications().store(lockedApplication);
}
});
}
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
tester.serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator())).run();
}
private void updateContactInformation() {
Contact contact = new Contact(URI.create("www.contacts.tld/1234"),
URI.create("www.properties.tld/1234"),
URI.create("www.issues.tld/1234"),
List.of(List.of("alice"), List.of("bob")), "queue", Optional.empty());
tester.controller().tenants().lockIfPresent(TenantName.from("tenant2"),
LockedTenant.Athenz.class,
lockedTenant -> tester.controller().tenants().store(lockedTenant.with(contact)));
}
private void registerContact(long propertyId) {
PropertyId p = new PropertyId(String.valueOf(propertyId));
tester.serviceRegistry().contactRetrieverMock().addContact(p, new Contact(URI.create("www.issues.tld/" + p.id()),
URI.create("www.contacts.tld/" + p.id()),
URI.create("www.properties.tld/" + p.id()),
List.of(Collections.singletonList("alice"),
Collections.singletonList("bob")),
"queue", Optional.empty()));
}
private static class RequestBuilder implements Supplier<Request> {
private final String path;
private final Request.Method method;
private byte[] data = new byte[0];
private AthenzIdentity identity;
private OktaIdentityToken oktaIdentityToken;
private OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private 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 oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { 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 (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} |
Ah, endpoints. | public void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
new File("root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
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"));
tester.assertResponse(request("/application/v4/tenant/tenant1/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/2018-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"month\":\"2018-01\",\"items\":[]}");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
var app1 = deploymentTester.newDeploymentContext(id);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.devUsEast1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\"message\":\"Deactivated tenant1.application1.otheruser in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.otheruser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
id.application());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsCentral1);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 666)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1 with version 1.0.666-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
entity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
id2.application());
deploymentTester.applications().deploymentTrigger().triggerChange(TenantAndApplicationId.from(id2), Change.of(Version.fromString("7.0")));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage, 1000)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", 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/instance/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant2.application2.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant2.application2\"}");
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
deploymentTester.controllerTester().computeVersionStatus();
setDeploymentMaintainedInfo();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("deployment"),
new File("recursive-root.json"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("tenant"),
new File("recursive-until-tenant-root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("tenant1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-central-1/instance/default/logs?from=1233&to=3214", GET)
.userIdentity(USER_ID),
"INFO - All good");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Changed deployment from 'application change to 1.0.1-commit1' to 'no change' for 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\"}");
deploymentTester.configServer().nodeRepository().addFixedNodes(ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart?hostname=hostA", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "default"), ZoneId.from("prod", "us-central-1")),
List.of(new RoutingEndpoint("https:
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "my-user"), ZoneId.from("dev", "us-east-1")),
List.of(new RoutingEndpoint("https:
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
ApplicationPackage packageWithServiceForWrongDomain = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN_2.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"message\":\"Application package version: 1.0.2-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=1", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
.data(streamer),
"{\"message\":\"Application package version: 1.0.3-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.systemTest()
.stagingTest()
.environment(Environment.prod)
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec, 123)),
"{\"message\":\"Application package version: 1.0.4-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
.userIdentity(USER_ID),
new File("jobs.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
.userIdentity(USER_ID),
new File("system-test-job.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
.userIdentity(USER_ID),
new File("system-test-details.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Unregistered 'tenant1.application1' from internal deployment pipeline.\"}");
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/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.my-user\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance2\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
} | .region("us-central-1") | public void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
new File("root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
new File("tenant-without-applications.json"));
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"));
tester.assertResponse(request("/application/v4/tenant/tenant1/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/2018-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"month\":\"2018-01\",\"items\":[]}");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID);
registerContact(1234);
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
new File("tenant-without-applications-with-id.json"));
updateContactInformation();
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
new File("tenant-with-contact-info.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
new File("instance-list.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
ApplicationId id = ApplicationId.from("tenant1", "application1", "instance1");
var app1 = deploymentTester.newDeploymentContext(id);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(JobType.devUsEast1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
.userIdentity(OTHER_USER_ID)
.data(createApplicationDeployData(applicationPackageInstance1, false)),
new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
.userIdentity(OTHER_USER_ID),
"{\"message\":\"Deactivated tenant1.application1.otheruser in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.otheruser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
id.application());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsCentral1);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 666)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No application package found for tenant1.application1 with version 1.0.666-commit1\"}",
400);
entity = createApplicationDeployData(Optional.empty(),
Optional.of(ApplicationVersion.from(DeploymentContext.defaultSourceRevision, 1)),
true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
entity = createApplicationDeployData(Optional.empty(), true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/", POST)
.data(entity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.region("us-west-1")
.region("us-east-3")
.allow(ValidationId.globalEndpointChange)
.build();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN_2,
id2.application());
deploymentTester.applications().deploymentTrigger().triggerChange(TenantAndApplicationId.from(id2), Change.of(Version.fromString("7.0")));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(applicationPackage, 1000)),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", 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/instance/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant2.application2.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant2.application2\"}");
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
deploymentTester.controllerTester().computeVersionStatus();
setDeploymentMaintainedInfo();
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("deployment"),
new File("recursive-root.json"));
tester.assertResponse(request("/application/v4/", GET)
.userIdentity(USER_ID)
.recursive("tenant"),
new File("recursive-until-tenant-root.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("tenant1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID)
.recursive("true"),
new File("instance1-recursive.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
.userIdentity(USER_ID),
new File("application-nodes.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-central-1/instance/default/logs?from=1233&to=3214", GET)
.userIdentity(USER_ID),
"INFO - All good");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Changed deployment from 'application change to 1.0.1-commit1' to 'no change' for 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\"}");
deploymentTester.configServer().nodeRepository().addFixedNodes(ZoneId.from("prod", "us-central-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart?hostname=hostA", POST)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
.userIdentity(USER_ID),
new File("suspended.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service", GET)
.userIdentity(USER_ID),
new File("services.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/service/storagenode-awe3slno6mmq2fye191y324jl/state/v1/", GET)
.userIdentity(USER_ID),
new File("service.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("delete-with-active-deployments.json"), 400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
.screwdriverIdentity(SCREWDRIVER_ID),
"{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(true, Optional.empty(), false, false));
tester.controller().applications().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"),
Optional.of(applicationPackageDefault),
new DeployOptions(false, Optional.empty(), false, false));
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "default"), ZoneId.from("prod", "us-central-1")),
List.of(new RoutingEndpoint("https:
tester.serviceRegistry().routingGeneratorMock().putEndpoints(new DeploymentId(ApplicationId.from("tenant1", "application1", "my-user"), ZoneId.from("dev", "us-east-1")),
List.of(new RoutingEndpoint("https:
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config-dev.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
.userIdentity(USER_ID),
new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
ZoneId.from("dev", "us-east-1"));
ApplicationPackage packageWithServiceForWrongDomain = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN_2.getName()), AthenzService.from("service"))
.region("us-west-1")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.environment(Environment.prod)
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from(ATHENZ_TENANT_DOMAIN.getName()), AthenzService.from("service"))
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"message\":\"Application package version: 1.0.2-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(packageWithService.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=1", GET).userIdentity(HOSTED_VESPA_OPERATOR),
(response) -> {
assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
},
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", "not/the/right/hash")
.data(createApplicationSubmissionData(packageWithService, 123)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
.data(streamer),
"{\"message\":\"Application package version: 1.0.3-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.environment(Environment.prod)
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
.screwdriverIdentity(SCREWDRIVER_ID)
.data(createApplicationSubmissionData(multiInstanceSpec, 123)),
"{\"message\":\"Application package version: 1.0.4-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
.userIdentity(USER_ID),
new File("jobs.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
.userIdentity(USER_ID),
new File("system-test-job.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
.userIdentity(USER_ID),
new File("system-test-details.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
.userIdentity(USER_ID),
"{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", DELETE)
.userIdentity(HOSTED_VESPA_OPERATOR),
"{\"message\":\"Unregistered 'tenant1.application1' from internal deployment pipeline.\"}");
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/default", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.my-user\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance2", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance2\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private ContainerTester tester;
private DeploymentTester deploymentTester;
@Before
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().computeVersionStatus();
}
@Test
private void addIssues(DeploymentTester tester, TenantAndApplicationId id) {
tester.applications().lockApplicationOrThrow(id, application ->
tester.controller().applications().store(application.withDeploymentIssueId(IssueId.from("123"))
.withOwnershipIssueId(IssueId.from("321"))
.withOwner(User.from("owner-username"))));
}
@Test
public void testRotationOverride() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
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
public void multiple_endpoints() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-west-1"));
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-east-3"));
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "eu-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation?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);
}
@Test
public void testDeployDirectly() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST).userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
ApplicationName.from("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);
deploymentTester.controllerTester().upgradeSystem(deploymentTester.controller().versionStatus().controllerVersion().get().versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/proxy-host/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-no-deployment.json"), 400);
}
@Test
public void testSortsDeploymentsAndJobs() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
app.runJob(JobType.stagingTest).runJob(JobType.productionUsEast3);
setDeploymentMaintainedInfo();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-without-change-multiple-deployments.json"));
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = tester.serviceRegistry().meteringService();
ResourceAllocation currentSnapshot = new ResourceAllocation(1, 2, 3);
ResourceAllocation thisMonth = new ResourceAllocation(12, 24, 1000);
ResourceAllocation lastMonth = new ResourceAllocation(24, 48, 2000);
ApplicationId applicationId = ApplicationId.from("doesnotexist", "doesnotexist", "default");
Map<ApplicationId, List<ResourceSnapshot>> snapshotHistory = Map.of(applicationId, List.of(
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(123), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
public void testTenantCostResponse() {
ApplicationId applicationId = createTenantAndApplication();
MockTenantCost mockTenantCost = deploymentTester.controllerTester().serviceRegistry().tenantCost();
mockTenantCost.setMonthsWithMetering(
new TreeSet<>(Set.of(
YearMonth.of(2019, 10),
YearMonth.of(2019, 9)
))
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[\"2019-09\",\"2019-10\"]}");
CostInfo costInfo1 = new CostInfo(applicationId, ZoneId.from("prod", "us-south-1"),
new BigDecimal("7.0"),
new BigDecimal("600.0"),
new BigDecimal("1000.0"),
35, 23, 10);
CostInfo costInfo2 = new CostInfo(applicationId, ZoneId.from("prod", "us-north-1"),
new BigDecimal("2.0"),
new BigDecimal("3.0"),
new BigDecimal("4.0"),
10, 20, 30);
mockTenantCost.setCostInfoList(
List.of(costInfo1, costInfo2)
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost/2019-09", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("cost-report.json"));
}
@Test
public void testErrorResponses() throws Exception {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=42", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=foobar", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", 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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost/2018-01-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/not-a-valid-date", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not parse year-month 'not-a-valid-date'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 1234L);
var application = deploymentTester.newDeploymentContext("tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId("123");
addScrewdriverUserToDeployRole(screwdriverId, ATHENZ_TENANT_DOMAIN, application.instanceId().application());
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
400);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
public void personal_deployment_with_athenz_service_requires_user_is_admin() {
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.userIdentity(userId),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.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);
createTenantAndApplication();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
expectedResult,
400);
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
.admin(HostedAthenzIdentities.from(userId));
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(userId),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
@Test
public void testJobStatusReporting() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
Version vespaVersion = tester.configServer().initialVersion();
app.submit(applicationPackageInstance1);
String data = "{\"jobName\":\"system-test\",\"instance\":\"instance1\"}";
var request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(data)
.userIdentity(HOSTED_VESPA_OPERATOR);
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of system-test for tenant1.application1.instance1, but that has not been triggered; last was never\"}",
400);
deploymentTester.triggerJobs();
tester.assertResponse(request, "{\"message\":\"ok\"}");
JobStatus recordedStatus = app.instance().deploymentJobs().jobStatus().get(JobType.systemTest);
assertNotNull("Status was recorded", recordedStatus);
assertTrue(recordedStatus.isSuccess());
assertEquals(vespaVersion, recordedStatus.lastCompleted().get().platform());
}
@Test
public void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.instances("instance1")
.region("us-west-1")
.build();
app.submit(applicationPackage).deploy();
RoutingPolicy policy = new RoutingPolicy(app.instanceId(),
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.instanceId(), Set.of(policy));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private MultiPartStreamer createApplicationDeployData(ApplicationPackage applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(Optional.of(applicationPackage), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(applicationPackage, Optional.empty(), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage,
Optional<ApplicationVersion> applicationVersion, boolean deployDirectly) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", deployOptions(deployDirectly, applicationVersion));
applicationPackage.ifPresent(ap -> streamer.addBytes("applicationZip", ap.zippedContent()));
return streamer;
}
private MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage, long projectId) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repository1\",\"branch\":\"master\",\"commit\":\"commit1\","
+ "\"projectId\":" + projectId + ",\"authorEmail\":\"a@b\"}")
.addBytes(EnvironmentResource.APPLICATION_ZIP, applicationPackage.zippedContent())
.addBytes(EnvironmentResource.APPLICATION_TEST_ZIP, "content".getBytes());
}
private String deployOptions(boolean deployDirectly, Optional<ApplicationVersion> applicationVersion) {
return "{\"vespaVersion\":null," +
"\"ignoreValidationErrors\":false," +
"\"deployDirectly\":" + deployDirectly +
applicationVersion.map(version ->
"," +
"\"buildNumber\":" + version.buildNumber().getAsLong() + "," +
"\"sourceRevision\":{" +
"\"repository\":\"" + version.source().get().repository() + "\"," +
"\"branch\":\"" + version.source().get().branch() + "\"," +
"\"commit\":\"" + version.source().get().commit() + "\"" +
"}"
).orElse("") +
"}";
}
/** Make a request with (athens) user domain1.mytenant */
private RequestBuilder request(String path, Request.Method method) {
return new RequestBuilder(path, method);
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void createAthenzDomainWithAdmin(AthenzDomain domain, UserId userId) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(domain);
domainMock.markAsVespaTenant();
domainMock.admin(AthenzUser.fromUserId(userId.id()));
}
/**
* Mock athenz service identity configuration. Simulates that configserver is allowed to launch a service
*/
private void allowLaunchOfService(com.yahoo.vespa.athenz.api.AthenzService service) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(service.getDomain());
domainMock.services.put(service.getName(), new AthenzDbMock.Service(true));
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void addScrewdriverUserToDeployRole(ScrewdriverId screwdriverId,
AthenzDomain domain,
ApplicationName application) {
tester.authorize(domain, HostedAthenzIdentities.from(screwdriverId), ApplicationAction.deploy, application);
}
private ApplicationId createTenantAndApplication() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
/**
* Cluster info, utilization and application and deployment metrics are maintained async by maintainers.
*
* This sets these values as if the maintainers has been ran.
*/
private void setDeploymentMaintainedInfo() {
for (Application application : deploymentTester.applications().asList()) {
deploymentTester.applications().lockApplicationOrThrow(application.id(), lockedApplication -> {
lockedApplication = lockedApplication.with(new ApplicationMetrics(0.5, 0.7));
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.deployments().values()) {
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));
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)
.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
deploymentTester.applications().store(lockedApplication);
}
});
}
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
tester.serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator())).run();
}
private void updateContactInformation() {
Contact contact = new Contact(URI.create("www.contacts.tld/1234"),
URI.create("www.properties.tld/1234"),
URI.create("www.issues.tld/1234"),
List.of(List.of("alice"), List.of("bob")), "queue", Optional.empty());
tester.controller().tenants().lockIfPresent(TenantName.from("tenant2"),
LockedTenant.Athenz.class,
lockedTenant -> tester.controller().tenants().store(lockedTenant.with(contact)));
}
private void registerContact(long propertyId) {
PropertyId p = new PropertyId(String.valueOf(propertyId));
tester.serviceRegistry().contactRetrieverMock().addContact(p, new Contact(URI.create("www.issues.tld/" + p.id()),
URI.create("www.contacts.tld/" + p.id()),
URI.create("www.properties.tld/" + p.id()),
List.of(Collections.singletonList("alice"),
Collections.singletonList("bob")),
"queue", Optional.empty()));
}
private static class RequestBuilder implements Supplier<Request> {
private final String path;
private final Request.Method method;
private byte[] data = new byte[0];
private AthenzIdentity identity;
private OktaIdentityToken oktaIdentityToken;
private OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private 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 oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { 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 (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} | class ApplicationApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/";
private static final String pemPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\n" +
"z/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\n" +
"-----END PUBLIC KEY-----\n";
private static final String quotedPemPublicKey = pemPublicKey.replaceAll("\\n", "\\\\n");
private static final ApplicationPackage applicationPackageDefault = new ApplicationPackageBuilder()
.instances("default")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final ApplicationPackage applicationPackageInstance1 = new ApplicationPackageBuilder()
.instances("instance1")
.environment(Environment.prod)
.globalServiceId("foo")
.region("us-central-1")
.region("us-east-3")
.region("us-west-1")
.blockChange(false, true, "mon-fri", "0-8", "UTC")
.build();
private static final AthenzDomain ATHENZ_TENANT_DOMAIN = new AthenzDomain("domain1");
private static final AthenzDomain ATHENZ_TENANT_DOMAIN_2 = new AthenzDomain("domain2");
private static final ScrewdriverId SCREWDRIVER_ID = new ScrewdriverId("12345");
private static final UserId USER_ID = new UserId("myuser");
private static final UserId OTHER_USER_ID = new UserId("otheruser");
private static final UserId HOSTED_VESPA_OPERATOR = new UserId("johnoperator");
private static final OktaIdentityToken OKTA_IT = new OktaIdentityToken("okta-it");
private static final OktaAccessToken OKTA_AT = new OktaAccessToken("okta-at");
private ContainerTester tester;
private DeploymentTester deploymentTester;
@Before
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().computeVersionStatus();
}
@Test
private void addIssues(DeploymentTester tester, TenantAndApplicationId id) {
tester.applications().lockApplicationOrThrow(id, application ->
tester.controller().applications().store(application.withDeploymentIssueId(IssueId.from("123"))
.withOwnershipIssueId(IssueId.from("321"))
.withOwner(User.from("owner-username"))));
}
@Test
public void testRotationOverride() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
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
public void multiple_endpoints() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-west-1")
.region("us-east-3")
.region("eu-west-1")
.endpoint("eu", "default", "eu-west-1")
.endpoint("default", "default", "us-west-1", "us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-west-1"));
setZoneInRotation("rotation-fqdn-2", ZoneId.from("prod", "us-east-3"));
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "eu-west-1"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation?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);
}
@Test
public void testDeployDirectly() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1", POST).userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
ATHENZ_TENANT_DOMAIN,
ApplicationName.from("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);
deploymentTester.controllerTester().upgradeSystem(deploymentTester.controller().versionStatus().controllerVersion().get().versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/proxy-host/environment/prod/region/us-central-1/instance/instance1/deploy", POST)
.data(noAppEntity)
.userIdentity(HOSTED_VESPA_OPERATOR),
new File("deploy-no-deployment.json"), 400);
}
@Test
public void testSortsDeploymentsAndJobs() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.region("us-east-3")
.build();
var app = deploymentTester.newDeploymentContext("tenant1", "application1", "instance1");
app.submit(applicationPackage).deploy();
applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
.globalServiceId("foo")
.region("us-west-1")
.region("us-east-3")
.build();
app.submit(applicationPackage).runJob(JobType.systemTest).runJob(JobType.stagingTest).runJob(JobType.productionUsWest1);
setZoneInRotation("rotation-fqdn-1", ZoneId.from("prod", "us-west-1"));
app.runJob(JobType.stagingTest).runJob(JobType.productionUsEast3);
setDeploymentMaintainedInfo();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-without-change-multiple-deployments.json"));
}
@Test
public void testMeteringResponses() {
MockMeteringClient mockMeteringClient = tester.serviceRegistry().meteringService();
ResourceAllocation currentSnapshot = new ResourceAllocation(1, 2, 3);
ResourceAllocation thisMonth = new ResourceAllocation(12, 24, 1000);
ResourceAllocation lastMonth = new ResourceAllocation(24, 48, 2000);
ApplicationId applicationId = ApplicationId.from("doesnotexist", "doesnotexist", "default");
Map<ApplicationId, List<ResourceSnapshot>> snapshotHistory = Map.of(applicationId, List.of(
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(123), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(246), ZoneId.defaultId()),
new ResourceSnapshot(applicationId, 1, 2,3, Instant.ofEpochMilli(492), ZoneId.defaultId())));
mockMeteringClient.setMeteringInfo(new MeteringInfo(thisMonth, lastMonth, currentSnapshot, snapshotHistory));
tester.assertResponse(request("/application/v4/tenant/doesnotexist/application/doesnotexist/metering", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance1-metering.json"));
}
@Test
public void testTenantCostResponse() {
ApplicationId applicationId = createTenantAndApplication();
MockTenantCost mockTenantCost = deploymentTester.controllerTester().serviceRegistry().tenantCost();
mockTenantCost.setMonthsWithMetering(
new TreeSet<>(Set.of(
YearMonth.of(2019, 10),
YearMonth.of(2019, 9)
))
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"months\":[\"2019-09\",\"2019-10\"]}");
CostInfo costInfo1 = new CostInfo(applicationId, ZoneId.from("prod", "us-south-1"),
new BigDecimal("7.0"),
new BigDecimal("600.0"),
new BigDecimal("1000.0"),
35, 23, 10);
CostInfo costInfo2 = new CostInfo(applicationId, ZoneId.from("prod", "us-north-1"),
new BigDecimal("2.0"),
new BigDecimal("3.0"),
new BigDecimal("4.0"),
10, 20, 30);
mockTenantCost.setCostInfoList(
List.of(costInfo1, costInfo2)
);
tester.assertResponse(request("/application/v4/tenant/" + applicationId.tenant().value() + "/cost/2019-09", GET)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("cost-report.json"));
}
@Test
public void testErrorResponses() throws Exception {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
400);
tester.assertResponse(request("/application/v4/tenant/by-tenant2", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, null));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package has been submitted for 'tenant1.application1'\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=42", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"No application package found for 'tenant1.application1' with build number 42\"}",
404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package?build=foobar", GET).userIdentity(HOSTED_VESPA_OPERATOR),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid build number: For input string: \\\"foobar\\\"\"}",
400);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-west-1/instance/instance1/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
new File("deploy-failure.json"), 400);
configServer.throwOnNextPrepare(new ConfigServerException(new URI("server-url"), "Failed to prepare application", 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).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
400);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/no-such-tenant/cost/2018-01-01", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'no-such-tenant' does not exist\"}", 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/cost/not-a-valid-date", GET).userIdentity(USER_ID).oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not parse year-month 'not-a-valid-date'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
new Property("property1"), Optional.empty(), Optional.empty()));
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
400);
}
@Test
public void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"{\n \"message\" : \"Not authenticated\"\n}",
401);
tester.assertResponse(request("/application/v4/tenant/", GET)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
"[]",
200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT)
.userIdentity(unauthorizedUser),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(unauthorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"),
200);
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault, true);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
.data(entity)
.userIdentity(USER_ID),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference-default.json"),
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"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).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted instance tenant1.application1.default\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"message\":\"Deleted application tenant1.application1\"}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
.data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
.userIdentity(authorizedUser)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
"{\"tenant\":\"tenant1\",\"type\":\"ATHENS\",\"athensDomain\":\"domain2\",\"property\":\"property1\",\"applications\":[]}",
200);
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
.userIdentity(unauthorizedUser),
"{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n}",
403);
}
@Test
public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
deploymentTester.controllerTester().createTenant("tenant1", ATHENZ_TENANT_DOMAIN.getName(), 1234L);
var application = deploymentTester.newDeploymentContext("tenant1", "application1", "default");
ScrewdriverId screwdriverId = new ScrewdriverId("123");
addScrewdriverUserToDeployRole(screwdriverId, ATHENZ_TENANT_DOMAIN, application.instanceId().application());
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
400);
applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.environment(Environment.prod)
.region("us-west-1")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
400);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
.data(createApplicationSubmissionData(applicationPackage, 123))
.screwdriverIdentity(screwdriverId),
"{\"message\":\"Application package version: 1.0.1-commit1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
public void personal_deployment_with_athenz_service_requires_user_is_admin() {
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/user?user=new_user&domain=by", PUT)
.userIdentity(userId),
new File("create-user-response.json"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain1"), com.yahoo.config.provision.AthenzService.from("service"))
.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);
createTenantAndApplication();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
expectedResult,
400);
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
.admin(HostedAthenzIdentities.from(userId));
tester.assertResponse(request("/application/v4/tenant/by-new-user/application/application1/environment/dev/region/us-west-1/instance/default", POST)
.data(entity)
.userIdentity(userId),
new File("deploy-result.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
.data(entity)
.userIdentity(userId),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
@Test
public void testJobStatusReporting() {
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
Version vespaVersion = tester.configServer().initialVersion();
app.submit(applicationPackageInstance1);
String data = "{\"jobName\":\"system-test\",\"instance\":\"instance1\"}";
var request = request("/application/v4/tenant/tenant1/application/application1/jobreport", POST)
.data(data)
.userIdentity(HOSTED_VESPA_OPERATOR);
tester.assertResponse(request, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Notified of completion " +
"of system-test for tenant1.application1.instance1, but that has not been triggered; last was never\"}",
400);
deploymentTester.triggerJobs();
tester.assertResponse(request, "{\"message\":\"ok\"}");
JobStatus recordedStatus = app.instance().deploymentJobs().jobStatus().get(JobType.systemTest);
assertNotNull("Status was recorded", recordedStatus);
assertTrue(recordedStatus.isSuccess());
assertEquals(vespaVersion, recordedStatus.lastCompleted().get().platform());
}
@Test
public void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.environment(Environment.prod)
.instances("instance1")
.region("us-west-1")
.build();
app.submit(applicationPackage).deploy();
RoutingPolicy policy = new RoutingPolicy(app.instanceId(),
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.instanceId(), Set.of(policy));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("instance-with-routing-policy.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
.userIdentity(USER_ID),
new File("deployment-with-routing-policy.json"));
}
private MultiPartStreamer createApplicationDeployData(ApplicationPackage applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(Optional.of(applicationPackage), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage, boolean deployDirectly) {
return createApplicationDeployData(applicationPackage, Optional.empty(), deployDirectly);
}
private MultiPartStreamer createApplicationDeployData(Optional<ApplicationPackage> applicationPackage,
Optional<ApplicationVersion> applicationVersion, boolean deployDirectly) {
MultiPartStreamer streamer = new MultiPartStreamer();
streamer.addJson("deployOptions", deployOptions(deployDirectly, applicationVersion));
applicationPackage.ifPresent(ap -> streamer.addBytes("applicationZip", ap.zippedContent()));
return streamer;
}
private MultiPartStreamer createApplicationSubmissionData(ApplicationPackage applicationPackage, long projectId) {
return new MultiPartStreamer().addJson(EnvironmentResource.SUBMIT_OPTIONS, "{\"repository\":\"repository1\",\"branch\":\"master\",\"commit\":\"commit1\","
+ "\"projectId\":" + projectId + ",\"authorEmail\":\"a@b\"}")
.addBytes(EnvironmentResource.APPLICATION_ZIP, applicationPackage.zippedContent())
.addBytes(EnvironmentResource.APPLICATION_TEST_ZIP, "content".getBytes());
}
private String deployOptions(boolean deployDirectly, Optional<ApplicationVersion> applicationVersion) {
return "{\"vespaVersion\":null," +
"\"ignoreValidationErrors\":false," +
"\"deployDirectly\":" + deployDirectly +
applicationVersion.map(version ->
"," +
"\"buildNumber\":" + version.buildNumber().getAsLong() + "," +
"\"sourceRevision\":{" +
"\"repository\":\"" + version.source().get().repository() + "\"," +
"\"branch\":\"" + version.source().get().branch() + "\"," +
"\"commit\":\"" + version.source().get().commit() + "\"" +
"}"
).orElse("") +
"}";
}
/** Make a request with (athens) user domain1.mytenant */
private RequestBuilder request(String path, Request.Method method) {
return new RequestBuilder(path, method);
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void createAthenzDomainWithAdmin(AthenzDomain domain, UserId userId) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(domain);
domainMock.markAsVespaTenant();
domainMock.admin(AthenzUser.fromUserId(userId.id()));
}
/**
* Mock athenz service identity configuration. Simulates that configserver is allowed to launch a service
*/
private void allowLaunchOfService(com.yahoo.vespa.athenz.api.AthenzService service) {
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(service.getDomain());
domainMock.services.put(service.getName(), new AthenzDbMock.Service(true));
}
/**
* In production this happens outside hosted Vespa, so there is no API for it and we need to reach down into the
* mock setup to replicate the action.
*/
private void addScrewdriverUserToDeployRole(ScrewdriverId screwdriverId,
AthenzDomain domain,
ApplicationName application) {
tester.authorize(domain, HostedAthenzIdentities.from(screwdriverId), ApplicationAction.deploy, application);
}
private ApplicationId createTenantAndApplication() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
.userIdentity(USER_ID)
.data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("tenant-without-applications.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
.userIdentity(USER_ID)
.oktaAccessToken(OKTA_AT).oktaIdentityToken(OKTA_IT),
new File("instance-reference.json"));
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
return ApplicationId.from("tenant1", "application1", "instance1");
}
/**
* Cluster info, utilization and application and deployment metrics are maintained async by maintainers.
*
* This sets these values as if the maintainers has been ran.
*/
private void setDeploymentMaintainedInfo() {
for (Application application : deploymentTester.applications().asList()) {
deploymentTester.applications().lockApplicationOrThrow(application.id(), lockedApplication -> {
lockedApplication = lockedApplication.with(new ApplicationMetrics(0.5, 0.7));
for (Instance instance : application.instances().values()) {
for (Deployment deployment : instance.deployments().values()) {
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));
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)
.with(deployment.zone(), metrics)
.recordActivityAt(Instant.parse("2018-06-01T10:15:30.00Z"), deployment.zone()));
}
deploymentTester.applications().store(lockedApplication);
}
});
}
}
private void setZoneInRotation(String rotationName, ZoneId zone) {
tester.serviceRegistry().globalRoutingServiceMock().setStatus(rotationName, zone, com.yahoo.vespa.hosted.controller.api.integration.routing.RotationStatus.IN);
new RotationStatusUpdater(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator())).run();
}
private void updateContactInformation() {
Contact contact = new Contact(URI.create("www.contacts.tld/1234"),
URI.create("www.properties.tld/1234"),
URI.create("www.issues.tld/1234"),
List.of(List.of("alice"), List.of("bob")), "queue", Optional.empty());
tester.controller().tenants().lockIfPresent(TenantName.from("tenant2"),
LockedTenant.Athenz.class,
lockedTenant -> tester.controller().tenants().store(lockedTenant.with(contact)));
}
private void registerContact(long propertyId) {
PropertyId p = new PropertyId(String.valueOf(propertyId));
tester.serviceRegistry().contactRetrieverMock().addContact(p, new Contact(URI.create("www.issues.tld/" + p.id()),
URI.create("www.contacts.tld/" + p.id()),
URI.create("www.properties.tld/" + p.id()),
List.of(Collections.singletonList("alice"),
Collections.singletonList("bob")),
"queue", Optional.empty()));
}
private static class RequestBuilder implements Supplier<Request> {
private final String path;
private final Request.Method method;
private byte[] data = new byte[0];
private AthenzIdentity identity;
private OktaIdentityToken oktaIdentityToken;
private OktaAccessToken oktaAccessToken;
private String contentType = "application/json";
private 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 oktaIdentityToken(OktaIdentityToken oktaIdentityToken) { this.oktaIdentityToken = oktaIdentityToken; return this; }
private RequestBuilder oktaAccessToken(OktaAccessToken oktaAccessToken) { this.oktaAccessToken = oktaAccessToken; return this; }
private RequestBuilder contentType(String contentType) { this.contentType = contentType; return this; }
private RequestBuilder recursive(String recursive) { 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 (oktaIdentityToken != null) {
addOktaIdentityToken(request, oktaIdentityToken);
}
if (oktaAccessToken != null) {
addOktaAccessToken(request, oktaAccessToken);
}
return request;
}
}
} |
Probably possible to `flatMap` the optionals to get rid of the duplicate `orElse`. | public boolean triggerAt(Instant instant, JobType job, JobStatus jobStatus, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
if (instance.deploymentJobs().statusOf(job).map(status -> status.pausedUntil().orElse(0)).orElse(0L) > clock.millis()) return false;
if (jobStatus.lastTriggered().isEmpty()) return true;
if (jobStatus.isSuccess()) return true;
if (jobStatus.lastCompleted().isEmpty()) return true;
if (jobStatus.firstFailing().isEmpty()) return true;
if ( ! versions.targetsMatch(jobStatus.lastCompleted().get().versions())) return true;
if (deploymentSpec.requireInstance(instance.name()).upgradePolicy() == DeploymentSpec.UpgradePolicy.canary) return true;
Instant firstFailing = jobStatus.firstFailing().get().end().get();
Instant lastCompleted = jobStatus.lastCompleted().get().end().get();
if (firstFailing.isAfter(instant.minus(Duration.ofMinutes(1)))) return true;
if (job.isTest() && jobStatus.isOutOfCapacity()) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(1)));
}
if (firstFailing.isAfter(instant.minus(Duration.ofHours(1)))) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(10)));
}
return lastCompleted.isBefore(instant.minus(Duration.ofHours(2)));
} | if (instance.deploymentJobs().statusOf(job).map(status -> status.pausedUntil().orElse(0)).orElse(0L) > clock.millis()) return false; | public boolean triggerAt(Instant instant, JobType job, JobStatus jobStatus, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
if (instance.deploymentJobs().statusOf(job).map(status -> status.pausedUntil().orElse(0)).orElse(0L) > clock.millis()) return false;
if (jobStatus.lastTriggered().isEmpty()) return true;
if (jobStatus.isSuccess()) return true;
if (jobStatus.lastCompleted().isEmpty()) return true;
if (jobStatus.firstFailing().isEmpty()) return true;
if ( ! versions.targetsMatch(jobStatus.lastCompleted().get().versions())) return true;
if (deploymentSpec.requireInstance(instance.name()).upgradePolicy() == DeploymentSpec.UpgradePolicy.canary) return true;
Instant firstFailing = jobStatus.firstFailing().get().end().get();
Instant lastCompleted = jobStatus.lastCompleted().get().end().get();
if (firstFailing.isAfter(instant.minus(Duration.ofMinutes(1)))) return true;
if (job.isTest() && jobStatus.isOutOfCapacity()) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(1)));
}
if (firstFailing.isAfter(instant.minus(Duration.ofHours(1)))) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(10)));
}
return lastCompleted.isBefore(instant.minus(Duration.ofHours(2)));
} | class DeploymentTrigger {
/*
* Instance orchestration TODO jonmv.
* Store new production application packages under non-instance path
* Read production packages from non-instance path, with fallback
* Deprecate and redirect some instance qualified paths in application/v4
* Orchestrate deployment across instances.
*/
public static final Duration maxPause = Duration.ofDays(3);
private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName());
private final Controller controller;
private final Clock clock;
private final BuildService buildService;
private final JobController jobs;
public DeploymentTrigger(Controller controller, BuildService buildService, Clock clock) {
this.controller = Objects.requireNonNull(controller, "controller cannot be null");
this.clock = Objects.requireNonNull(clock, "clock cannot be null");
this.buildService = Objects.requireNonNull(buildService, "buildService cannot be null");
this.jobs = controller.jobController();
}
public DeploymentSteps steps(DeploymentInstanceSpec spec) {
return new DeploymentSteps(spec, controller::system);
}
public void notifyOfSubmission(TenantAndApplicationId id, ApplicationVersion version, long projectId) {
if (applications().getApplication(id).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring submission from project '" + projectId +
"': Unknown application '" + id + "'");
return;
}
applications().lockApplicationOrThrow(id, application -> {
if (acceptNewApplicationVersion(application.get())) {
application = application.withChange(application.get().change().with(version))
.withOutstandingChange(Change.empty());
if (application.get().internal())
for (Run run : jobs.active(id))
if ( ! run.id().type().environment().isManuallyDeployed())
jobs.abort(run.id());
}
else
application = application.withOutstandingChange(Change.of(version));
application = application.withProjectId(OptionalLong.of(projectId));
application = application.withNewSubmission(version);
applications().store(application.withChange(remainingChange(application.get())));
});
}
/**
* Records information when a job completes (successfully or not). This information is used when deciding what to
* trigger next.
*/
public void notifyOfCompletion(JobReport report) {
log.log(LogLevel.DEBUG, String.format("Notified of %s for %s of %s (%d)",
report.jobError().map(e -> e.toString() + " error")
.orElse("success"),
report.jobType(),
report.applicationId(),
report.projectId()));
if (applications().getInstance(report.applicationId()).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring completion of job of project '" + report.projectId() +
"': Unknown application '" + report.applicationId() + "'");
return;
}
applications().lockApplicationOrThrow(TenantAndApplicationId.from(report.applicationId()), application -> {
var status = application.get().require(report.applicationId().instance())
.deploymentJobs().statusOf(report.jobType());
var triggering = status.filter(job -> job.lastTriggered().isPresent()
&& job.lastCompleted()
.map(completion -> ! completion.at().isAfter(job.lastTriggered().get().at()))
.orElse(true))
.orElseThrow(() -> new IllegalStateException("Notified of completion of " + report.jobType().jobName() + " for " +
report.applicationId() + ", but that has not been triggered; last was " +
status.flatMap(job -> job.lastTriggered().map(run -> run.at().toString()))
.orElse("never")))
.lastTriggered().get();
application = application.with(report.applicationId().instance(),
instance -> instance.withJobCompletion(report.jobType(),
triggering.completion(report.buildNumber(), clock.instant()),
report.jobError()));
applications().store(application.withChange(remainingChange(application.get())));
});
}
/** Returns a map of jobs that are scheduled to be run, grouped by the job type */
public Map<JobType, ? extends List<? extends BuildJob>> jobsToRun() {
return computeReadyJobs().stream().collect(groupingBy(Job::jobType));
}
/**
* Finds and triggers jobs that can and should run but are currently not, and returns the number of triggered jobs.
*
* Only one job is triggered each run for test jobs, since their environments have limited capacity.
*/
public long triggerReadyJobs() {
return computeReadyJobs().stream()
.collect(partitioningBy(job -> job.jobType().isTest()))
.entrySet().stream()
.flatMap(entry -> (entry.getKey()
? entry.getValue().stream()
.sorted(comparing(Job::isRetry)
.thenComparing(Job::applicationUpgrade)
.reversed()
.thenComparing(Job::availableSince))
.collect(groupingBy(Job::jobType))
: entry.getValue().stream()
.collect(groupingBy(Job::applicationId)))
.values().stream()
.map(jobs -> (Supplier<Long>) jobs.stream()
.filter(this::trigger)
.limit(entry.getKey() ? 1 : Long.MAX_VALUE)::count))
.parallel().map(Supplier::get).reduce(0L, Long::sum);
}
/**
* Attempts to trigger the given job for the given application and returns the outcome.
*
* If the build service can not find the given job, or claims it is illegal to trigger it,
* the project id is removed from the application owning the job, to prevent further trigger attempts.
*/
public boolean trigger(Job job) {
log.log(LogLevel.DEBUG, String.format("Triggering %s: %s", job, job.triggering));
try {
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application -> {
if (application.get().internal())
jobs.start(job.applicationId(), job.jobType, new Versions(job.triggering.platform(),
job.triggering.application(),
job.triggering.sourcePlatform(),
job.triggering.sourceApplication()));
else
buildService.trigger(job);
applications().store(application.with(job.applicationId().instance(),
instance -> instance.withJobTriggering(job.jobType, job.triggering)));
});
return true;
}
catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception triggering " + job + ": " + e);
if (e instanceof NoSuchElementException || e instanceof IllegalArgumentException)
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application ->
applications().store(application.withProjectId(OptionalLong.empty())));
return false;
}
}
/** Force triggering of a job for given instance. */
public List<JobType> forceTrigger(ApplicationId applicationId, JobType jobType, String user) {
Application application = applications().requireApplication(TenantAndApplicationId.from(applicationId));
Instance instance = application.require(applicationId.instance());
Versions versions = Versions.from(application.change(), application, deploymentFor(instance, jobType),
controller.systemVersion());
String reason = "Job triggered manually by " + user;
var jobStatus = jobs.jobStatus(applicationId, application.deploymentSpec());
return (jobType.isProduction() && ! isTested(jobStatus, versions)
? testJobs(application.deploymentSpec(), application.change(), instance, jobStatus, versions, reason, clock.instant(), __ -> true).stream()
: Stream.of(deploymentJob(instance, versions, application.change(), jobType, jobStatus.get(jobType), reason, clock.instant())))
.peek(this::trigger)
.map(Job::jobType).collect(toList());
}
/** Prevents jobs of the given type from starting, until the given time. */
public void pauseJob(ApplicationId id, JobType jobType, Instant until) {
if (until.isAfter(clock.instant().plus(maxPause)))
throw new IllegalArgumentException("Pause only allowed for up to " + maxPause);
applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application ->
applications().store(application.with(id.instance(),
instance -> instance.withJobPause(jobType, OptionalLong.of(until.toEpochMilli())))));
}
/** Triggers a change of this application, unless it already has a change. */
public void triggerChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if ( ! application.get().change().hasTargets())
forceChange(applicationId, change);
});
}
/** Overrides the given application's platform and application changes with any contained in the given change. */
public void forceChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if (change.application().isPresent())
application = application.withOutstandingChange(Change.empty());
applications().store(application.withChange(change.onTopOf(application.get().change())));
});
}
/** Cancels the indicated part of the given application's change. */
public void cancelChange(TenantAndApplicationId applicationId, ChangesToCancel cancellation) {
applications().lockApplicationOrThrow(applicationId, application -> {
Change change;
switch (cancellation) {
case ALL: change = Change.empty(); break;
case VERSIONS: change = Change.empty().withPin(); break;
case PLATFORM: change = application.get().change().withoutPlatform(); break;
case APPLICATION: change = application.get().change().withoutApplication(); break;
case PIN: change = application.get().change().withoutPin(); break;
default: throw new IllegalArgumentException("Unknown cancellation choice '" + cancellation + "'!");
}
applications().store(application.withChange(change));
});
}
public enum ChangesToCancel { ALL, PLATFORM, APPLICATION, VERSIONS, PIN }
private ApplicationController applications() {
return controller.applications();
}
private Optional<Run> successOn(JobStatus status, Versions versions) {
return status.lastSuccess().filter(run -> versions.targetsMatch(run.versions()));
}
private Optional<Deployment> deploymentFor(Instance instance, JobType jobType) {
return Optional.ofNullable(instance.deployments().get(jobType.zone(controller.system())));
}
private static <T extends Comparable<T>> Optional<T> max(Optional<T> o1, Optional<T> o2) {
return o1.isEmpty() ? o2 : o2.isEmpty() ? o1 : o1.get().compareTo(o2.get()) >= 0 ? o1 : o2;
}
/** Returns the set of all jobs which have changes to propagate from the upstream steps. */
private List<Job> computeReadyJobs() {
return ApplicationList.from(applications().asList())
.withProjectId()
.withChanges()
.withDeploymentSpec()
.idList().stream()
.map(this::computeReadyJobs)
.flatMap(Collection::stream)
.collect(toList());
}
/**
* Finds the next step to trigger for the given application, if any, and returns these as a list.
*/
private List<Job> computeReadyJobs(TenantAndApplicationId id) {
List<Job> jobs = new ArrayList<>();
applications().getApplication(id).ifPresent(application -> {
Collection<Instance> instances = application.deploymentSpec().instances().stream()
.flatMap(instance -> application.get(instance.name()).stream())
.collect(Collectors.toUnmodifiableList());
for (Instance instance : instances) {
var jobStatus = this.jobs.jobStatus(instance.id(), application.deploymentSpec());
Change change = application.change();
Optional<Instant> completedAt = max(Optional.ofNullable(jobStatus.get(systemTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())),
Optional.ofNullable(jobStatus.get(stagingTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())));
String reason = "New change available";
List<Job> testJobs = null;
DeploymentSteps steps = steps(application.deploymentSpec().requireInstance(instance.name()));
if (change.hasTargets()) {
for (Step step : steps.production()) {
List<JobType> stepJobs = steps.toJobs(step);
List<JobType> remainingJobs = stepJobs.stream().filter(job -> ! isComplete(change, change, instance, job, jobStatus.get(job))).collect(toList());
if ( ! remainingJobs.isEmpty()) {
for (JobType job : remainingJobs) {
Versions versions = Versions.from(change, application, deploymentFor(instance, job),
controller.systemVersion());
if (isTested(jobStatus, versions)) {
if (completedAt.isPresent() && canTrigger(job, jobStatus, versions, instance, application.deploymentSpec(), stepJobs)) {
jobs.add(deploymentJob(instance, versions, change, job, jobStatus.get(job), reason, completedAt.get()));
}
if ( ! alreadyTriggered(jobStatus, versions) && testJobs == null) {
testJobs = emptyList();
}
}
else if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(),
change, instance, jobStatus, versions,
String.format("Testing deployment for %s (%s)",
job.jobName(), versions.toString()),
completedAt.orElseGet(clock::instant));
}
}
completedAt = Optional.empty();
}
else {
if (stepJobs.isEmpty()) {
completedAt = completedAt.map(at -> at.plus(step.delay())).filter(at -> ! at.isAfter(clock.instant()));
reason += " after a delay of " + step.delay();
}
else {
completedAt = stepJobs.stream().map(job -> jobStatus.get(job).lastCompleted().get().end().get()).max(naturalOrder());
reason = "Available change in " + stepJobs.stream().map(JobType::jobName).collect(joining(", "));
}
}
}
}
if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(), change, instance, jobStatus,
Versions.from(application.outstandingChange().onTopOf(change),
application,
steps.sortedDeployments(instance.productionDeployments().values()).stream().findFirst(),
controller.systemVersion()),
"Testing last changes outside prod", clock.instant());
}
jobs.addAll(testJobs);
}
});
return Collections.unmodifiableList(jobs);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec, List<JobType> parallelJobs) {
if (status.get(job).isRunning()) return false;
if (parallelJobs != null && ! parallelJobs.containsAll(runningProductionJobs(status))) return false;
if (job.isProduction() && isSuspendedInAnotherZone(instance, job.zone(controller.system()))) return false;
return triggerAt(clock.instant(), job, status.get(job), versions, instance, deploymentSpec);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
return canTrigger(job, status, versions, instance, deploymentSpec, null);
}
private boolean isSuspendedInAnotherZone(Instance instance, ZoneId zone) {
for (Deployment deployment : instance.productionDeployments().values()) {
if ( ! deployment.zone().equals(zone)
&& controller.applications().isSuspended(new DeploymentId(instance.id(), deployment.zone())))
return true;
}
return false;
}
/** Returns whether the given job can trigger at the given instant */
private List<JobType> runningProductionJobs(Map<JobType, JobStatus> status) {
return status.values().parallelStream()
.filter(job -> job.isRunning())
.map(job -> job.job().type())
.filter(JobType::isProduction)
.collect(toList());
}
/**
* Returns whether the given change is complete for the given application for the given job.
*
* Any job is complete if the given change is already successful on that job.
* A production job is also considered complete if its current change is strictly dominated by what
* is already deployed in its zone, i.e., no parts of the change are upgrades, and the full current
* change for the application downgrades the deployment, which is an acknowledgement that the deployed
* version is broken somehow, such that the job may be locked in failure until a new version is released.
*
* Additionally, if the application is pinned to a Vespa version, and the given change has a (this) platform,
* the deployment for the job must be on the pinned version.
*/
public boolean isComplete(Change change, Change fullChange, Instance instance, JobType jobType,
JobStatus status) {
Optional<Deployment> existingDeployment = deploymentFor(instance, jobType);
if ( change.isPinned()
&& change.platform().isPresent()
&& ! existingDeployment.map(Deployment::version).equals(change.platform()))
return false;
return status.lastSuccess()
.map(run -> change.platform().map(run.versions().targetPlatform()::equals).orElse(true)
&& change.application().map(run.versions().targetApplication()::equals).orElse(true))
.orElse(false)
|| jobType.isProduction()
&& existingDeployment.map(deployment -> ! isUpgrade(change, deployment) && isDowngrade(fullChange, deployment))
.orElse(false);
}
private static boolean isUpgrade(Change change, Deployment deployment) {
return change.upgrades(deployment.version()) || change.upgrades(deployment.applicationVersion());
}
private static boolean isDowngrade(Change change, Deployment deployment) {
return change.downgrades(deployment.version()) || change.downgrades(deployment.applicationVersion());
}
private boolean isTested(Map<JobType, JobStatus> status, Versions versions) {
return testedIn(systemTest, status.get(systemTest), versions)
&& testedIn(stagingTest, status.get(stagingTest), versions)
|| alreadyTriggered(status, versions);
}
public boolean testedIn(JobType testType, JobStatus status, Versions versions) {
if (testType == systemTest)
return successOn(status, versions).isPresent();
if (testType == stagingTest)
return successOn(status, versions).map(Run::versions).filter(versions::sourcesMatchIfPresent).isPresent();
throw new IllegalArgumentException(testType + " is not a test job!");
}
public boolean alreadyTriggered(Map<JobType, JobStatus> status, Versions versions) {
return status.values().stream()
.filter(job -> job.job().type().isProduction())
.anyMatch(job -> job.lastTriggered()
.map(Run::versions)
.filter(versions::targetsMatch)
.filter(versions::sourcesMatchIfPresent)
.isPresent());
}
private boolean acceptNewApplicationVersion(Application application) {
if ( ! application.deploymentSpec().instances().stream()
.allMatch(instance -> instance.canChangeRevisionAt(clock.instant()))) return false;
if (application.change().application().isPresent()) return true;
for (Instance instance : application.instances().values())
if (instance.deploymentJobs().hasFailures()) return true;
return application.change().platform().isEmpty();
}
private Change remainingChange(Application application) {
Change change = application.change();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutApplication(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutPlatform();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutPlatform(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutApplication();
return change;
}
/**
* Returns the list of test jobs that should run now, and that need to succeed on the given versions for it to be considered tested.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince) {
return testJobs(deploymentSpec, change, instance, status, versions, reason, availableSince,
jobType -> canTrigger(jobType, status, versions, instance, deploymentSpec));
}
/**
* Returns the list of test jobs that need to succeed on the given versions for it to be considered tested, filtered by the given condition.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince, Predicate<JobType> condition) {
List<Job> jobs = new ArrayList<>();
for (JobType jobType : new DeploymentSteps(deploymentSpec.requireInstance(instance.name()), controller::system).testJobs()) {
Optional<Run> completion = successOn(status.get(jobType), versions)
.filter(run -> versions.sourcesMatchIfPresent(run.versions()) || jobType == systemTest);
if (completion.isEmpty() && condition.test(jobType))
jobs.add(deploymentJob(instance, versions, change, jobType, status.get(jobType), reason, availableSince));
}
return jobs;
}
private Job deploymentJob(Instance instance, Versions versions, Change change, JobType jobType, JobStatus jobStatus, String reason, Instant availableSince) {
if (jobStatus.isOutOfCapacity()) reason += "; retrying on out of capacity";
var triggering = JobRun.triggering(versions.targetPlatform(), versions.targetApplication(),
versions.sourcePlatform(), versions.sourceApplication(),
reason, clock.instant());
return new Job(instance, triggering, jobType, availableSince, jobStatus.isOutOfCapacity(), change.application().isPresent());
}
private static class Job extends BuildJob {
private final JobType jobType;
private final JobRun triggering;
private final Instant availableSince;
private final boolean isRetry;
private final boolean isApplicationUpgrade;
private Job(Instance instance, JobRun triggering, JobType jobType, Instant availableSince,
boolean isRetry, boolean isApplicationUpgrade) {
super(instance.id(), 0L, jobType.jobName());
this.jobType = jobType;
this.triggering = triggering;
this.availableSince = availableSince;
this.isRetry = isRetry;
this.isApplicationUpgrade = isApplicationUpgrade;
}
JobType jobType() { return jobType; }
Instant availableSince() { return availableSince; }
boolean isRetry() { return isRetry; }
boolean applicationUpgrade() { return isApplicationUpgrade; }
}
} | class DeploymentTrigger {
public static final Duration maxPause = Duration.ofDays(3);
private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName());
private final Controller controller;
private final Clock clock;
private final JobController jobs;
public DeploymentTrigger(Controller controller, Clock clock) {
this.controller = Objects.requireNonNull(controller, "controller cannot be null");
this.clock = Objects.requireNonNull(clock, "clock cannot be null");
this.jobs = controller.jobController();
}
public DeploymentSteps steps(DeploymentInstanceSpec spec) {
return new DeploymentSteps(spec, controller::system);
}
public void notifyOfSubmission(TenantAndApplicationId id, ApplicationVersion version, long projectId) {
if (applications().getApplication(id).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring submission from project '" + projectId +
"': Unknown application '" + id + "'");
return;
}
applications().lockApplicationOrThrow(id, application -> {
if (acceptNewApplicationVersion(application.get())) {
application = application.withChange(application.get().change().with(version))
.withOutstandingChange(Change.empty());
for (Run run : jobs.active(id))
if ( ! run.id().type().environment().isManuallyDeployed())
jobs.abort(run.id());
}
else
application = application.withOutstandingChange(Change.of(version));
application = application.withProjectId(OptionalLong.of(projectId));
application = application.withNewSubmission(version);
applications().store(application.withChange(remainingChange(application.get())));
});
}
/**
* Records information when a job completes (successfully or not). This information is used when deciding what to
* trigger next.
*/
public void notifyOfCompletion(JobReport report) {
log.log(LogLevel.DEBUG, String.format("Notified of %s for %s of %s (%d)",
report.jobError().map(e -> e.toString() + " error")
.orElse("success"),
report.jobType(),
report.applicationId(),
report.projectId()));
if (applications().getInstance(report.applicationId()).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring completion of job of project '" + report.projectId() +
"': Unknown application '" + report.applicationId() + "'");
return;
}
applications().lockApplicationOrThrow(TenantAndApplicationId.from(report.applicationId()), application -> {
var status = application.get().require(report.applicationId().instance())
.deploymentJobs().statusOf(report.jobType());
var triggering = status.filter(job -> job.lastTriggered().isPresent()
&& job.lastCompleted()
.map(completion -> ! completion.at().isAfter(job.lastTriggered().get().at()))
.orElse(true))
.orElseThrow(() -> new IllegalStateException("Notified of completion of " + report.jobType().jobName() + " for " +
report.applicationId() + ", but that has not been triggered; last was " +
status.flatMap(job -> job.lastTriggered().map(run -> run.at().toString()))
.orElse("never")))
.lastTriggered().get();
application = application.with(report.applicationId().instance(),
instance -> instance.withJobCompletion(report.jobType(),
triggering.completion(report.buildNumber(), clock.instant()),
report.jobError()));
applications().store(application.withChange(remainingChange(application.get())));
});
}
/**
* Finds and triggers jobs that can and should run but are currently not, and returns the number of triggered jobs.
*
* Only one job is triggered each run for test jobs, since their environments have limited capacity.
*/
public long triggerReadyJobs() {
return computeReadyJobs().stream()
.collect(partitioningBy(job -> job.jobType().isTest()))
.entrySet().stream()
.flatMap(entry -> (entry.getKey()
? entry.getValue().stream()
.sorted(comparing(Job::isRetry)
.thenComparing(Job::applicationUpgrade)
.reversed()
.thenComparing(Job::availableSince))
.collect(groupingBy(Job::jobType))
: entry.getValue().stream()
.collect(groupingBy(Job::applicationId)))
.values().stream()
.map(jobs -> (Supplier<Long>) jobs.stream()
.filter(this::trigger)
.limit(entry.getKey() ? 1 : Long.MAX_VALUE)::count))
.parallel().map(Supplier::get).reduce(0L, Long::sum);
}
/**
* Attempts to trigger the given job for the given application and returns the outcome.
*
* If the build service can not find the given job, or claims it is illegal to trigger it,
* the project id is removed from the application owning the job, to prevent further trigger attempts.
*/
public boolean trigger(Job job) {
log.log(LogLevel.DEBUG, String.format("Triggering %s: %s", job, job.triggering));
try {
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application -> {
jobs.start(job.applicationId(), job.jobType, new Versions(job.triggering.platform(),
job.triggering.application(),
job.triggering.sourcePlatform(),
job.triggering.sourceApplication()));
applications().store(application.with(job.applicationId().instance(),
instance -> instance.withJobTriggering(job.jobType, job.triggering)));
});
return true;
}
catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception triggering " + job + ": " + e);
if (e instanceof NoSuchElementException || e instanceof IllegalArgumentException)
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application ->
applications().store(application.withProjectId(OptionalLong.empty())));
return false;
}
}
/** Force triggering of a job for given instance. */
public List<JobType> forceTrigger(ApplicationId applicationId, JobType jobType, String user) {
Application application = applications().requireApplication(TenantAndApplicationId.from(applicationId));
Instance instance = application.require(applicationId.instance());
Versions versions = Versions.from(application.change(), application, deploymentFor(instance, jobType),
controller.systemVersion());
String reason = "Job triggered manually by " + user;
var jobStatus = jobs.deploymentStatus(application).instanceJobs(instance.name());
return (jobType.isProduction() && ! isTested(jobStatus, versions)
? testJobs(application.deploymentSpec(), application.change(), instance, jobStatus, versions, reason, clock.instant(), __ -> true).stream()
: Stream.of(deploymentJob(instance, versions, application.change(), jobType, jobStatus.get(jobType), reason, clock.instant())))
.peek(this::trigger)
.map(Job::jobType).collect(toList());
}
/** Prevents jobs of the given type from starting, until the given time. */
public void pauseJob(ApplicationId id, JobType jobType, Instant until) {
if (until.isAfter(clock.instant().plus(maxPause)))
throw new IllegalArgumentException("Pause only allowed for up to " + maxPause);
applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application ->
applications().store(application.with(id.instance(),
instance -> instance.withJobPause(jobType, OptionalLong.of(until.toEpochMilli())))));
}
/** Triggers a change of this application, unless it already has a change. */
public void triggerChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if ( ! application.get().change().hasTargets())
forceChange(applicationId, change);
});
}
/** Overrides the given application's platform and application changes with any contained in the given change. */
public void forceChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if (change.application().isPresent())
application = application.withOutstandingChange(Change.empty());
applications().store(application.withChange(change.onTopOf(application.get().change())));
});
}
/** Cancels the indicated part of the given application's change. */
public void cancelChange(TenantAndApplicationId applicationId, ChangesToCancel cancellation) {
applications().lockApplicationOrThrow(applicationId, application -> {
Change change;
switch (cancellation) {
case ALL: change = Change.empty(); break;
case VERSIONS: change = Change.empty().withPin(); break;
case PLATFORM: change = application.get().change().withoutPlatform(); break;
case APPLICATION: change = application.get().change().withoutApplication(); break;
case PIN: change = application.get().change().withoutPin(); break;
default: throw new IllegalArgumentException("Unknown cancellation choice '" + cancellation + "'!");
}
applications().store(application.withChange(change));
});
}
public enum ChangesToCancel { ALL, PLATFORM, APPLICATION, VERSIONS, PIN }
private ApplicationController applications() {
return controller.applications();
}
private Optional<Run> successOn(JobStatus status, Versions versions) {
return status.lastSuccess().filter(run -> versions.targetsMatch(run.versions()));
}
private Optional<Deployment> deploymentFor(Instance instance, JobType jobType) {
return Optional.ofNullable(instance.deployments().get(jobType.zone(controller.system())));
}
private static <T extends Comparable<T>> Optional<T> max(Optional<T> o1, Optional<T> o2) {
return o1.isEmpty() ? o2 : o2.isEmpty() ? o1 : o1.get().compareTo(o2.get()) >= 0 ? o1 : o2;
}
/** Returns the set of all jobs which have changes to propagate from the upstream steps. */
private List<Job> computeReadyJobs() {
return ApplicationList.from(applications().asList())
.withProjectId()
.withChanges()
.withDeploymentSpec()
.idList().stream()
.map(this::computeReadyJobs)
.flatMap(Collection::stream)
.collect(toList());
}
/**
* Finds the next step to trigger for the given application, if any, and returns these as a list.
*/
private List<Job> computeReadyJobs(TenantAndApplicationId id) {
List<Job> jobs = new ArrayList<>();
applications().getApplication(id).ifPresent(application -> {
Collection<Instance> instances = application.deploymentSpec().instances().stream()
.flatMap(instance -> application.get(instance.name()).stream())
.collect(Collectors.toUnmodifiableList());
DeploymentStatus deploymentStatus = this.jobs.deploymentStatus(application);
for (Instance instance : instances) {
var jobStatus = deploymentStatus.instanceJobs(instance.name());
Change change = application.change();
Optional<Instant> completedAt = max(Optional.ofNullable(jobStatus.get(systemTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())),
Optional.ofNullable(jobStatus.get(stagingTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())));
String reason = "New change available";
List<Job> testJobs = null;
DeploymentSteps steps = steps(application.deploymentSpec().requireInstance(instance.name()));
if (change.hasTargets()) {
for (Step step : steps.production()) {
List<JobType> stepJobs = steps.toJobs(step);
List<JobType> remainingJobs = stepJobs.stream().filter(job -> ! isComplete(change, change, instance, job, jobStatus.get(job))).collect(toList());
if ( ! remainingJobs.isEmpty()) {
for (JobType job : remainingJobs) {
Versions versions = Versions.from(change, application, deploymentFor(instance, job),
controller.systemVersion());
if (isTested(jobStatus, versions)) {
if (completedAt.isPresent() && canTrigger(job, jobStatus, versions, instance, application.deploymentSpec(), stepJobs)) {
jobs.add(deploymentJob(instance, versions, change, job, jobStatus.get(job), reason, completedAt.get()));
}
if ( ! alreadyTriggered(jobStatus, versions) && testJobs == null) {
testJobs = emptyList();
}
}
else if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(),
change, instance, jobStatus, versions,
String.format("Testing deployment for %s (%s)",
job.jobName(), versions.toString()),
completedAt.orElseGet(clock::instant));
}
}
completedAt = Optional.empty();
}
else {
if (stepJobs.isEmpty()) {
completedAt = completedAt.map(at -> at.plus(step.delay())).filter(at -> ! at.isAfter(clock.instant()));
reason += " after a delay of " + step.delay();
}
else {
completedAt = stepJobs.stream().map(job -> jobStatus.get(job).lastCompleted().get().end().get()).max(naturalOrder());
reason = "Available change in " + stepJobs.stream().map(JobType::jobName).collect(joining(", "));
}
}
}
}
if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(), change, instance, jobStatus,
Versions.from(application.outstandingChange().onTopOf(change),
application,
steps.sortedDeployments(instance.productionDeployments().values()).stream().findFirst(),
controller.systemVersion()),
"Testing last changes outside prod", clock.instant());
}
jobs.addAll(testJobs);
}
});
return Collections.unmodifiableList(jobs);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec, List<JobType> parallelJobs) {
if (status.get(job).isRunning()) return false;
if (parallelJobs != null && ! parallelJobs.containsAll(runningProductionJobs(status))) return false;
if (job.isProduction() && isSuspendedInAnotherZone(instance, job.zone(controller.system()))) return false;
return triggerAt(clock.instant(), job, status.get(job), versions, instance, deploymentSpec);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
return canTrigger(job, status, versions, instance, deploymentSpec, null);
}
private boolean isSuspendedInAnotherZone(Instance instance, ZoneId zone) {
for (Deployment deployment : instance.productionDeployments().values()) {
if ( ! deployment.zone().equals(zone)
&& controller.applications().isSuspended(new DeploymentId(instance.id(), deployment.zone())))
return true;
}
return false;
}
/** Returns whether the given job can trigger at the given instant */
private List<JobType> runningProductionJobs(Map<JobType, JobStatus> status) {
return status.values().parallelStream()
.filter(job -> job.isRunning())
.map(job -> job.id().type())
.filter(JobType::isProduction)
.collect(toList());
}
/**
* Returns whether the given change is complete for the given application for the given job.
*
* Any job is complete if the given change is already successful on that job.
* A production job is also considered complete if its current change is strictly dominated by what
* is already deployed in its zone, i.e., no parts of the change are upgrades, and the full current
* change for the application downgrades the deployment, which is an acknowledgement that the deployed
* version is broken somehow, such that the job may be locked in failure until a new version is released.
*
* Additionally, if the application is pinned to a Vespa version, and the given change has a (this) platform,
* the deployment for the job must be on the pinned version.
*/
public boolean isComplete(Change change, Change fullChange, Instance instance, JobType jobType,
JobStatus status) {
Optional<Deployment> existingDeployment = deploymentFor(instance, jobType);
if ( change.isPinned()
&& change.platform().isPresent()
&& ! existingDeployment.map(Deployment::version).equals(change.platform()))
return false;
return status.lastSuccess()
.map(run -> change.platform().map(run.versions().targetPlatform()::equals).orElse(true)
&& change.application().map(run.versions().targetApplication()::equals).orElse(true))
.orElse(false)
|| jobType.isProduction()
&& existingDeployment.map(deployment -> ! isUpgrade(change, deployment) && isDowngrade(fullChange, deployment))
.orElse(false);
}
private static boolean isUpgrade(Change change, Deployment deployment) {
return change.upgrades(deployment.version()) || change.upgrades(deployment.applicationVersion());
}
private static boolean isDowngrade(Change change, Deployment deployment) {
return change.downgrades(deployment.version()) || change.downgrades(deployment.applicationVersion());
}
private boolean isTested(Map<JobType, JobStatus> status, Versions versions) {
return testedIn(systemTest, status.get(systemTest), versions)
&& testedIn(stagingTest, status.get(stagingTest), versions)
|| alreadyTriggered(status, versions);
}
public boolean testedIn(JobType testType, JobStatus status, Versions versions) {
if (testType == systemTest)
return successOn(status, versions).isPresent();
if (testType == stagingTest)
return successOn(status, versions).map(Run::versions).filter(versions::sourcesMatchIfPresent).isPresent();
throw new IllegalArgumentException(testType + " is not a test job!");
}
public boolean alreadyTriggered(Map<JobType, JobStatus> status, Versions versions) {
return status.values().stream()
.filter(job -> job.id().type().isProduction())
.anyMatch(job -> job.lastTriggered()
.map(Run::versions)
.filter(versions::targetsMatch)
.filter(versions::sourcesMatchIfPresent)
.isPresent());
}
private boolean acceptNewApplicationVersion(Application application) {
if ( ! application.deploymentSpec().instances().stream()
.allMatch(instance -> instance.canChangeRevisionAt(clock.instant()))) return false;
if (application.change().application().isPresent()) return true;
for (Instance instance : application.instances().values())
if (instance.deploymentJobs().hasFailures()) return true;
return application.change().platform().isEmpty();
}
private Change remainingChange(Application application) {
Change change = application.change();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutApplication(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutPlatform();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutPlatform(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutApplication();
return change;
}
/**
* Returns the list of test jobs that should run now, and that need to succeed on the given versions for it to be considered tested.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince) {
return testJobs(deploymentSpec, change, instance, status, versions, reason, availableSince,
jobType -> canTrigger(jobType, status, versions, instance, deploymentSpec));
}
/**
* Returns the list of test jobs that need to succeed on the given versions for it to be considered tested, filtered by the given condition.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince, Predicate<JobType> condition) {
List<Job> jobs = new ArrayList<>();
for (JobType jobType : new DeploymentSteps(deploymentSpec.requireInstance(instance.name()), controller::system).testJobs()) {
Optional<Run> completion = successOn(status.get(jobType), versions)
.filter(run -> versions.sourcesMatchIfPresent(run.versions()) || jobType == systemTest);
if (completion.isEmpty() && condition.test(jobType))
jobs.add(deploymentJob(instance, versions, change, jobType, status.get(jobType), reason, availableSince));
}
return jobs;
}
private Job deploymentJob(Instance instance, Versions versions, Change change, JobType jobType, JobStatus jobStatus, String reason, Instant availableSince) {
if (jobStatus.isOutOfCapacity()) reason += "; retrying on out of capacity";
var triggering = JobRun.triggering(versions.targetPlatform(), versions.targetApplication(),
versions.sourcePlatform(), versions.sourceApplication(),
reason, clock.instant());
return new Job(instance, triggering, jobType, availableSince, jobStatus.isOutOfCapacity(), change.application().isPresent());
}
private static class Job {
private final ApplicationId instanceId;
private final JobType jobType;
private final JobRun triggering;
private final Instant availableSince;
private final boolean isRetry;
private final boolean isApplicationUpgrade;
private Job(Instance instance, JobRun triggering, JobType jobType, Instant availableSince,
boolean isRetry, boolean isApplicationUpgrade) {
this.instanceId = instance.id();
this.jobType = jobType;
this.triggering = triggering;
this.availableSince = availableSince;
this.isRetry = isRetry;
this.isApplicationUpgrade = isApplicationUpgrade;
}
ApplicationId applicationId() { return instanceId; }
JobType jobType() { return jobType; }
Instant availableSince() { return availableSince; }
boolean isRetry() { return isRetry; }
boolean applicationUpgrade() { return isApplicationUpgrade; }
}
} |
Nit: Alignment. | private Job deploymentJob(Instance instance, Versions versions, Change change, JobType jobType, JobStatus jobStatus, String reason, Instant availableSince) {
if (jobStatus.isOutOfCapacity()) reason += "; retrying on out of capacity";
var triggering = JobRun.triggering(versions.targetPlatform(), versions.targetApplication(),
versions.sourcePlatform(), versions.sourceApplication(),
reason, clock.instant());
return new Job(instance, triggering, jobType, availableSince, jobStatus.isOutOfCapacity(), change.application().isPresent());
} | versions.sourcePlatform(), versions.sourceApplication(), | private Job deploymentJob(Instance instance, Versions versions, Change change, JobType jobType, JobStatus jobStatus, String reason, Instant availableSince) {
if (jobStatus.isOutOfCapacity()) reason += "; retrying on out of capacity";
var triggering = JobRun.triggering(versions.targetPlatform(), versions.targetApplication(),
versions.sourcePlatform(), versions.sourceApplication(),
reason, clock.instant());
return new Job(instance, triggering, jobType, availableSince, jobStatus.isOutOfCapacity(), change.application().isPresent());
} | class DeploymentTrigger {
/*
* Instance orchestration TODO jonmv.
* Store new production application packages under non-instance path
* Read production packages from non-instance path, with fallback
* Deprecate and redirect some instance qualified paths in application/v4
* Orchestrate deployment across instances.
*/
public static final Duration maxPause = Duration.ofDays(3);
private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName());
private final Controller controller;
private final Clock clock;
private final BuildService buildService;
private final JobController jobs;
public DeploymentTrigger(Controller controller, BuildService buildService, Clock clock) {
this.controller = Objects.requireNonNull(controller, "controller cannot be null");
this.clock = Objects.requireNonNull(clock, "clock cannot be null");
this.buildService = Objects.requireNonNull(buildService, "buildService cannot be null");
this.jobs = controller.jobController();
}
public DeploymentSteps steps(DeploymentInstanceSpec spec) {
return new DeploymentSteps(spec, controller::system);
}
public void notifyOfSubmission(TenantAndApplicationId id, ApplicationVersion version, long projectId) {
if (applications().getApplication(id).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring submission from project '" + projectId +
"': Unknown application '" + id + "'");
return;
}
applications().lockApplicationOrThrow(id, application -> {
if (acceptNewApplicationVersion(application.get())) {
application = application.withChange(application.get().change().with(version))
.withOutstandingChange(Change.empty());
if (application.get().internal())
for (Run run : jobs.active(id))
if ( ! run.id().type().environment().isManuallyDeployed())
jobs.abort(run.id());
}
else
application = application.withOutstandingChange(Change.of(version));
application = application.withProjectId(OptionalLong.of(projectId));
application = application.withNewSubmission(version);
applications().store(application.withChange(remainingChange(application.get())));
});
}
/**
* Records information when a job completes (successfully or not). This information is used when deciding what to
* trigger next.
*/
public void notifyOfCompletion(JobReport report) {
log.log(LogLevel.DEBUG, String.format("Notified of %s for %s of %s (%d)",
report.jobError().map(e -> e.toString() + " error")
.orElse("success"),
report.jobType(),
report.applicationId(),
report.projectId()));
if (applications().getInstance(report.applicationId()).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring completion of job of project '" + report.projectId() +
"': Unknown application '" + report.applicationId() + "'");
return;
}
applications().lockApplicationOrThrow(TenantAndApplicationId.from(report.applicationId()), application -> {
var status = application.get().require(report.applicationId().instance())
.deploymentJobs().statusOf(report.jobType());
var triggering = status.filter(job -> job.lastTriggered().isPresent()
&& job.lastCompleted()
.map(completion -> ! completion.at().isAfter(job.lastTriggered().get().at()))
.orElse(true))
.orElseThrow(() -> new IllegalStateException("Notified of completion of " + report.jobType().jobName() + " for " +
report.applicationId() + ", but that has not been triggered; last was " +
status.flatMap(job -> job.lastTriggered().map(run -> run.at().toString()))
.orElse("never")))
.lastTriggered().get();
application = application.with(report.applicationId().instance(),
instance -> instance.withJobCompletion(report.jobType(),
triggering.completion(report.buildNumber(), clock.instant()),
report.jobError()));
applications().store(application.withChange(remainingChange(application.get())));
});
}
/** Returns a map of jobs that are scheduled to be run, grouped by the job type */
public Map<JobType, ? extends List<? extends BuildJob>> jobsToRun() {
return computeReadyJobs().stream().collect(groupingBy(Job::jobType));
}
/**
* Finds and triggers jobs that can and should run but are currently not, and returns the number of triggered jobs.
*
* Only one job is triggered each run for test jobs, since their environments have limited capacity.
*/
public long triggerReadyJobs() {
return computeReadyJobs().stream()
.collect(partitioningBy(job -> job.jobType().isTest()))
.entrySet().stream()
.flatMap(entry -> (entry.getKey()
? entry.getValue().stream()
.sorted(comparing(Job::isRetry)
.thenComparing(Job::applicationUpgrade)
.reversed()
.thenComparing(Job::availableSince))
.collect(groupingBy(Job::jobType))
: entry.getValue().stream()
.collect(groupingBy(Job::applicationId)))
.values().stream()
.map(jobs -> (Supplier<Long>) jobs.stream()
.filter(this::trigger)
.limit(entry.getKey() ? 1 : Long.MAX_VALUE)::count))
.parallel().map(Supplier::get).reduce(0L, Long::sum);
}
/**
* Attempts to trigger the given job for the given application and returns the outcome.
*
* If the build service can not find the given job, or claims it is illegal to trigger it,
* the project id is removed from the application owning the job, to prevent further trigger attempts.
*/
public boolean trigger(Job job) {
log.log(LogLevel.DEBUG, String.format("Triggering %s: %s", job, job.triggering));
try {
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application -> {
if (application.get().internal())
jobs.start(job.applicationId(), job.jobType, new Versions(job.triggering.platform(),
job.triggering.application(),
job.triggering.sourcePlatform(),
job.triggering.sourceApplication()));
else
buildService.trigger(job);
applications().store(application.with(job.applicationId().instance(),
instance -> instance.withJobTriggering(job.jobType, job.triggering)));
});
return true;
}
catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception triggering " + job + ": " + e);
if (e instanceof NoSuchElementException || e instanceof IllegalArgumentException)
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application ->
applications().store(application.withProjectId(OptionalLong.empty())));
return false;
}
}
/** Force triggering of a job for given instance. */
public List<JobType> forceTrigger(ApplicationId applicationId, JobType jobType, String user) {
Application application = applications().requireApplication(TenantAndApplicationId.from(applicationId));
Instance instance = application.require(applicationId.instance());
Versions versions = Versions.from(application.change(), application, deploymentFor(instance, jobType),
controller.systemVersion());
String reason = "Job triggered manually by " + user;
var jobStatus = jobs.jobStatus(applicationId, application.deploymentSpec());
return (jobType.isProduction() && ! isTested(jobStatus, versions)
? testJobs(application.deploymentSpec(), application.change(), instance, jobStatus, versions, reason, clock.instant(), __ -> true).stream()
: Stream.of(deploymentJob(instance, versions, application.change(), jobType, jobStatus.get(jobType), reason, clock.instant())))
.peek(this::trigger)
.map(Job::jobType).collect(toList());
}
/** Prevents jobs of the given type from starting, until the given time. */
public void pauseJob(ApplicationId id, JobType jobType, Instant until) {
if (until.isAfter(clock.instant().plus(maxPause)))
throw new IllegalArgumentException("Pause only allowed for up to " + maxPause);
applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application ->
applications().store(application.with(id.instance(),
instance -> instance.withJobPause(jobType, OptionalLong.of(until.toEpochMilli())))));
}
/** Triggers a change of this application, unless it already has a change. */
public void triggerChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if ( ! application.get().change().hasTargets())
forceChange(applicationId, change);
});
}
/** Overrides the given application's platform and application changes with any contained in the given change. */
public void forceChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if (change.application().isPresent())
application = application.withOutstandingChange(Change.empty());
applications().store(application.withChange(change.onTopOf(application.get().change())));
});
}
/** Cancels the indicated part of the given application's change. */
public void cancelChange(TenantAndApplicationId applicationId, ChangesToCancel cancellation) {
applications().lockApplicationOrThrow(applicationId, application -> {
Change change;
switch (cancellation) {
case ALL: change = Change.empty(); break;
case VERSIONS: change = Change.empty().withPin(); break;
case PLATFORM: change = application.get().change().withoutPlatform(); break;
case APPLICATION: change = application.get().change().withoutApplication(); break;
case PIN: change = application.get().change().withoutPin(); break;
default: throw new IllegalArgumentException("Unknown cancellation choice '" + cancellation + "'!");
}
applications().store(application.withChange(change));
});
}
public enum ChangesToCancel { ALL, PLATFORM, APPLICATION, VERSIONS, PIN }
private ApplicationController applications() {
return controller.applications();
}
private Optional<Run> successOn(JobStatus status, Versions versions) {
return status.lastSuccess().filter(run -> versions.targetsMatch(run.versions()));
}
private Optional<Deployment> deploymentFor(Instance instance, JobType jobType) {
return Optional.ofNullable(instance.deployments().get(jobType.zone(controller.system())));
}
private static <T extends Comparable<T>> Optional<T> max(Optional<T> o1, Optional<T> o2) {
return o1.isEmpty() ? o2 : o2.isEmpty() ? o1 : o1.get().compareTo(o2.get()) >= 0 ? o1 : o2;
}
/** Returns the set of all jobs which have changes to propagate from the upstream steps. */
private List<Job> computeReadyJobs() {
return ApplicationList.from(applications().asList())
.withProjectId()
.withChanges()
.withDeploymentSpec()
.idList().stream()
.map(this::computeReadyJobs)
.flatMap(Collection::stream)
.collect(toList());
}
/**
* Finds the next step to trigger for the given application, if any, and returns these as a list.
*/
private List<Job> computeReadyJobs(TenantAndApplicationId id) {
List<Job> jobs = new ArrayList<>();
applications().getApplication(id).ifPresent(application -> {
Collection<Instance> instances = application.deploymentSpec().instances().stream()
.flatMap(instance -> application.get(instance.name()).stream())
.collect(Collectors.toUnmodifiableList());
for (Instance instance : instances) {
var jobStatus = this.jobs.jobStatus(instance.id(), application.deploymentSpec());
Change change = application.change();
Optional<Instant> completedAt = max(Optional.ofNullable(jobStatus.get(systemTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())),
Optional.ofNullable(jobStatus.get(stagingTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())));
String reason = "New change available";
List<Job> testJobs = null;
DeploymentSteps steps = steps(application.deploymentSpec().requireInstance(instance.name()));
if (change.hasTargets()) {
for (Step step : steps.production()) {
List<JobType> stepJobs = steps.toJobs(step);
List<JobType> remainingJobs = stepJobs.stream().filter(job -> ! isComplete(change, change, instance, job, jobStatus.get(job))).collect(toList());
if ( ! remainingJobs.isEmpty()) {
for (JobType job : remainingJobs) {
Versions versions = Versions.from(change, application, deploymentFor(instance, job),
controller.systemVersion());
if (isTested(jobStatus, versions)) {
if (completedAt.isPresent() && canTrigger(job, jobStatus, versions, instance, application.deploymentSpec(), stepJobs)) {
jobs.add(deploymentJob(instance, versions, change, job, jobStatus.get(job), reason, completedAt.get()));
}
if ( ! alreadyTriggered(jobStatus, versions) && testJobs == null) {
testJobs = emptyList();
}
}
else if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(),
change, instance, jobStatus, versions,
String.format("Testing deployment for %s (%s)",
job.jobName(), versions.toString()),
completedAt.orElseGet(clock::instant));
}
}
completedAt = Optional.empty();
}
else {
if (stepJobs.isEmpty()) {
completedAt = completedAt.map(at -> at.plus(step.delay())).filter(at -> ! at.isAfter(clock.instant()));
reason += " after a delay of " + step.delay();
}
else {
completedAt = stepJobs.stream().map(job -> jobStatus.get(job).lastCompleted().get().end().get()).max(naturalOrder());
reason = "Available change in " + stepJobs.stream().map(JobType::jobName).collect(joining(", "));
}
}
}
}
if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(), change, instance, jobStatus,
Versions.from(application.outstandingChange().onTopOf(change),
application,
steps.sortedDeployments(instance.productionDeployments().values()).stream().findFirst(),
controller.systemVersion()),
"Testing last changes outside prod", clock.instant());
}
jobs.addAll(testJobs);
}
});
return Collections.unmodifiableList(jobs);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec, List<JobType> parallelJobs) {
if (status.get(job).isRunning()) return false;
if (parallelJobs != null && ! parallelJobs.containsAll(runningProductionJobs(status))) return false;
if (job.isProduction() && isSuspendedInAnotherZone(instance, job.zone(controller.system()))) return false;
return triggerAt(clock.instant(), job, status.get(job), versions, instance, deploymentSpec);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
return canTrigger(job, status, versions, instance, deploymentSpec, null);
}
private boolean isSuspendedInAnotherZone(Instance instance, ZoneId zone) {
for (Deployment deployment : instance.productionDeployments().values()) {
if ( ! deployment.zone().equals(zone)
&& controller.applications().isSuspended(new DeploymentId(instance.id(), deployment.zone())))
return true;
}
return false;
}
/** Returns whether the given job can trigger at the given instant */
public boolean triggerAt(Instant instant, JobType job, JobStatus jobStatus, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
if (instance.deploymentJobs().statusOf(job).map(status -> status.pausedUntil().orElse(0)).orElse(0L) > clock.millis()) return false;
if (jobStatus.lastTriggered().isEmpty()) return true;
if (jobStatus.isSuccess()) return true;
if (jobStatus.lastCompleted().isEmpty()) return true;
if (jobStatus.firstFailing().isEmpty()) return true;
if ( ! versions.targetsMatch(jobStatus.lastCompleted().get().versions())) return true;
if (deploymentSpec.requireInstance(instance.name()).upgradePolicy() == DeploymentSpec.UpgradePolicy.canary) return true;
Instant firstFailing = jobStatus.firstFailing().get().end().get();
Instant lastCompleted = jobStatus.lastCompleted().get().end().get();
if (firstFailing.isAfter(instant.minus(Duration.ofMinutes(1)))) return true;
if (job.isTest() && jobStatus.isOutOfCapacity()) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(1)));
}
if (firstFailing.isAfter(instant.minus(Duration.ofHours(1)))) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(10)));
}
return lastCompleted.isBefore(instant.minus(Duration.ofHours(2)));
}
private List<JobType> runningProductionJobs(Map<JobType, JobStatus> status) {
return status.values().parallelStream()
.filter(job -> job.isRunning())
.map(job -> job.job().type())
.filter(JobType::isProduction)
.collect(toList());
}
/**
* Returns whether the given change is complete for the given application for the given job.
*
* Any job is complete if the given change is already successful on that job.
* A production job is also considered complete if its current change is strictly dominated by what
* is already deployed in its zone, i.e., no parts of the change are upgrades, and the full current
* change for the application downgrades the deployment, which is an acknowledgement that the deployed
* version is broken somehow, such that the job may be locked in failure until a new version is released.
*
* Additionally, if the application is pinned to a Vespa version, and the given change has a (this) platform,
* the deployment for the job must be on the pinned version.
*/
public boolean isComplete(Change change, Change fullChange, Instance instance, JobType jobType,
JobStatus status) {
Optional<Deployment> existingDeployment = deploymentFor(instance, jobType);
if ( change.isPinned()
&& change.platform().isPresent()
&& ! existingDeployment.map(Deployment::version).equals(change.platform()))
return false;
return status.lastSuccess()
.map(run -> change.platform().map(run.versions().targetPlatform()::equals).orElse(true)
&& change.application().map(run.versions().targetApplication()::equals).orElse(true))
.orElse(false)
|| jobType.isProduction()
&& existingDeployment.map(deployment -> ! isUpgrade(change, deployment) && isDowngrade(fullChange, deployment))
.orElse(false);
}
private static boolean isUpgrade(Change change, Deployment deployment) {
return change.upgrades(deployment.version()) || change.upgrades(deployment.applicationVersion());
}
private static boolean isDowngrade(Change change, Deployment deployment) {
return change.downgrades(deployment.version()) || change.downgrades(deployment.applicationVersion());
}
private boolean isTested(Map<JobType, JobStatus> status, Versions versions) {
return testedIn(systemTest, status.get(systemTest), versions)
&& testedIn(stagingTest, status.get(stagingTest), versions)
|| alreadyTriggered(status, versions);
}
public boolean testedIn(JobType testType, JobStatus status, Versions versions) {
if (testType == systemTest)
return successOn(status, versions).isPresent();
if (testType == stagingTest)
return successOn(status, versions).map(Run::versions).filter(versions::sourcesMatchIfPresent).isPresent();
throw new IllegalArgumentException(testType + " is not a test job!");
}
public boolean alreadyTriggered(Map<JobType, JobStatus> status, Versions versions) {
return status.values().stream()
.filter(job -> job.job().type().isProduction())
.anyMatch(job -> job.lastTriggered()
.map(Run::versions)
.filter(versions::targetsMatch)
.filter(versions::sourcesMatchIfPresent)
.isPresent());
}
private boolean acceptNewApplicationVersion(Application application) {
if ( ! application.deploymentSpec().instances().stream()
.allMatch(instance -> instance.canChangeRevisionAt(clock.instant()))) return false;
if (application.change().application().isPresent()) return true;
for (Instance instance : application.instances().values())
if (instance.deploymentJobs().hasFailures()) return true;
return application.change().platform().isEmpty();
}
private Change remainingChange(Application application) {
Change change = application.change();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutApplication(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutPlatform();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutPlatform(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutApplication();
return change;
}
/**
* Returns the list of test jobs that should run now, and that need to succeed on the given versions for it to be considered tested.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince) {
return testJobs(deploymentSpec, change, instance, status, versions, reason, availableSince,
jobType -> canTrigger(jobType, status, versions, instance, deploymentSpec));
}
/**
* Returns the list of test jobs that need to succeed on the given versions for it to be considered tested, filtered by the given condition.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince, Predicate<JobType> condition) {
List<Job> jobs = new ArrayList<>();
for (JobType jobType : new DeploymentSteps(deploymentSpec.requireInstance(instance.name()), controller::system).testJobs()) {
Optional<Run> completion = successOn(status.get(jobType), versions)
.filter(run -> versions.sourcesMatchIfPresent(run.versions()) || jobType == systemTest);
if (completion.isEmpty() && condition.test(jobType))
jobs.add(deploymentJob(instance, versions, change, jobType, status.get(jobType), reason, availableSince));
}
return jobs;
}
private static class Job extends BuildJob {
private final JobType jobType;
private final JobRun triggering;
private final Instant availableSince;
private final boolean isRetry;
private final boolean isApplicationUpgrade;
private Job(Instance instance, JobRun triggering, JobType jobType, Instant availableSince,
boolean isRetry, boolean isApplicationUpgrade) {
super(instance.id(), 0L, jobType.jobName());
this.jobType = jobType;
this.triggering = triggering;
this.availableSince = availableSince;
this.isRetry = isRetry;
this.isApplicationUpgrade = isApplicationUpgrade;
}
JobType jobType() { return jobType; }
Instant availableSince() { return availableSince; }
boolean isRetry() { return isRetry; }
boolean applicationUpgrade() { return isApplicationUpgrade; }
}
} | class DeploymentTrigger {
public static final Duration maxPause = Duration.ofDays(3);
private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName());
private final Controller controller;
private final Clock clock;
private final JobController jobs;
public DeploymentTrigger(Controller controller, Clock clock) {
this.controller = Objects.requireNonNull(controller, "controller cannot be null");
this.clock = Objects.requireNonNull(clock, "clock cannot be null");
this.jobs = controller.jobController();
}
public DeploymentSteps steps(DeploymentInstanceSpec spec) {
return new DeploymentSteps(spec, controller::system);
}
public void notifyOfSubmission(TenantAndApplicationId id, ApplicationVersion version, long projectId) {
if (applications().getApplication(id).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring submission from project '" + projectId +
"': Unknown application '" + id + "'");
return;
}
applications().lockApplicationOrThrow(id, application -> {
if (acceptNewApplicationVersion(application.get())) {
application = application.withChange(application.get().change().with(version))
.withOutstandingChange(Change.empty());
for (Run run : jobs.active(id))
if ( ! run.id().type().environment().isManuallyDeployed())
jobs.abort(run.id());
}
else
application = application.withOutstandingChange(Change.of(version));
application = application.withProjectId(OptionalLong.of(projectId));
application = application.withNewSubmission(version);
applications().store(application.withChange(remainingChange(application.get())));
});
}
/**
* Records information when a job completes (successfully or not). This information is used when deciding what to
* trigger next.
*/
public void notifyOfCompletion(JobReport report) {
log.log(LogLevel.DEBUG, String.format("Notified of %s for %s of %s (%d)",
report.jobError().map(e -> e.toString() + " error")
.orElse("success"),
report.jobType(),
report.applicationId(),
report.projectId()));
if (applications().getInstance(report.applicationId()).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring completion of job of project '" + report.projectId() +
"': Unknown application '" + report.applicationId() + "'");
return;
}
applications().lockApplicationOrThrow(TenantAndApplicationId.from(report.applicationId()), application -> {
var status = application.get().require(report.applicationId().instance())
.deploymentJobs().statusOf(report.jobType());
var triggering = status.filter(job -> job.lastTriggered().isPresent()
&& job.lastCompleted()
.map(completion -> ! completion.at().isAfter(job.lastTriggered().get().at()))
.orElse(true))
.orElseThrow(() -> new IllegalStateException("Notified of completion of " + report.jobType().jobName() + " for " +
report.applicationId() + ", but that has not been triggered; last was " +
status.flatMap(job -> job.lastTriggered().map(run -> run.at().toString()))
.orElse("never")))
.lastTriggered().get();
application = application.with(report.applicationId().instance(),
instance -> instance.withJobCompletion(report.jobType(),
triggering.completion(report.buildNumber(), clock.instant()),
report.jobError()));
applications().store(application.withChange(remainingChange(application.get())));
});
}
/**
* Finds and triggers jobs that can and should run but are currently not, and returns the number of triggered jobs.
*
* Only one job is triggered each run for test jobs, since their environments have limited capacity.
*/
public long triggerReadyJobs() {
return computeReadyJobs().stream()
.collect(partitioningBy(job -> job.jobType().isTest()))
.entrySet().stream()
.flatMap(entry -> (entry.getKey()
? entry.getValue().stream()
.sorted(comparing(Job::isRetry)
.thenComparing(Job::applicationUpgrade)
.reversed()
.thenComparing(Job::availableSince))
.collect(groupingBy(Job::jobType))
: entry.getValue().stream()
.collect(groupingBy(Job::applicationId)))
.values().stream()
.map(jobs -> (Supplier<Long>) jobs.stream()
.filter(this::trigger)
.limit(entry.getKey() ? 1 : Long.MAX_VALUE)::count))
.parallel().map(Supplier::get).reduce(0L, Long::sum);
}
/**
* Attempts to trigger the given job for the given application and returns the outcome.
*
* If the build service can not find the given job, or claims it is illegal to trigger it,
* the project id is removed from the application owning the job, to prevent further trigger attempts.
*/
public boolean trigger(Job job) {
log.log(LogLevel.DEBUG, String.format("Triggering %s: %s", job, job.triggering));
try {
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application -> {
jobs.start(job.applicationId(), job.jobType, new Versions(job.triggering.platform(),
job.triggering.application(),
job.triggering.sourcePlatform(),
job.triggering.sourceApplication()));
applications().store(application.with(job.applicationId().instance(),
instance -> instance.withJobTriggering(job.jobType, job.triggering)));
});
return true;
}
catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception triggering " + job + ": " + e);
if (e instanceof NoSuchElementException || e instanceof IllegalArgumentException)
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application ->
applications().store(application.withProjectId(OptionalLong.empty())));
return false;
}
}
/** Force triggering of a job for given instance. */
public List<JobType> forceTrigger(ApplicationId applicationId, JobType jobType, String user) {
Application application = applications().requireApplication(TenantAndApplicationId.from(applicationId));
Instance instance = application.require(applicationId.instance());
Versions versions = Versions.from(application.change(), application, deploymentFor(instance, jobType),
controller.systemVersion());
String reason = "Job triggered manually by " + user;
var jobStatus = jobs.deploymentStatus(application).instanceJobs(instance.name());
return (jobType.isProduction() && ! isTested(jobStatus, versions)
? testJobs(application.deploymentSpec(), application.change(), instance, jobStatus, versions, reason, clock.instant(), __ -> true).stream()
: Stream.of(deploymentJob(instance, versions, application.change(), jobType, jobStatus.get(jobType), reason, clock.instant())))
.peek(this::trigger)
.map(Job::jobType).collect(toList());
}
/** Prevents jobs of the given type from starting, until the given time. */
public void pauseJob(ApplicationId id, JobType jobType, Instant until) {
if (until.isAfter(clock.instant().plus(maxPause)))
throw new IllegalArgumentException("Pause only allowed for up to " + maxPause);
applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application ->
applications().store(application.with(id.instance(),
instance -> instance.withJobPause(jobType, OptionalLong.of(until.toEpochMilli())))));
}
/** Triggers a change of this application, unless it already has a change. */
public void triggerChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if ( ! application.get().change().hasTargets())
forceChange(applicationId, change);
});
}
/** Overrides the given application's platform and application changes with any contained in the given change. */
public void forceChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if (change.application().isPresent())
application = application.withOutstandingChange(Change.empty());
applications().store(application.withChange(change.onTopOf(application.get().change())));
});
}
/** Cancels the indicated part of the given application's change. */
public void cancelChange(TenantAndApplicationId applicationId, ChangesToCancel cancellation) {
applications().lockApplicationOrThrow(applicationId, application -> {
Change change;
switch (cancellation) {
case ALL: change = Change.empty(); break;
case VERSIONS: change = Change.empty().withPin(); break;
case PLATFORM: change = application.get().change().withoutPlatform(); break;
case APPLICATION: change = application.get().change().withoutApplication(); break;
case PIN: change = application.get().change().withoutPin(); break;
default: throw new IllegalArgumentException("Unknown cancellation choice '" + cancellation + "'!");
}
applications().store(application.withChange(change));
});
}
public enum ChangesToCancel { ALL, PLATFORM, APPLICATION, VERSIONS, PIN }
private ApplicationController applications() {
return controller.applications();
}
private Optional<Run> successOn(JobStatus status, Versions versions) {
return status.lastSuccess().filter(run -> versions.targetsMatch(run.versions()));
}
private Optional<Deployment> deploymentFor(Instance instance, JobType jobType) {
return Optional.ofNullable(instance.deployments().get(jobType.zone(controller.system())));
}
private static <T extends Comparable<T>> Optional<T> max(Optional<T> o1, Optional<T> o2) {
return o1.isEmpty() ? o2 : o2.isEmpty() ? o1 : o1.get().compareTo(o2.get()) >= 0 ? o1 : o2;
}
/** Returns the set of all jobs which have changes to propagate from the upstream steps. */
private List<Job> computeReadyJobs() {
return ApplicationList.from(applications().asList())
.withProjectId()
.withChanges()
.withDeploymentSpec()
.idList().stream()
.map(this::computeReadyJobs)
.flatMap(Collection::stream)
.collect(toList());
}
/**
* Finds the next step to trigger for the given application, if any, and returns these as a list.
*/
private List<Job> computeReadyJobs(TenantAndApplicationId id) {
List<Job> jobs = new ArrayList<>();
applications().getApplication(id).ifPresent(application -> {
Collection<Instance> instances = application.deploymentSpec().instances().stream()
.flatMap(instance -> application.get(instance.name()).stream())
.collect(Collectors.toUnmodifiableList());
DeploymentStatus deploymentStatus = this.jobs.deploymentStatus(application);
for (Instance instance : instances) {
var jobStatus = deploymentStatus.instanceJobs(instance.name());
Change change = application.change();
Optional<Instant> completedAt = max(Optional.ofNullable(jobStatus.get(systemTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())),
Optional.ofNullable(jobStatus.get(stagingTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())));
String reason = "New change available";
List<Job> testJobs = null;
DeploymentSteps steps = steps(application.deploymentSpec().requireInstance(instance.name()));
if (change.hasTargets()) {
for (Step step : steps.production()) {
List<JobType> stepJobs = steps.toJobs(step);
List<JobType> remainingJobs = stepJobs.stream().filter(job -> ! isComplete(change, change, instance, job, jobStatus.get(job))).collect(toList());
if ( ! remainingJobs.isEmpty()) {
for (JobType job : remainingJobs) {
Versions versions = Versions.from(change, application, deploymentFor(instance, job),
controller.systemVersion());
if (isTested(jobStatus, versions)) {
if (completedAt.isPresent() && canTrigger(job, jobStatus, versions, instance, application.deploymentSpec(), stepJobs)) {
jobs.add(deploymentJob(instance, versions, change, job, jobStatus.get(job), reason, completedAt.get()));
}
if ( ! alreadyTriggered(jobStatus, versions) && testJobs == null) {
testJobs = emptyList();
}
}
else if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(),
change, instance, jobStatus, versions,
String.format("Testing deployment for %s (%s)",
job.jobName(), versions.toString()),
completedAt.orElseGet(clock::instant));
}
}
completedAt = Optional.empty();
}
else {
if (stepJobs.isEmpty()) {
completedAt = completedAt.map(at -> at.plus(step.delay())).filter(at -> ! at.isAfter(clock.instant()));
reason += " after a delay of " + step.delay();
}
else {
completedAt = stepJobs.stream().map(job -> jobStatus.get(job).lastCompleted().get().end().get()).max(naturalOrder());
reason = "Available change in " + stepJobs.stream().map(JobType::jobName).collect(joining(", "));
}
}
}
}
if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(), change, instance, jobStatus,
Versions.from(application.outstandingChange().onTopOf(change),
application,
steps.sortedDeployments(instance.productionDeployments().values()).stream().findFirst(),
controller.systemVersion()),
"Testing last changes outside prod", clock.instant());
}
jobs.addAll(testJobs);
}
});
return Collections.unmodifiableList(jobs);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec, List<JobType> parallelJobs) {
if (status.get(job).isRunning()) return false;
if (parallelJobs != null && ! parallelJobs.containsAll(runningProductionJobs(status))) return false;
if (job.isProduction() && isSuspendedInAnotherZone(instance, job.zone(controller.system()))) return false;
return triggerAt(clock.instant(), job, status.get(job), versions, instance, deploymentSpec);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
return canTrigger(job, status, versions, instance, deploymentSpec, null);
}
private boolean isSuspendedInAnotherZone(Instance instance, ZoneId zone) {
for (Deployment deployment : instance.productionDeployments().values()) {
if ( ! deployment.zone().equals(zone)
&& controller.applications().isSuspended(new DeploymentId(instance.id(), deployment.zone())))
return true;
}
return false;
}
/** Returns whether the given job can trigger at the given instant */
public boolean triggerAt(Instant instant, JobType job, JobStatus jobStatus, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
if (instance.deploymentJobs().statusOf(job).map(status -> status.pausedUntil().orElse(0)).orElse(0L) > clock.millis()) return false;
if (jobStatus.lastTriggered().isEmpty()) return true;
if (jobStatus.isSuccess()) return true;
if (jobStatus.lastCompleted().isEmpty()) return true;
if (jobStatus.firstFailing().isEmpty()) return true;
if ( ! versions.targetsMatch(jobStatus.lastCompleted().get().versions())) return true;
if (deploymentSpec.requireInstance(instance.name()).upgradePolicy() == DeploymentSpec.UpgradePolicy.canary) return true;
Instant firstFailing = jobStatus.firstFailing().get().end().get();
Instant lastCompleted = jobStatus.lastCompleted().get().end().get();
if (firstFailing.isAfter(instant.minus(Duration.ofMinutes(1)))) return true;
if (job.isTest() && jobStatus.isOutOfCapacity()) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(1)));
}
if (firstFailing.isAfter(instant.minus(Duration.ofHours(1)))) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(10)));
}
return lastCompleted.isBefore(instant.minus(Duration.ofHours(2)));
}
private List<JobType> runningProductionJobs(Map<JobType, JobStatus> status) {
return status.values().parallelStream()
.filter(job -> job.isRunning())
.map(job -> job.id().type())
.filter(JobType::isProduction)
.collect(toList());
}
/**
* Returns whether the given change is complete for the given application for the given job.
*
* Any job is complete if the given change is already successful on that job.
* A production job is also considered complete if its current change is strictly dominated by what
* is already deployed in its zone, i.e., no parts of the change are upgrades, and the full current
* change for the application downgrades the deployment, which is an acknowledgement that the deployed
* version is broken somehow, such that the job may be locked in failure until a new version is released.
*
* Additionally, if the application is pinned to a Vespa version, and the given change has a (this) platform,
* the deployment for the job must be on the pinned version.
*/
public boolean isComplete(Change change, Change fullChange, Instance instance, JobType jobType,
JobStatus status) {
Optional<Deployment> existingDeployment = deploymentFor(instance, jobType);
if ( change.isPinned()
&& change.platform().isPresent()
&& ! existingDeployment.map(Deployment::version).equals(change.platform()))
return false;
return status.lastSuccess()
.map(run -> change.platform().map(run.versions().targetPlatform()::equals).orElse(true)
&& change.application().map(run.versions().targetApplication()::equals).orElse(true))
.orElse(false)
|| jobType.isProduction()
&& existingDeployment.map(deployment -> ! isUpgrade(change, deployment) && isDowngrade(fullChange, deployment))
.orElse(false);
}
private static boolean isUpgrade(Change change, Deployment deployment) {
return change.upgrades(deployment.version()) || change.upgrades(deployment.applicationVersion());
}
private static boolean isDowngrade(Change change, Deployment deployment) {
return change.downgrades(deployment.version()) || change.downgrades(deployment.applicationVersion());
}
private boolean isTested(Map<JobType, JobStatus> status, Versions versions) {
return testedIn(systemTest, status.get(systemTest), versions)
&& testedIn(stagingTest, status.get(stagingTest), versions)
|| alreadyTriggered(status, versions);
}
public boolean testedIn(JobType testType, JobStatus status, Versions versions) {
if (testType == systemTest)
return successOn(status, versions).isPresent();
if (testType == stagingTest)
return successOn(status, versions).map(Run::versions).filter(versions::sourcesMatchIfPresent).isPresent();
throw new IllegalArgumentException(testType + " is not a test job!");
}
public boolean alreadyTriggered(Map<JobType, JobStatus> status, Versions versions) {
return status.values().stream()
.filter(job -> job.id().type().isProduction())
.anyMatch(job -> job.lastTriggered()
.map(Run::versions)
.filter(versions::targetsMatch)
.filter(versions::sourcesMatchIfPresent)
.isPresent());
}
private boolean acceptNewApplicationVersion(Application application) {
if ( ! application.deploymentSpec().instances().stream()
.allMatch(instance -> instance.canChangeRevisionAt(clock.instant()))) return false;
if (application.change().application().isPresent()) return true;
for (Instance instance : application.instances().values())
if (instance.deploymentJobs().hasFailures()) return true;
return application.change().platform().isEmpty();
}
private Change remainingChange(Application application) {
Change change = application.change();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutApplication(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutPlatform();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutPlatform(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutApplication();
return change;
}
/**
* Returns the list of test jobs that should run now, and that need to succeed on the given versions for it to be considered tested.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince) {
return testJobs(deploymentSpec, change, instance, status, versions, reason, availableSince,
jobType -> canTrigger(jobType, status, versions, instance, deploymentSpec));
}
/**
* Returns the list of test jobs that need to succeed on the given versions for it to be considered tested, filtered by the given condition.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince, Predicate<JobType> condition) {
List<Job> jobs = new ArrayList<>();
for (JobType jobType : new DeploymentSteps(deploymentSpec.requireInstance(instance.name()), controller::system).testJobs()) {
Optional<Run> completion = successOn(status.get(jobType), versions)
.filter(run -> versions.sourcesMatchIfPresent(run.versions()) || jobType == systemTest);
if (completion.isEmpty() && condition.test(jobType))
jobs.add(deploymentJob(instance, versions, change, jobType, status.get(jobType), reason, availableSince));
}
return jobs;
}
private static class Job {
private final ApplicationId instanceId;
private final JobType jobType;
private final JobRun triggering;
private final Instant availableSince;
private final boolean isRetry;
private final boolean isApplicationUpgrade;
private Job(Instance instance, JobRun triggering, JobType jobType, Instant availableSince,
boolean isRetry, boolean isApplicationUpgrade) {
this.instanceId = instance.id();
this.jobType = jobType;
this.triggering = triggering;
this.availableSince = availableSince;
this.isRetry = isRetry;
this.isApplicationUpgrade = isApplicationUpgrade;
}
ApplicationId applicationId() { return instanceId; }
JobType jobType() { return jobType; }
Instant availableSince() { return availableSince; }
boolean isRetry() { return isRetry; }
boolean applicationUpgrade() { return isApplicationUpgrade; }
}
} |
This will cause `internal` to become `false` for all apps on the remaining 2/3 controllers once the first upgrades. Is this fine? If not, keep writing this as `true` for at least one version. | 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()));
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;
} | toSlime(application.change(), root, deployingField); | 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, true);
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;
} | 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";
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 = latestVersionFromSlime(root.field(latestVersionField));
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
deployKeys, projectId, latestVersion, instances);
}
private Optional<ApplicationVersion> latestVersionFromSlime(Inspector latestVersionObject) {
if (latestVersionObject.valid())
return Optional.of(applicationVersionFromSlime(latestVersionObject));
return Optional.empty();
}
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, instanceName, 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, 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);
}
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, InstanceName instance, 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.instance(instance)
.map(spec -> globalEndpointRegions(spec, endpointId))
.orElse(Set.of());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
private Set<RegionName> globalEndpointRegions(DeploymentInstanceSpec spec, EndpointId endpointId) {
if (spec.globalServiceId().isPresent())
return spec.zones().stream()
.flatMap(zone -> zone.region().stream())
.collect(Collectors.toSet());
return spec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
}
} | 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";
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 = latestVersionFromSlime(root.field(latestVersionField));
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
deployKeys, projectId, latestVersion, instances);
}
private Optional<ApplicationVersion> latestVersionFromSlime(Inspector latestVersionObject) {
if (latestVersionObject.valid())
return Optional.of(applicationVersionFromSlime(latestVersionObject));
return Optional.empty();
}
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, instanceName, 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, 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);
}
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, InstanceName instance, 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.instance(instance)
.map(spec -> globalEndpointRegions(spec, endpointId))
.orElse(Set.of());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
private Set<RegionName> globalEndpointRegions(DeploymentInstanceSpec spec, EndpointId endpointId) {
if (spec.globalServiceId().isPresent())
return spec.zones().stream()
.flatMap(zone -> zone.region().stream())
.collect(Collectors.toSet());
return spec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
}
} |
Nice! | private void upgrade(ApplicationList applications, Version version) {
applications = applications.withProductionDeployment();
applications = applications.onLowerVersionThan(version);
applications = applications.allowMajorVersion(version.getMajor(), targetMajorVersion().orElse(version.getMajor()));
applications = applications.not().deploying();
applications = applications.not().failingOn(version);
applications = applications.canUpgradeAt(controller().clock().instant());
applications = applications.byIncreasingDeployedVersion();
for (Application application : applications.with(UpgradePolicy.canary).asList())
controller().applications().deploymentTrigger().triggerChange(application.id(), Change.of(version));
for (Application application : applications.not().with(UpgradePolicy.canary).first(numberOfApplicationsToUpgrade()).asList())
controller().applications().deploymentTrigger().triggerChange(application.id(), Change.of(version));
} | applications = applications.not().failingOn(version); | private void upgrade(ApplicationList applications, Version version) {
applications = applications.withProductionDeployment();
applications = applications.onLowerVersionThan(version);
applications = applications.allowMajorVersion(version.getMajor(), targetMajorVersion().orElse(version.getMajor()));
applications = applications.not().deploying();
applications = applications.not().failingOn(version);
applications = applications.canUpgradeAt(controller().clock().instant());
applications = applications.byIncreasingDeployedVersion();
for (Application application : applications.with(UpgradePolicy.canary).asList())
controller().applications().deploymentTrigger().triggerChange(application.id(), Change.of(version));
for (Application application : applications.not().with(UpgradePolicy.canary).first(numberOfApplicationsToUpgrade()).asList())
controller().applications().deploymentTrigger().triggerChange(application.id(), Change.of(version));
} | class Upgrader extends Maintainer {
private static final Logger log = Logger.getLogger(Upgrader.class.getName());
private final CuratorDb curator;
public Upgrader(Controller controller, Duration interval, JobControl jobControl, CuratorDb curator) {
super(controller, interval, jobControl);
this.curator = Objects.requireNonNull(curator, "curator cannot be null");
}
/**
* Schedule application upgrades. Note that this implementation must be idempotent.
*/
@Override
public void maintain() {
Version canaryTarget = controller().systemVersion();
Collection<Version> defaultTargets = targetVersions(Confidence.normal);
Collection<Version> conservativeTargets = targetVersions(Confidence.high);
for (VespaVersion version : controller().versionStatus().versions()) {
if (version.confidence() == Confidence.broken)
cancelUpgradesOf(applications().not().with(UpgradePolicy.canary).upgradingTo(version.versionNumber()),
version.versionNumber() + " is broken");
}
cancelUpgradesOf(applications().with(UpgradePolicy.canary).upgrading().not().upgradingTo(canaryTarget),
"Outdated target version for Canaries");
String reason = "Failing on outdated version";
cancelUpgradesOf(applications().with(UpgradePolicy.defaultPolicy).upgrading().failing().not().upgradingTo(defaultTargets), reason);
cancelUpgradesOf(applications().with(UpgradePolicy.conservative).upgrading().failing().not().upgradingTo(conservativeTargets), reason);
ApplicationList applications = applications();
upgrade(applications.with(UpgradePolicy.canary), canaryTarget);
defaultTargets.forEach(target -> upgrade(applications.with(UpgradePolicy.defaultPolicy), target));
conservativeTargets.forEach(target -> upgrade(applications.with(UpgradePolicy.conservative), target));
}
/** Returns the target versions for given confidence, one per major version in the system */
private Collection<Version> targetVersions(Confidence confidence) {
return controller().versionStatus().versions().stream()
.filter(v -> !v.versionNumber().isAfter(controller().systemVersion()))
.filter(v -> v.confidence().equalOrHigherThan(confidence))
.map(VespaVersion::versionNumber)
.collect(Collectors.toMap(Version::getMajor,
Function.identity(),
BinaryOperator.<Version>maxBy(Comparator.naturalOrder())))
.values();
}
/** Returns a list of all applications, except those which are pinned — these should not be manipulated by the Upgrader */
private ApplicationList applications() {
return ApplicationList.from(controller().applications().asList()).unpinned();
}
private void cancelUpgradesOf(ApplicationList applications, String reason) {
if (applications.isEmpty()) return;
log.info("Cancelling upgrading of " + applications.asList().size() + " applications: " + reason);
for (Application application : applications.asList())
controller().applications().deploymentTrigger().cancelChange(application.id(), PLATFORM);
}
/** Returns the number of applications to upgrade in this run */
private int numberOfApplicationsToUpgrade() {
return numberOfApplicationsToUpgrade(maintenanceInterval().dividedBy(Math.max(1, controller().curator().cluster().size())).toMillis(),
controller().clock().millis(),
upgradesPerMinute());
}
/** Returns the number of applications to upgrade in the interval containing now */
static int numberOfApplicationsToUpgrade(long intervalMillis, long nowMillis, double upgradesPerMinute) {
long intervalStart = Math.round(nowMillis / (double) intervalMillis) * intervalMillis;
double upgradesPerMilli = upgradesPerMinute / 60_000;
long upgradesAtStart = (long) (intervalStart * upgradesPerMilli);
long upgradesAtEnd = (long) ((intervalStart + intervalMillis) * upgradesPerMilli);
return (int) (upgradesAtEnd - upgradesAtStart);
}
/** Returns number of upgrades per minute */
public double upgradesPerMinute() {
return curator.readUpgradesPerMinute();
}
/** Sets the number of upgrades per minute */
public void setUpgradesPerMinute(double n) {
if (n < 0)
throw new IllegalArgumentException("Upgrades per minute must be >= 0, got " + n);
curator.writeUpgradesPerMinute(n);
}
/** Returns the target major version for applications not specifying one */
public Optional<Integer> targetMajorVersion() {
return curator.readTargetMajorVersion();
}
/** Sets the default target major version. Set to empty to determine target version normally (by confidence) */
public void setTargetMajorVersion(Optional<Integer> targetMajorVersion) {
curator.writeTargetMajorVersion(targetMajorVersion);
}
/** Override confidence for given version. This will cause the computed confidence to be ignored */
public void overrideConfidence(Version version, Confidence confidence) {
try (Lock lock = curator.lockConfidenceOverrides()) {
Map<Version, Confidence> overrides = new LinkedHashMap<>(curator.readConfidenceOverrides());
overrides.put(version, confidence);
curator.writeConfidenceOverrides(overrides);
}
}
/** Returns all confidence overrides */
public Map<Version, Confidence> confidenceOverrides() {
return curator.readConfidenceOverrides();
}
/** Remove confidence override for given version */
public void removeConfidenceOverride(Version version) {
controller().removeConfidenceOverride(version::equals);
}
} | class Upgrader extends Maintainer {
private static final Logger log = Logger.getLogger(Upgrader.class.getName());
private final CuratorDb curator;
public Upgrader(Controller controller, Duration interval, JobControl jobControl, CuratorDb curator) {
super(controller, interval, jobControl);
this.curator = Objects.requireNonNull(curator, "curator cannot be null");
}
/**
* Schedule application upgrades. Note that this implementation must be idempotent.
*/
@Override
public void maintain() {
Version canaryTarget = controller().systemVersion();
Collection<Version> defaultTargets = targetVersions(Confidence.normal);
Collection<Version> conservativeTargets = targetVersions(Confidence.high);
for (VespaVersion version : controller().versionStatus().versions()) {
if (version.confidence() == Confidence.broken)
cancelUpgradesOf(applications().not().with(UpgradePolicy.canary).upgradingTo(version.versionNumber()),
version.versionNumber() + " is broken");
}
cancelUpgradesOf(applications().with(UpgradePolicy.canary).upgrading().not().upgradingTo(canaryTarget),
"Outdated target version for Canaries");
String reason = "Failing on outdated version";
cancelUpgradesOf(applications().with(UpgradePolicy.defaultPolicy).upgrading().failing().not().upgradingTo(defaultTargets), reason);
cancelUpgradesOf(applications().with(UpgradePolicy.conservative).upgrading().failing().not().upgradingTo(conservativeTargets), reason);
ApplicationList applications = applications();
upgrade(applications.with(UpgradePolicy.canary), canaryTarget);
defaultTargets.forEach(target -> upgrade(applications.with(UpgradePolicy.defaultPolicy), target));
conservativeTargets.forEach(target -> upgrade(applications.with(UpgradePolicy.conservative), target));
}
/** Returns the target versions for given confidence, one per major version in the system */
private Collection<Version> targetVersions(Confidence confidence) {
return controller().versionStatus().versions().stream()
.filter(v -> !v.versionNumber().isAfter(controller().systemVersion()))
.filter(v -> v.confidence().equalOrHigherThan(confidence))
.map(VespaVersion::versionNumber)
.collect(Collectors.toMap(Version::getMajor,
Function.identity(),
BinaryOperator.<Version>maxBy(Comparator.naturalOrder())))
.values();
}
/** Returns a list of all applications, except those which are pinned — these should not be manipulated by the Upgrader */
private ApplicationList applications() {
return ApplicationList.from(controller().applications().asList()).unpinned();
}
private void cancelUpgradesOf(ApplicationList applications, String reason) {
if (applications.isEmpty()) return;
log.info("Cancelling upgrading of " + applications.asList().size() + " applications: " + reason);
for (Application application : applications.asList())
controller().applications().deploymentTrigger().cancelChange(application.id(), PLATFORM);
}
/** Returns the number of applications to upgrade in this run */
private int numberOfApplicationsToUpgrade() {
return numberOfApplicationsToUpgrade(maintenanceInterval().dividedBy(Math.max(1, controller().curator().cluster().size())).toMillis(),
controller().clock().millis(),
upgradesPerMinute());
}
/** Returns the number of applications to upgrade in the interval containing now */
static int numberOfApplicationsToUpgrade(long intervalMillis, long nowMillis, double upgradesPerMinute) {
long intervalStart = Math.round(nowMillis / (double) intervalMillis) * intervalMillis;
double upgradesPerMilli = upgradesPerMinute / 60_000;
long upgradesAtStart = (long) (intervalStart * upgradesPerMilli);
long upgradesAtEnd = (long) ((intervalStart + intervalMillis) * upgradesPerMilli);
return (int) (upgradesAtEnd - upgradesAtStart);
}
/** Returns number of upgrades per minute */
public double upgradesPerMinute() {
return curator.readUpgradesPerMinute();
}
/** Sets the number of upgrades per minute */
public void setUpgradesPerMinute(double n) {
if (n < 0)
throw new IllegalArgumentException("Upgrades per minute must be >= 0, got " + n);
curator.writeUpgradesPerMinute(n);
}
/** Returns the target major version for applications not specifying one */
public Optional<Integer> targetMajorVersion() {
return curator.readTargetMajorVersion();
}
/** Sets the default target major version. Set to empty to determine target version normally (by confidence) */
public void setTargetMajorVersion(Optional<Integer> targetMajorVersion) {
curator.writeTargetMajorVersion(targetMajorVersion);
}
/** Override confidence for given version. This will cause the computed confidence to be ignored */
public void overrideConfidence(Version version, Confidence confidence) {
try (Lock lock = curator.lockConfidenceOverrides()) {
Map<Version, Confidence> overrides = new LinkedHashMap<>(curator.readConfidenceOverrides());
overrides.put(version, confidence);
curator.writeConfidenceOverrides(overrides);
}
}
/** Returns all confidence overrides */
public Map<Version, Confidence> confidenceOverrides() {
return curator.readConfidenceOverrides();
}
/** Remove confidence override for given version */
public void removeConfidenceOverride(Version version) {
controller().removeConfidenceOverride(version::equals);
}
} |
Thanks. | private Job deploymentJob(Instance instance, Versions versions, Change change, JobType jobType, JobStatus jobStatus, String reason, Instant availableSince) {
if (jobStatus.isOutOfCapacity()) reason += "; retrying on out of capacity";
var triggering = JobRun.triggering(versions.targetPlatform(), versions.targetApplication(),
versions.sourcePlatform(), versions.sourceApplication(),
reason, clock.instant());
return new Job(instance, triggering, jobType, availableSince, jobStatus.isOutOfCapacity(), change.application().isPresent());
} | versions.sourcePlatform(), versions.sourceApplication(), | private Job deploymentJob(Instance instance, Versions versions, Change change, JobType jobType, JobStatus jobStatus, String reason, Instant availableSince) {
if (jobStatus.isOutOfCapacity()) reason += "; retrying on out of capacity";
var triggering = JobRun.triggering(versions.targetPlatform(), versions.targetApplication(),
versions.sourcePlatform(), versions.sourceApplication(),
reason, clock.instant());
return new Job(instance, triggering, jobType, availableSince, jobStatus.isOutOfCapacity(), change.application().isPresent());
} | class DeploymentTrigger {
/*
* Instance orchestration TODO jonmv.
* Store new production application packages under non-instance path
* Read production packages from non-instance path, with fallback
* Deprecate and redirect some instance qualified paths in application/v4
* Orchestrate deployment across instances.
*/
public static final Duration maxPause = Duration.ofDays(3);
private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName());
private final Controller controller;
private final Clock clock;
private final BuildService buildService;
private final JobController jobs;
public DeploymentTrigger(Controller controller, BuildService buildService, Clock clock) {
this.controller = Objects.requireNonNull(controller, "controller cannot be null");
this.clock = Objects.requireNonNull(clock, "clock cannot be null");
this.buildService = Objects.requireNonNull(buildService, "buildService cannot be null");
this.jobs = controller.jobController();
}
public DeploymentSteps steps(DeploymentInstanceSpec spec) {
return new DeploymentSteps(spec, controller::system);
}
public void notifyOfSubmission(TenantAndApplicationId id, ApplicationVersion version, long projectId) {
if (applications().getApplication(id).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring submission from project '" + projectId +
"': Unknown application '" + id + "'");
return;
}
applications().lockApplicationOrThrow(id, application -> {
if (acceptNewApplicationVersion(application.get())) {
application = application.withChange(application.get().change().with(version))
.withOutstandingChange(Change.empty());
if (application.get().internal())
for (Run run : jobs.active(id))
if ( ! run.id().type().environment().isManuallyDeployed())
jobs.abort(run.id());
}
else
application = application.withOutstandingChange(Change.of(version));
application = application.withProjectId(OptionalLong.of(projectId));
application = application.withNewSubmission(version);
applications().store(application.withChange(remainingChange(application.get())));
});
}
/**
* Records information when a job completes (successfully or not). This information is used when deciding what to
* trigger next.
*/
public void notifyOfCompletion(JobReport report) {
log.log(LogLevel.DEBUG, String.format("Notified of %s for %s of %s (%d)",
report.jobError().map(e -> e.toString() + " error")
.orElse("success"),
report.jobType(),
report.applicationId(),
report.projectId()));
if (applications().getInstance(report.applicationId()).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring completion of job of project '" + report.projectId() +
"': Unknown application '" + report.applicationId() + "'");
return;
}
applications().lockApplicationOrThrow(TenantAndApplicationId.from(report.applicationId()), application -> {
var status = application.get().require(report.applicationId().instance())
.deploymentJobs().statusOf(report.jobType());
var triggering = status.filter(job -> job.lastTriggered().isPresent()
&& job.lastCompleted()
.map(completion -> ! completion.at().isAfter(job.lastTriggered().get().at()))
.orElse(true))
.orElseThrow(() -> new IllegalStateException("Notified of completion of " + report.jobType().jobName() + " for " +
report.applicationId() + ", but that has not been triggered; last was " +
status.flatMap(job -> job.lastTriggered().map(run -> run.at().toString()))
.orElse("never")))
.lastTriggered().get();
application = application.with(report.applicationId().instance(),
instance -> instance.withJobCompletion(report.jobType(),
triggering.completion(report.buildNumber(), clock.instant()),
report.jobError()));
applications().store(application.withChange(remainingChange(application.get())));
});
}
/** Returns a map of jobs that are scheduled to be run, grouped by the job type */
public Map<JobType, ? extends List<? extends BuildJob>> jobsToRun() {
return computeReadyJobs().stream().collect(groupingBy(Job::jobType));
}
/**
* Finds and triggers jobs that can and should run but are currently not, and returns the number of triggered jobs.
*
* Only one job is triggered each run for test jobs, since their environments have limited capacity.
*/
public long triggerReadyJobs() {
return computeReadyJobs().stream()
.collect(partitioningBy(job -> job.jobType().isTest()))
.entrySet().stream()
.flatMap(entry -> (entry.getKey()
? entry.getValue().stream()
.sorted(comparing(Job::isRetry)
.thenComparing(Job::applicationUpgrade)
.reversed()
.thenComparing(Job::availableSince))
.collect(groupingBy(Job::jobType))
: entry.getValue().stream()
.collect(groupingBy(Job::applicationId)))
.values().stream()
.map(jobs -> (Supplier<Long>) jobs.stream()
.filter(this::trigger)
.limit(entry.getKey() ? 1 : Long.MAX_VALUE)::count))
.parallel().map(Supplier::get).reduce(0L, Long::sum);
}
/**
* Attempts to trigger the given job for the given application and returns the outcome.
*
* If the build service can not find the given job, or claims it is illegal to trigger it,
* the project id is removed from the application owning the job, to prevent further trigger attempts.
*/
public boolean trigger(Job job) {
log.log(LogLevel.DEBUG, String.format("Triggering %s: %s", job, job.triggering));
try {
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application -> {
if (application.get().internal())
jobs.start(job.applicationId(), job.jobType, new Versions(job.triggering.platform(),
job.triggering.application(),
job.triggering.sourcePlatform(),
job.triggering.sourceApplication()));
else
buildService.trigger(job);
applications().store(application.with(job.applicationId().instance(),
instance -> instance.withJobTriggering(job.jobType, job.triggering)));
});
return true;
}
catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception triggering " + job + ": " + e);
if (e instanceof NoSuchElementException || e instanceof IllegalArgumentException)
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application ->
applications().store(application.withProjectId(OptionalLong.empty())));
return false;
}
}
/** Force triggering of a job for given instance. */
public List<JobType> forceTrigger(ApplicationId applicationId, JobType jobType, String user) {
Application application = applications().requireApplication(TenantAndApplicationId.from(applicationId));
Instance instance = application.require(applicationId.instance());
Versions versions = Versions.from(application.change(), application, deploymentFor(instance, jobType),
controller.systemVersion());
String reason = "Job triggered manually by " + user;
var jobStatus = jobs.jobStatus(applicationId, application.deploymentSpec());
return (jobType.isProduction() && ! isTested(jobStatus, versions)
? testJobs(application.deploymentSpec(), application.change(), instance, jobStatus, versions, reason, clock.instant(), __ -> true).stream()
: Stream.of(deploymentJob(instance, versions, application.change(), jobType, jobStatus.get(jobType), reason, clock.instant())))
.peek(this::trigger)
.map(Job::jobType).collect(toList());
}
/** Prevents jobs of the given type from starting, until the given time. */
public void pauseJob(ApplicationId id, JobType jobType, Instant until) {
if (until.isAfter(clock.instant().plus(maxPause)))
throw new IllegalArgumentException("Pause only allowed for up to " + maxPause);
applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application ->
applications().store(application.with(id.instance(),
instance -> instance.withJobPause(jobType, OptionalLong.of(until.toEpochMilli())))));
}
/** Triggers a change of this application, unless it already has a change. */
public void triggerChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if ( ! application.get().change().hasTargets())
forceChange(applicationId, change);
});
}
/** Overrides the given application's platform and application changes with any contained in the given change. */
public void forceChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if (change.application().isPresent())
application = application.withOutstandingChange(Change.empty());
applications().store(application.withChange(change.onTopOf(application.get().change())));
});
}
/** Cancels the indicated part of the given application's change. */
public void cancelChange(TenantAndApplicationId applicationId, ChangesToCancel cancellation) {
applications().lockApplicationOrThrow(applicationId, application -> {
Change change;
switch (cancellation) {
case ALL: change = Change.empty(); break;
case VERSIONS: change = Change.empty().withPin(); break;
case PLATFORM: change = application.get().change().withoutPlatform(); break;
case APPLICATION: change = application.get().change().withoutApplication(); break;
case PIN: change = application.get().change().withoutPin(); break;
default: throw new IllegalArgumentException("Unknown cancellation choice '" + cancellation + "'!");
}
applications().store(application.withChange(change));
});
}
public enum ChangesToCancel { ALL, PLATFORM, APPLICATION, VERSIONS, PIN }
private ApplicationController applications() {
return controller.applications();
}
private Optional<Run> successOn(JobStatus status, Versions versions) {
return status.lastSuccess().filter(run -> versions.targetsMatch(run.versions()));
}
private Optional<Deployment> deploymentFor(Instance instance, JobType jobType) {
return Optional.ofNullable(instance.deployments().get(jobType.zone(controller.system())));
}
private static <T extends Comparable<T>> Optional<T> max(Optional<T> o1, Optional<T> o2) {
return o1.isEmpty() ? o2 : o2.isEmpty() ? o1 : o1.get().compareTo(o2.get()) >= 0 ? o1 : o2;
}
/** Returns the set of all jobs which have changes to propagate from the upstream steps. */
private List<Job> computeReadyJobs() {
return ApplicationList.from(applications().asList())
.withProjectId()
.withChanges()
.withDeploymentSpec()
.idList().stream()
.map(this::computeReadyJobs)
.flatMap(Collection::stream)
.collect(toList());
}
/**
* Finds the next step to trigger for the given application, if any, and returns these as a list.
*/
private List<Job> computeReadyJobs(TenantAndApplicationId id) {
List<Job> jobs = new ArrayList<>();
applications().getApplication(id).ifPresent(application -> {
Collection<Instance> instances = application.deploymentSpec().instances().stream()
.flatMap(instance -> application.get(instance.name()).stream())
.collect(Collectors.toUnmodifiableList());
for (Instance instance : instances) {
var jobStatus = this.jobs.jobStatus(instance.id(), application.deploymentSpec());
Change change = application.change();
Optional<Instant> completedAt = max(Optional.ofNullable(jobStatus.get(systemTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())),
Optional.ofNullable(jobStatus.get(stagingTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())));
String reason = "New change available";
List<Job> testJobs = null;
DeploymentSteps steps = steps(application.deploymentSpec().requireInstance(instance.name()));
if (change.hasTargets()) {
for (Step step : steps.production()) {
List<JobType> stepJobs = steps.toJobs(step);
List<JobType> remainingJobs = stepJobs.stream().filter(job -> ! isComplete(change, change, instance, job, jobStatus.get(job))).collect(toList());
if ( ! remainingJobs.isEmpty()) {
for (JobType job : remainingJobs) {
Versions versions = Versions.from(change, application, deploymentFor(instance, job),
controller.systemVersion());
if (isTested(jobStatus, versions)) {
if (completedAt.isPresent() && canTrigger(job, jobStatus, versions, instance, application.deploymentSpec(), stepJobs)) {
jobs.add(deploymentJob(instance, versions, change, job, jobStatus.get(job), reason, completedAt.get()));
}
if ( ! alreadyTriggered(jobStatus, versions) && testJobs == null) {
testJobs = emptyList();
}
}
else if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(),
change, instance, jobStatus, versions,
String.format("Testing deployment for %s (%s)",
job.jobName(), versions.toString()),
completedAt.orElseGet(clock::instant));
}
}
completedAt = Optional.empty();
}
else {
if (stepJobs.isEmpty()) {
completedAt = completedAt.map(at -> at.plus(step.delay())).filter(at -> ! at.isAfter(clock.instant()));
reason += " after a delay of " + step.delay();
}
else {
completedAt = stepJobs.stream().map(job -> jobStatus.get(job).lastCompleted().get().end().get()).max(naturalOrder());
reason = "Available change in " + stepJobs.stream().map(JobType::jobName).collect(joining(", "));
}
}
}
}
if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(), change, instance, jobStatus,
Versions.from(application.outstandingChange().onTopOf(change),
application,
steps.sortedDeployments(instance.productionDeployments().values()).stream().findFirst(),
controller.systemVersion()),
"Testing last changes outside prod", clock.instant());
}
jobs.addAll(testJobs);
}
});
return Collections.unmodifiableList(jobs);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec, List<JobType> parallelJobs) {
if (status.get(job).isRunning()) return false;
if (parallelJobs != null && ! parallelJobs.containsAll(runningProductionJobs(status))) return false;
if (job.isProduction() && isSuspendedInAnotherZone(instance, job.zone(controller.system()))) return false;
return triggerAt(clock.instant(), job, status.get(job), versions, instance, deploymentSpec);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
return canTrigger(job, status, versions, instance, deploymentSpec, null);
}
private boolean isSuspendedInAnotherZone(Instance instance, ZoneId zone) {
for (Deployment deployment : instance.productionDeployments().values()) {
if ( ! deployment.zone().equals(zone)
&& controller.applications().isSuspended(new DeploymentId(instance.id(), deployment.zone())))
return true;
}
return false;
}
/** Returns whether the given job can trigger at the given instant */
public boolean triggerAt(Instant instant, JobType job, JobStatus jobStatus, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
if (instance.deploymentJobs().statusOf(job).map(status -> status.pausedUntil().orElse(0)).orElse(0L) > clock.millis()) return false;
if (jobStatus.lastTriggered().isEmpty()) return true;
if (jobStatus.isSuccess()) return true;
if (jobStatus.lastCompleted().isEmpty()) return true;
if (jobStatus.firstFailing().isEmpty()) return true;
if ( ! versions.targetsMatch(jobStatus.lastCompleted().get().versions())) return true;
if (deploymentSpec.requireInstance(instance.name()).upgradePolicy() == DeploymentSpec.UpgradePolicy.canary) return true;
Instant firstFailing = jobStatus.firstFailing().get().end().get();
Instant lastCompleted = jobStatus.lastCompleted().get().end().get();
if (firstFailing.isAfter(instant.minus(Duration.ofMinutes(1)))) return true;
if (job.isTest() && jobStatus.isOutOfCapacity()) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(1)));
}
if (firstFailing.isAfter(instant.minus(Duration.ofHours(1)))) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(10)));
}
return lastCompleted.isBefore(instant.minus(Duration.ofHours(2)));
}
private List<JobType> runningProductionJobs(Map<JobType, JobStatus> status) {
return status.values().parallelStream()
.filter(job -> job.isRunning())
.map(job -> job.job().type())
.filter(JobType::isProduction)
.collect(toList());
}
/**
* Returns whether the given change is complete for the given application for the given job.
*
* Any job is complete if the given change is already successful on that job.
* A production job is also considered complete if its current change is strictly dominated by what
* is already deployed in its zone, i.e., no parts of the change are upgrades, and the full current
* change for the application downgrades the deployment, which is an acknowledgement that the deployed
* version is broken somehow, such that the job may be locked in failure until a new version is released.
*
* Additionally, if the application is pinned to a Vespa version, and the given change has a (this) platform,
* the deployment for the job must be on the pinned version.
*/
public boolean isComplete(Change change, Change fullChange, Instance instance, JobType jobType,
JobStatus status) {
Optional<Deployment> existingDeployment = deploymentFor(instance, jobType);
if ( change.isPinned()
&& change.platform().isPresent()
&& ! existingDeployment.map(Deployment::version).equals(change.platform()))
return false;
return status.lastSuccess()
.map(run -> change.platform().map(run.versions().targetPlatform()::equals).orElse(true)
&& change.application().map(run.versions().targetApplication()::equals).orElse(true))
.orElse(false)
|| jobType.isProduction()
&& existingDeployment.map(deployment -> ! isUpgrade(change, deployment) && isDowngrade(fullChange, deployment))
.orElse(false);
}
private static boolean isUpgrade(Change change, Deployment deployment) {
return change.upgrades(deployment.version()) || change.upgrades(deployment.applicationVersion());
}
private static boolean isDowngrade(Change change, Deployment deployment) {
return change.downgrades(deployment.version()) || change.downgrades(deployment.applicationVersion());
}
private boolean isTested(Map<JobType, JobStatus> status, Versions versions) {
return testedIn(systemTest, status.get(systemTest), versions)
&& testedIn(stagingTest, status.get(stagingTest), versions)
|| alreadyTriggered(status, versions);
}
public boolean testedIn(JobType testType, JobStatus status, Versions versions) {
if (testType == systemTest)
return successOn(status, versions).isPresent();
if (testType == stagingTest)
return successOn(status, versions).map(Run::versions).filter(versions::sourcesMatchIfPresent).isPresent();
throw new IllegalArgumentException(testType + " is not a test job!");
}
public boolean alreadyTriggered(Map<JobType, JobStatus> status, Versions versions) {
return status.values().stream()
.filter(job -> job.job().type().isProduction())
.anyMatch(job -> job.lastTriggered()
.map(Run::versions)
.filter(versions::targetsMatch)
.filter(versions::sourcesMatchIfPresent)
.isPresent());
}
private boolean acceptNewApplicationVersion(Application application) {
if ( ! application.deploymentSpec().instances().stream()
.allMatch(instance -> instance.canChangeRevisionAt(clock.instant()))) return false;
if (application.change().application().isPresent()) return true;
for (Instance instance : application.instances().values())
if (instance.deploymentJobs().hasFailures()) return true;
return application.change().platform().isEmpty();
}
private Change remainingChange(Application application) {
Change change = application.change();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutApplication(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutPlatform();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutPlatform(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutApplication();
return change;
}
/**
* Returns the list of test jobs that should run now, and that need to succeed on the given versions for it to be considered tested.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince) {
return testJobs(deploymentSpec, change, instance, status, versions, reason, availableSince,
jobType -> canTrigger(jobType, status, versions, instance, deploymentSpec));
}
/**
* Returns the list of test jobs that need to succeed on the given versions for it to be considered tested, filtered by the given condition.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince, Predicate<JobType> condition) {
List<Job> jobs = new ArrayList<>();
for (JobType jobType : new DeploymentSteps(deploymentSpec.requireInstance(instance.name()), controller::system).testJobs()) {
Optional<Run> completion = successOn(status.get(jobType), versions)
.filter(run -> versions.sourcesMatchIfPresent(run.versions()) || jobType == systemTest);
if (completion.isEmpty() && condition.test(jobType))
jobs.add(deploymentJob(instance, versions, change, jobType, status.get(jobType), reason, availableSince));
}
return jobs;
}
private static class Job extends BuildJob {
private final JobType jobType;
private final JobRun triggering;
private final Instant availableSince;
private final boolean isRetry;
private final boolean isApplicationUpgrade;
private Job(Instance instance, JobRun triggering, JobType jobType, Instant availableSince,
boolean isRetry, boolean isApplicationUpgrade) {
super(instance.id(), 0L, jobType.jobName());
this.jobType = jobType;
this.triggering = triggering;
this.availableSince = availableSince;
this.isRetry = isRetry;
this.isApplicationUpgrade = isApplicationUpgrade;
}
JobType jobType() { return jobType; }
Instant availableSince() { return availableSince; }
boolean isRetry() { return isRetry; }
boolean applicationUpgrade() { return isApplicationUpgrade; }
}
} | class DeploymentTrigger {
public static final Duration maxPause = Duration.ofDays(3);
private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName());
private final Controller controller;
private final Clock clock;
private final JobController jobs;
public DeploymentTrigger(Controller controller, Clock clock) {
this.controller = Objects.requireNonNull(controller, "controller cannot be null");
this.clock = Objects.requireNonNull(clock, "clock cannot be null");
this.jobs = controller.jobController();
}
public DeploymentSteps steps(DeploymentInstanceSpec spec) {
return new DeploymentSteps(spec, controller::system);
}
public void notifyOfSubmission(TenantAndApplicationId id, ApplicationVersion version, long projectId) {
if (applications().getApplication(id).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring submission from project '" + projectId +
"': Unknown application '" + id + "'");
return;
}
applications().lockApplicationOrThrow(id, application -> {
if (acceptNewApplicationVersion(application.get())) {
application = application.withChange(application.get().change().with(version))
.withOutstandingChange(Change.empty());
for (Run run : jobs.active(id))
if ( ! run.id().type().environment().isManuallyDeployed())
jobs.abort(run.id());
}
else
application = application.withOutstandingChange(Change.of(version));
application = application.withProjectId(OptionalLong.of(projectId));
application = application.withNewSubmission(version);
applications().store(application.withChange(remainingChange(application.get())));
});
}
/**
* Records information when a job completes (successfully or not). This information is used when deciding what to
* trigger next.
*/
public void notifyOfCompletion(JobReport report) {
log.log(LogLevel.DEBUG, String.format("Notified of %s for %s of %s (%d)",
report.jobError().map(e -> e.toString() + " error")
.orElse("success"),
report.jobType(),
report.applicationId(),
report.projectId()));
if (applications().getInstance(report.applicationId()).isEmpty()) {
log.log(LogLevel.WARNING, "Ignoring completion of job of project '" + report.projectId() +
"': Unknown application '" + report.applicationId() + "'");
return;
}
applications().lockApplicationOrThrow(TenantAndApplicationId.from(report.applicationId()), application -> {
var status = application.get().require(report.applicationId().instance())
.deploymentJobs().statusOf(report.jobType());
var triggering = status.filter(job -> job.lastTriggered().isPresent()
&& job.lastCompleted()
.map(completion -> ! completion.at().isAfter(job.lastTriggered().get().at()))
.orElse(true))
.orElseThrow(() -> new IllegalStateException("Notified of completion of " + report.jobType().jobName() + " for " +
report.applicationId() + ", but that has not been triggered; last was " +
status.flatMap(job -> job.lastTriggered().map(run -> run.at().toString()))
.orElse("never")))
.lastTriggered().get();
application = application.with(report.applicationId().instance(),
instance -> instance.withJobCompletion(report.jobType(),
triggering.completion(report.buildNumber(), clock.instant()),
report.jobError()));
applications().store(application.withChange(remainingChange(application.get())));
});
}
/**
* Finds and triggers jobs that can and should run but are currently not, and returns the number of triggered jobs.
*
* Only one job is triggered each run for test jobs, since their environments have limited capacity.
*/
public long triggerReadyJobs() {
return computeReadyJobs().stream()
.collect(partitioningBy(job -> job.jobType().isTest()))
.entrySet().stream()
.flatMap(entry -> (entry.getKey()
? entry.getValue().stream()
.sorted(comparing(Job::isRetry)
.thenComparing(Job::applicationUpgrade)
.reversed()
.thenComparing(Job::availableSince))
.collect(groupingBy(Job::jobType))
: entry.getValue().stream()
.collect(groupingBy(Job::applicationId)))
.values().stream()
.map(jobs -> (Supplier<Long>) jobs.stream()
.filter(this::trigger)
.limit(entry.getKey() ? 1 : Long.MAX_VALUE)::count))
.parallel().map(Supplier::get).reduce(0L, Long::sum);
}
/**
* Attempts to trigger the given job for the given application and returns the outcome.
*
* If the build service can not find the given job, or claims it is illegal to trigger it,
* the project id is removed from the application owning the job, to prevent further trigger attempts.
*/
public boolean trigger(Job job) {
log.log(LogLevel.DEBUG, String.format("Triggering %s: %s", job, job.triggering));
try {
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application -> {
jobs.start(job.applicationId(), job.jobType, new Versions(job.triggering.platform(),
job.triggering.application(),
job.triggering.sourcePlatform(),
job.triggering.sourceApplication()));
applications().store(application.with(job.applicationId().instance(),
instance -> instance.withJobTriggering(job.jobType, job.triggering)));
});
return true;
}
catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception triggering " + job + ": " + e);
if (e instanceof NoSuchElementException || e instanceof IllegalArgumentException)
applications().lockApplicationOrThrow(TenantAndApplicationId.from(job.applicationId()), application ->
applications().store(application.withProjectId(OptionalLong.empty())));
return false;
}
}
/** Force triggering of a job for given instance. */
public List<JobType> forceTrigger(ApplicationId applicationId, JobType jobType, String user) {
Application application = applications().requireApplication(TenantAndApplicationId.from(applicationId));
Instance instance = application.require(applicationId.instance());
Versions versions = Versions.from(application.change(), application, deploymentFor(instance, jobType),
controller.systemVersion());
String reason = "Job triggered manually by " + user;
var jobStatus = jobs.deploymentStatus(application).instanceJobs(instance.name());
return (jobType.isProduction() && ! isTested(jobStatus, versions)
? testJobs(application.deploymentSpec(), application.change(), instance, jobStatus, versions, reason, clock.instant(), __ -> true).stream()
: Stream.of(deploymentJob(instance, versions, application.change(), jobType, jobStatus.get(jobType), reason, clock.instant())))
.peek(this::trigger)
.map(Job::jobType).collect(toList());
}
/** Prevents jobs of the given type from starting, until the given time. */
public void pauseJob(ApplicationId id, JobType jobType, Instant until) {
if (until.isAfter(clock.instant().plus(maxPause)))
throw new IllegalArgumentException("Pause only allowed for up to " + maxPause);
applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application ->
applications().store(application.with(id.instance(),
instance -> instance.withJobPause(jobType, OptionalLong.of(until.toEpochMilli())))));
}
/** Triggers a change of this application, unless it already has a change. */
public void triggerChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if ( ! application.get().change().hasTargets())
forceChange(applicationId, change);
});
}
/** Overrides the given application's platform and application changes with any contained in the given change. */
public void forceChange(TenantAndApplicationId applicationId, Change change) {
applications().lockApplicationOrThrow(applicationId, application -> {
if (change.application().isPresent())
application = application.withOutstandingChange(Change.empty());
applications().store(application.withChange(change.onTopOf(application.get().change())));
});
}
/** Cancels the indicated part of the given application's change. */
public void cancelChange(TenantAndApplicationId applicationId, ChangesToCancel cancellation) {
applications().lockApplicationOrThrow(applicationId, application -> {
Change change;
switch (cancellation) {
case ALL: change = Change.empty(); break;
case VERSIONS: change = Change.empty().withPin(); break;
case PLATFORM: change = application.get().change().withoutPlatform(); break;
case APPLICATION: change = application.get().change().withoutApplication(); break;
case PIN: change = application.get().change().withoutPin(); break;
default: throw new IllegalArgumentException("Unknown cancellation choice '" + cancellation + "'!");
}
applications().store(application.withChange(change));
});
}
public enum ChangesToCancel { ALL, PLATFORM, APPLICATION, VERSIONS, PIN }
private ApplicationController applications() {
return controller.applications();
}
private Optional<Run> successOn(JobStatus status, Versions versions) {
return status.lastSuccess().filter(run -> versions.targetsMatch(run.versions()));
}
private Optional<Deployment> deploymentFor(Instance instance, JobType jobType) {
return Optional.ofNullable(instance.deployments().get(jobType.zone(controller.system())));
}
private static <T extends Comparable<T>> Optional<T> max(Optional<T> o1, Optional<T> o2) {
return o1.isEmpty() ? o2 : o2.isEmpty() ? o1 : o1.get().compareTo(o2.get()) >= 0 ? o1 : o2;
}
/** Returns the set of all jobs which have changes to propagate from the upstream steps. */
private List<Job> computeReadyJobs() {
return ApplicationList.from(applications().asList())
.withProjectId()
.withChanges()
.withDeploymentSpec()
.idList().stream()
.map(this::computeReadyJobs)
.flatMap(Collection::stream)
.collect(toList());
}
/**
* Finds the next step to trigger for the given application, if any, and returns these as a list.
*/
private List<Job> computeReadyJobs(TenantAndApplicationId id) {
List<Job> jobs = new ArrayList<>();
applications().getApplication(id).ifPresent(application -> {
Collection<Instance> instances = application.deploymentSpec().instances().stream()
.flatMap(instance -> application.get(instance.name()).stream())
.collect(Collectors.toUnmodifiableList());
DeploymentStatus deploymentStatus = this.jobs.deploymentStatus(application);
for (Instance instance : instances) {
var jobStatus = deploymentStatus.instanceJobs(instance.name());
Change change = application.change();
Optional<Instant> completedAt = max(Optional.ofNullable(jobStatus.get(systemTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())),
Optional.ofNullable(jobStatus.get(stagingTest))
.<Instant>flatMap(job -> job.lastSuccess().map(run -> run.end().get())));
String reason = "New change available";
List<Job> testJobs = null;
DeploymentSteps steps = steps(application.deploymentSpec().requireInstance(instance.name()));
if (change.hasTargets()) {
for (Step step : steps.production()) {
List<JobType> stepJobs = steps.toJobs(step);
List<JobType> remainingJobs = stepJobs.stream().filter(job -> ! isComplete(change, change, instance, job, jobStatus.get(job))).collect(toList());
if ( ! remainingJobs.isEmpty()) {
for (JobType job : remainingJobs) {
Versions versions = Versions.from(change, application, deploymentFor(instance, job),
controller.systemVersion());
if (isTested(jobStatus, versions)) {
if (completedAt.isPresent() && canTrigger(job, jobStatus, versions, instance, application.deploymentSpec(), stepJobs)) {
jobs.add(deploymentJob(instance, versions, change, job, jobStatus.get(job), reason, completedAt.get()));
}
if ( ! alreadyTriggered(jobStatus, versions) && testJobs == null) {
testJobs = emptyList();
}
}
else if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(),
change, instance, jobStatus, versions,
String.format("Testing deployment for %s (%s)",
job.jobName(), versions.toString()),
completedAt.orElseGet(clock::instant));
}
}
completedAt = Optional.empty();
}
else {
if (stepJobs.isEmpty()) {
completedAt = completedAt.map(at -> at.plus(step.delay())).filter(at -> ! at.isAfter(clock.instant()));
reason += " after a delay of " + step.delay();
}
else {
completedAt = stepJobs.stream().map(job -> jobStatus.get(job).lastCompleted().get().end().get()).max(naturalOrder());
reason = "Available change in " + stepJobs.stream().map(JobType::jobName).collect(joining(", "));
}
}
}
}
if (testJobs == null) {
testJobs = testJobs(application.deploymentSpec(), change, instance, jobStatus,
Versions.from(application.outstandingChange().onTopOf(change),
application,
steps.sortedDeployments(instance.productionDeployments().values()).stream().findFirst(),
controller.systemVersion()),
"Testing last changes outside prod", clock.instant());
}
jobs.addAll(testJobs);
}
});
return Collections.unmodifiableList(jobs);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec, List<JobType> parallelJobs) {
if (status.get(job).isRunning()) return false;
if (parallelJobs != null && ! parallelJobs.containsAll(runningProductionJobs(status))) return false;
if (job.isProduction() && isSuspendedInAnotherZone(instance, job.zone(controller.system()))) return false;
return triggerAt(clock.instant(), job, status.get(job), versions, instance, deploymentSpec);
}
/** Returns whether given job should be triggered */
private boolean canTrigger(JobType job, Map<JobType, JobStatus> status, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
return canTrigger(job, status, versions, instance, deploymentSpec, null);
}
private boolean isSuspendedInAnotherZone(Instance instance, ZoneId zone) {
for (Deployment deployment : instance.productionDeployments().values()) {
if ( ! deployment.zone().equals(zone)
&& controller.applications().isSuspended(new DeploymentId(instance.id(), deployment.zone())))
return true;
}
return false;
}
/** Returns whether the given job can trigger at the given instant */
public boolean triggerAt(Instant instant, JobType job, JobStatus jobStatus, Versions versions, Instance instance, DeploymentSpec deploymentSpec) {
if (instance.deploymentJobs().statusOf(job).map(status -> status.pausedUntil().orElse(0)).orElse(0L) > clock.millis()) return false;
if (jobStatus.lastTriggered().isEmpty()) return true;
if (jobStatus.isSuccess()) return true;
if (jobStatus.lastCompleted().isEmpty()) return true;
if (jobStatus.firstFailing().isEmpty()) return true;
if ( ! versions.targetsMatch(jobStatus.lastCompleted().get().versions())) return true;
if (deploymentSpec.requireInstance(instance.name()).upgradePolicy() == DeploymentSpec.UpgradePolicy.canary) return true;
Instant firstFailing = jobStatus.firstFailing().get().end().get();
Instant lastCompleted = jobStatus.lastCompleted().get().end().get();
if (firstFailing.isAfter(instant.minus(Duration.ofMinutes(1)))) return true;
if (job.isTest() && jobStatus.isOutOfCapacity()) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(1)));
}
if (firstFailing.isAfter(instant.minus(Duration.ofHours(1)))) {
return lastCompleted.isBefore(instant.minus(Duration.ofMinutes(10)));
}
return lastCompleted.isBefore(instant.minus(Duration.ofHours(2)));
}
private List<JobType> runningProductionJobs(Map<JobType, JobStatus> status) {
return status.values().parallelStream()
.filter(job -> job.isRunning())
.map(job -> job.id().type())
.filter(JobType::isProduction)
.collect(toList());
}
/**
* Returns whether the given change is complete for the given application for the given job.
*
* Any job is complete if the given change is already successful on that job.
* A production job is also considered complete if its current change is strictly dominated by what
* is already deployed in its zone, i.e., no parts of the change are upgrades, and the full current
* change for the application downgrades the deployment, which is an acknowledgement that the deployed
* version is broken somehow, such that the job may be locked in failure until a new version is released.
*
* Additionally, if the application is pinned to a Vespa version, and the given change has a (this) platform,
* the deployment for the job must be on the pinned version.
*/
public boolean isComplete(Change change, Change fullChange, Instance instance, JobType jobType,
JobStatus status) {
Optional<Deployment> existingDeployment = deploymentFor(instance, jobType);
if ( change.isPinned()
&& change.platform().isPresent()
&& ! existingDeployment.map(Deployment::version).equals(change.platform()))
return false;
return status.lastSuccess()
.map(run -> change.platform().map(run.versions().targetPlatform()::equals).orElse(true)
&& change.application().map(run.versions().targetApplication()::equals).orElse(true))
.orElse(false)
|| jobType.isProduction()
&& existingDeployment.map(deployment -> ! isUpgrade(change, deployment) && isDowngrade(fullChange, deployment))
.orElse(false);
}
private static boolean isUpgrade(Change change, Deployment deployment) {
return change.upgrades(deployment.version()) || change.upgrades(deployment.applicationVersion());
}
private static boolean isDowngrade(Change change, Deployment deployment) {
return change.downgrades(deployment.version()) || change.downgrades(deployment.applicationVersion());
}
private boolean isTested(Map<JobType, JobStatus> status, Versions versions) {
return testedIn(systemTest, status.get(systemTest), versions)
&& testedIn(stagingTest, status.get(stagingTest), versions)
|| alreadyTriggered(status, versions);
}
public boolean testedIn(JobType testType, JobStatus status, Versions versions) {
if (testType == systemTest)
return successOn(status, versions).isPresent();
if (testType == stagingTest)
return successOn(status, versions).map(Run::versions).filter(versions::sourcesMatchIfPresent).isPresent();
throw new IllegalArgumentException(testType + " is not a test job!");
}
public boolean alreadyTriggered(Map<JobType, JobStatus> status, Versions versions) {
return status.values().stream()
.filter(job -> job.id().type().isProduction())
.anyMatch(job -> job.lastTriggered()
.map(Run::versions)
.filter(versions::targetsMatch)
.filter(versions::sourcesMatchIfPresent)
.isPresent());
}
private boolean acceptNewApplicationVersion(Application application) {
if ( ! application.deploymentSpec().instances().stream()
.allMatch(instance -> instance.canChangeRevisionAt(clock.instant()))) return false;
if (application.change().application().isPresent()) return true;
for (Instance instance : application.instances().values())
if (instance.deploymentJobs().hasFailures()) return true;
return application.change().platform().isEmpty();
}
private Change remainingChange(Application application) {
Change change = application.change();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutApplication(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutPlatform();
if (application.deploymentSpec().instances().stream()
.allMatch(spec -> {
DeploymentSteps steps = new DeploymentSteps(spec, controller::system);
return (steps.productionJobs().isEmpty() ? steps.testJobs() : steps.productionJobs())
.stream().allMatch(job -> isComplete(application.change().withoutPlatform(), application.change(), application.require(spec.name()), job, jobs.jobStatus(new JobId(application.id().instance(spec.name()), job))));
}))
change = change.withoutApplication();
return change;
}
/**
* Returns the list of test jobs that should run now, and that need to succeed on the given versions for it to be considered tested.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince) {
return testJobs(deploymentSpec, change, instance, status, versions, reason, availableSince,
jobType -> canTrigger(jobType, status, versions, instance, deploymentSpec));
}
/**
* Returns the list of test jobs that need to succeed on the given versions for it to be considered tested, filtered by the given condition.
*/
private List<Job> testJobs(DeploymentSpec deploymentSpec, Change change, Instance instance, Map<JobType, JobStatus> status, Versions versions,
String reason, Instant availableSince, Predicate<JobType> condition) {
List<Job> jobs = new ArrayList<>();
for (JobType jobType : new DeploymentSteps(deploymentSpec.requireInstance(instance.name()), controller::system).testJobs()) {
Optional<Run> completion = successOn(status.get(jobType), versions)
.filter(run -> versions.sourcesMatchIfPresent(run.versions()) || jobType == systemTest);
if (completion.isEmpty() && condition.test(jobType))
jobs.add(deploymentJob(instance, versions, change, jobType, status.get(jobType), reason, availableSince));
}
return jobs;
}
private static class Job {
private final ApplicationId instanceId;
private final JobType jobType;
private final JobRun triggering;
private final Instant availableSince;
private final boolean isRetry;
private final boolean isApplicationUpgrade;
private Job(Instance instance, JobRun triggering, JobType jobType, Instant availableSince,
boolean isRetry, boolean isApplicationUpgrade) {
this.instanceId = instance.id();
this.jobType = jobType;
this.triggering = triggering;
this.availableSince = availableSince;
this.isRetry = isRetry;
this.isApplicationUpgrade = isApplicationUpgrade;
}
ApplicationId applicationId() { return instanceId; }
JobType jobType() { return jobType; }
Instant availableSince() { return availableSince; }
boolean isRetry() { return isRetry; }
boolean applicationUpgrade() { return isApplicationUpgrade; }
}
} |
Ooooooh, good spot. That would have been painful. | 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()));
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;
} | toSlime(application.change(), root, deployingField); | 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, true);
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;
} | 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";
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 = latestVersionFromSlime(root.field(latestVersionField));
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
deployKeys, projectId, latestVersion, instances);
}
private Optional<ApplicationVersion> latestVersionFromSlime(Inspector latestVersionObject) {
if (latestVersionObject.valid())
return Optional.of(applicationVersionFromSlime(latestVersionObject));
return Optional.empty();
}
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, instanceName, 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, 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);
}
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, InstanceName instance, 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.instance(instance)
.map(spec -> globalEndpointRegions(spec, endpointId))
.orElse(Set.of());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
private Set<RegionName> globalEndpointRegions(DeploymentInstanceSpec spec, EndpointId endpointId) {
if (spec.globalServiceId().isPresent())
return spec.zones().stream()
.flatMap(zone -> zone.region().stream())
.collect(Collectors.toSet());
return spec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
}
} | 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";
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 = latestVersionFromSlime(root.field(latestVersionField));
return new Application(id, createdAt, deploymentSpec, validationOverrides, deploying, outstandingChange,
deploymentIssueId, ownershipIssueId, owner, majorVersion, metrics,
deployKeys, projectId, latestVersion, instances);
}
private Optional<ApplicationVersion> latestVersionFromSlime(Inspector latestVersionObject) {
if (latestVersionObject.valid())
return Optional.of(applicationVersionFromSlime(latestVersionObject));
return Optional.empty();
}
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, instanceName, 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, 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);
}
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, InstanceName instance, 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.instance(instance)
.map(spec -> globalEndpointRegions(spec, endpointId))
.orElse(Set.of());
assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions));
});
return List.copyOf(assignedRotations.values());
}
private Set<RegionName> globalEndpointRegions(DeploymentInstanceSpec spec, EndpointId endpointId) {
if (spec.globalServiceId().isPresent())
return spec.zones().stream()
.flatMap(zone -> zone.region().stream())
.collect(Collectors.toSet());
return spec.endpoints().stream()
.filter(endpoint -> endpoint.endpointId().equals(endpointId.id()))
.flatMap(endpoint -> endpoint.regions().stream())
.collect(Collectors.toSet());
}
} |
🔫 | public void testUpgradesPerMinute() {
assertEquals(0, Upgrader.numberOfApplicationsToUpgrade(10, 0, 0));
for (long now = 0; now < 60_000; now++)
assertEquals(7, Upgrader.numberOfApplicationsToUpgrade(60_000, now, 7));
assertEquals(3, Upgrader.numberOfApplicationsToUpgrade(30_000, 0, 7.5));
assertEquals(4, Upgrader.numberOfApplicationsToUpgrade(30_000, 30_000, 7.5));
assertEquals(4, Upgrader.numberOfApplicationsToUpgrade(30_000, 60_000, 7.5));
assertEquals(4, Upgrader.numberOfApplicationsToUpgrade(30_000, 90_000, 7.5));
assertEquals(3, Upgrader.numberOfApplicationsToUpgrade(30_000, 120_000, 7.5));
int upgrades = 0;
for (int i = 0, now = 0; i < 30; i++, now += 40_000)
upgrades += Upgrader.numberOfApplicationsToUpgrade(40_000, now, 8.7);
assertEquals(174, upgrades);
} | assertEquals(0, Upgrader.numberOfApplicationsToUpgrade(10, 0, 0)); | public void testUpgradesPerMinute() {
assertEquals(0, Upgrader.numberOfApplicationsToUpgrade(10, 0, 0));
for (long now = 0; now < 60_000; now++)
assertEquals(7, Upgrader.numberOfApplicationsToUpgrade(60_000, now, 7));
assertEquals(3, Upgrader.numberOfApplicationsToUpgrade(30_000, 0, 7.5));
assertEquals(4, Upgrader.numberOfApplicationsToUpgrade(30_000, 30_000, 7.5));
assertEquals(4, Upgrader.numberOfApplicationsToUpgrade(30_000, 60_000, 7.5));
assertEquals(4, Upgrader.numberOfApplicationsToUpgrade(30_000, 90_000, 7.5));
assertEquals(3, Upgrader.numberOfApplicationsToUpgrade(30_000, 120_000, 7.5));
int upgrades = 0;
for (int i = 0, now = 0; i < 30; i++, now += 40_000)
upgrades += Upgrader.numberOfApplicationsToUpgrade(40_000, now, 8.7);
assertEquals(174, upgrades);
} | class UpgraderTest {
private final DeploymentTester tester = new DeploymentTester().atHourOfDay(5);
@Test
public void testUpgrading() {
Version version0 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version0);
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("No applications: Nothing to do", 0, tester.jobs().active().size());
var canary0 = createAndDeploy("canary0", "canary");
var canary1 = createAndDeploy("canary1", "canary");
var default0 = createAndDeploy("default0", "default");
var default1 = createAndDeploy("default1", "default");
var default2 = createAndDeploy("default2", "default");
var conservative0 = createAndDeploy("conservative0", "conservative");
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("All already on the right version: Nothing to do", 0, tester.jobs().active().size());
Version version1 = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version1);
assertEquals(version1, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
canary0.deployPlatform(version1);
assertEquals(version1, tester.configServer().lastPrepareVersion().get());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("One canary pending; nothing else", 2, tester.jobs().active().size());
canary1.deployPlatform(version1);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Canaries done: Should upgrade defaults", 6, tester.jobs().active().size());
default0.deployPlatform(version1);
default1.deployPlatform(version1);
default2.deployPlatform(version1);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Normals done: Should upgrade conservatives", 2, tester.jobs().active().size());
conservative0.deployPlatform(version1);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Nothing to do", 0, tester.jobs().active().size());
Version version2 = Version.fromString("6.4");
tester.controllerTester().upgradeSystem(version2);
assertEquals(version2, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
canary0.runJob(systemTest);
canary0.timeOutUpgrade(stagingTest);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Version broken, but Canaries should keep trying", 3, tester.jobs().active().size());
Version version3 = Version.fromString("6.5");
tester.controllerTester().upgradeSystem(version3);
assertEquals(version3, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
canary0.abortJob(stagingTest);
canary1.abortJob(systemTest);
canary1.abortJob(stagingTest);
tester.triggerJobs();
assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
canary0.deployPlatform(version3);
assertEquals(version3, tester.configServer().lastPrepareVersion().get());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("One canary pending; nothing else", 2, tester.jobs().active().size());
canary1.deployPlatform(version3);
tester.controllerTester().computeVersionStatus();;
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Canaries done: Should upgrade defaults", 6, tester.jobs().active().size());
default0.runJob(systemTest);
default0.timeOutConvergence(stagingTest);
default1.deployPlatform(version3);
default2.deployPlatform(version3);
tester.controllerTester().computeVersionStatus();
assertEquals("Not enough evidence to mark this as neither broken nor high",
VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.triggerJobs();
assertEquals("Upgrade with error should retry", 1, tester.jobs().active().size());
default0.submit(applicationPackage("default"));
default0.jobAborted(stagingTest);
default0.deploy();
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Normals done: Should upgrade conservatives", 2, tester.jobs().active().size());
conservative0.deployPlatform(version3);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Applications are on " + version3 + " - nothing to do", 0, tester.jobs().active().size());
var default3 = createAndDeploy("default3", "default");
var default4 = createAndDeploy("default4", "default");
Version version4 = Version.fromString("6.6");
tester.controllerTester().upgradeSystem(version4);
tester.upgrader().maintain();
tester.triggerJobs();
canary0.deployPlatform(version4);
canary1.deployPlatform(version4);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Upgrade of defaults are scheduled", 10, tester.jobs().active().size());
for (var context : List.of(default0, default1, default2, default3, default4))
assertEquals(version4, context.application().change().platform().get());
default0.deployPlatform(version4);
Version version5 = Version.fromString("6.7");
tester.controllerTester().upgradeSystem(version5);
tester.upgrader().maintain();
tester.triggerJobs();
canary0.deployPlatform(version5);
canary1.deployPlatform(version5);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Upgrade of defaults are scheduled", 10, tester.jobs().active().size());
assertEquals(version5, default0.application().change().platform().get());
for (var context : List.of(default1, default2, default3, default4))
assertEquals(version4, context.application().change().platform().get());
default1.deployPlatform(version4);
default2.deployPlatform(version4);
default3.runJob(systemTest)
.failDeployment(stagingTest);
default4.runJob(systemTest)
.runJob(stagingTest)
.failDeployment(productionUsWest1);
tester.clock().advance(Duration.ofHours(1));
tester.upgrader().maintain();
default3.failDeployment(stagingTest);
default0.runJob(systemTest)
.failDeployment(stagingTest);
default1.runJob(systemTest)
.failDeployment(stagingTest);
default2.runJob(systemTest)
.failDeployment(stagingTest);
default3.runJob(systemTest)
.runJob(stagingTest)
.failDeployment(productionUsWest1);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
assertEquals(version4, default3.application().change().platform().get());
}
@Test
public void testUpgradingToVersionWhichBreaksSomeNonCanaries() {
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("No system version: Nothing to do", 0, tester.jobs().active().size());
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("No applications: Nothing to do", 0, tester.jobs().active().size());
var canary0 = createAndDeploy("canary0", "canary");
var canary1 = createAndDeploy("canary1", "canary");
var default0 = createAndDeploy("default0", "default");
var default1 = createAndDeploy("default1", "default");
var default2 = createAndDeploy("default2", "default");
var default3 = createAndDeploy("default3", "default");
var default4 = createAndDeploy("default4", "default");
var default5 = createAndDeploy("default5", "default");
var default6 = createAndDeploy("default6", "default");
var default7 = createAndDeploy("default7", "default");
var default8 = createAndDeploy("default8", "default");
var default9 = createAndDeploy("default9", "default");
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("All already on the right version: Nothing to do", 0, tester.jobs().active().size());
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
canary0.deployPlatform(version);
assertEquals(version, tester.configServer().lastPrepareVersion().get());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("One canary pending; nothing else", 2, tester.jobs().active().size());
canary1.deployPlatform(version);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Canaries done: Should upgrade defaults", 20, tester.jobs().active().size());
default0.deployPlatform(version);
for (var context : List.of(default1, default2, default3, default4))
context.failDeployment(systemTest);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.abortAll();
tester.triggerJobs();
assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence());
assertEquals("Upgrades are cancelled", 0, tester.jobs().active().size());
}
@Test
public void testVersionIsBrokenAfterAZoneIsLive() {
Version v0 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(v0);
var canary0 = createAndDeploy("canary0", "canary");
var canary1 = createAndDeploy("canary1", "canary");
var default0 = createAndDeploy("default0", "default");
var default1 = createAndDeploy("default1", "default");
var default2 = createAndDeploy("default2", "default");
var default3 = createAndDeploy("default3", "default");
var default4 = createAndDeploy("default4", "default");
Version v1 = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(v1);
assertEquals(v1, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
canary0.deployPlatform(v1);
canary1.deployPlatform(v1);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
Version v2 = Version.fromString("6.4");
tester.controllerTester().upgradeSystem(v2);
assertEquals(v2, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
canary0.deployPlatform(v2);
canary1.deployPlatform(v2);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.deploymentTrigger().cancelChange(default0.application().id(), ALL);
tester.deploymentTrigger().cancelChange(default1.application().id(), ALL);
tester.deploymentTrigger().cancelChange(default2.application().id(), ALL);
tester.deploymentTrigger().cancelChange(default3.application().id(), ALL);
default0.abortJob(systemTest).abortJob(stagingTest);
default1.abortJob(systemTest).abortJob(stagingTest);
default2.abortJob(systemTest).abortJob(stagingTest);
default3.abortJob(systemTest).abortJob(stagingTest);
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Upgrade scheduled for remaining apps", 10, tester.jobs().active().size());
assertEquals("default4 is still upgrading to 6.3", v1, default4.application().change().platform().get());
default0.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1).failDeployment(productionUsEast3);
default1.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1).failDeployment(productionUsEast3);
default2.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1).failDeployment(productionUsEast3);
default3.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1).failDeployment(productionUsEast3);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence());
assertEquals(v2, default0.deployment(ZoneId.from("prod.us-west-1")).version());
assertEquals(v0, default0.deployment(ZoneId.from("prod.us-east-3")).version());
tester.upgrader().maintain();
tester.abortAll();
tester.triggerJobs();
assertEquals("Upgrade to 5.1 scheduled for apps not completely on 5.1 or 5.2", 10, tester.jobs().active().size());
default0.runJob(systemTest).runJob(stagingTest).runJob(productionUsEast3);
assertEquals(v2, default0.deployment(ZoneId.from("prod.us-west-1")).version());
assertEquals("Last zone is upgraded to v1",
v1, default0.deployment(ZoneId.from("prod.us-east-3")).version());
assertFalse(default0.application().change().hasTargets());
}
@Test
public void testConfidenceIgnoresFailingApplicationChanges() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
var canary0 = createAndDeploy("canary0", "canary");
var canary1 = createAndDeploy("canary1", "canary");
var default0 = createAndDeploy("default0", "default");
var default1 = createAndDeploy("default1", "default");
var default2 = createAndDeploy("default2", "default");
var default3 = createAndDeploy("default3", "default");
var default4 = createAndDeploy("default4", "default");
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
canary0.deployPlatform(version);
canary1.deployPlatform(version);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
for (var context : List.of(default0, default1, default2, default3, default4))
context.deployPlatform(version);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence());
default0.submit(applicationPackage("default")).failDeployment(systemTest);
default1.submit(applicationPackage("default")).failDeployment(stagingTest);
default2.submit(applicationPackage("default")).failDeployment(systemTest);
default3.submit(applicationPackage("default")).failDeployment(stagingTest);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence());
}
@Test
public void testBlockVersionChange() {
tester.at(Instant.parse("2017-09-26T18:00:00.00Z"));
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("canary")
.blockChange(false, true, "tue", "18-19", "UTC")
.region("us-west-1")
.build();
var app = tester.newDeploymentContext().submit(applicationPackage).deploy();
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
assertTrue("No jobs scheduled", tester.jobs().active().isEmpty());
tester.clock().advance(Duration.ofHours(1));
tester.upgrader().maintain();
tester.triggerJobs();
assertTrue("No jobs scheduled", tester.jobs().active().isEmpty());
tester.clock().advance(Duration.ofHours(1));
tester.upgrader().maintain();
tester.triggerJobs();
assertFalse("Job is scheduled", tester.jobs().active().isEmpty());
app.deployPlatform(version);
assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
}
@Test
public void testBlockVersionChangeHalfwayThough() {
tester.at(Instant.parse("2017-09-26T17:00:00.00Z"));
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("canary")
.blockChange(false, true, "tue", "18-19", "UTC")
.region("us-west-1")
.region("us-central-1")
.region("us-east-3")
.build();
var app = tester.newDeploymentContext().submit(applicationPackage).deploy();
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
app.runJob(systemTest).runJob(stagingTest);
tester.triggerJobs();
tester.clock().advance(Duration.ofHours(1));
app.runJob(productionUsWest1);
tester.triggerJobs();
assertEquals(1, tester.jobs().active().size());
app.runJob(productionUsCentral1).runJob(productionUsEast3);
assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
}
@Test
public void testBlockVersionChangeHalfwayThoughThenNewRevision() {
tester.at(Instant.parse("2017-09-29T16:00:00.00Z"));
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.blockChange(false, true, "mon-fri", "00-09,17-23", "UTC")
.blockChange(false, true, "sat-sun", "00-23", "UTC")
.region("us-west-1")
.region("us-central-1")
.region("us-east-3")
.build();
var app = tester.newDeploymentContext().submit(applicationPackage).deploy();
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
app.runJob(systemTest).runJob(stagingTest);
tester.clock().advance(Duration.ofHours(1));
app.runJob(productionUsWest1);
tester.triggerJobs();
assertEquals(1, tester.jobs().active().size());
app.failDeployment(productionUsCentral1);
app.submit(applicationPackage);
tester.triggerJobs();
assertEquals(2, tester.jobs().active().size());
app.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1);
app.runJob(stagingTest);
tester.triggerJobs();
tester.clock().advance(Duration.ofHours(17));
version = Version.fromString("6.4");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
app.runJob(productionUsCentral1);
app.runJob(systemTest).runJob(stagingTest).runJob(productionUsEast3);
assertEquals(List.of(), tester.jobs().active());
assertEquals(new Version("6.3"), app.deployment(ZoneId.from("prod", "us-central-1")).version());
assertEquals(new Version("6.2"), app.deployment(ZoneId.from("prod", "us-east-3")).version());
tester.clock().advance(Duration.ofDays(2));
tester.upgrader().maintain();
tester.triggerJobs();
app.runJob(systemTest)
.runJob(stagingTest)
.runJob(productionUsWest1)
.runJob(productionUsCentral1)
.runJob(stagingTest)
.runJob(productionUsEast3);
assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
for (Deployment deployment : app.instance().deployments().values())
assertEquals(version, deployment.version());
}
@Test
public void testThrottlesUpgrades() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10),
new JobControl(tester.controllerTester().curator()),
tester.controllerTester().curator());
upgrader.setUpgradesPerMinute(0.2);
var canary0 = createAndDeploy("canary0", "canary");
var canary1 = createAndDeploy("canary1", "canary");
var canary2 = createAndDeploy("canary2", "canary");
var default0 = createAndDeploy("default0", "default");
var default1 = createAndDeploy("default1", "default");
var default2 = createAndDeploy("default2", "default");
var default3 = createAndDeploy("default3", "default");
var dev0 = tester.newDeploymentContext("tenant1", "dev0", "default")
.runJob(devUsEast1, DeploymentContext.applicationPackage);
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber());
upgrader.maintain();
tester.triggerJobs();
assertEquals(6, tester.jobs().active().size());
canary0.deployPlatform(version);
canary1.deployPlatform(version);
canary2.deployPlatform(version);
assertEquals(0, tester.jobs().active().size());
tester.controllerTester().computeVersionStatus();
upgrader.maintain();
tester.triggerJobs();
assertEquals(4, tester.jobs().active().size());
upgrader.maintain();
tester.triggerJobs();
assertEquals(8, tester.jobs().active().size());
}
@Test
public void testPinningMajorVersionInDeploymentXml() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage version6ApplicationPackage = new ApplicationPackageBuilder().majorVersion(6)
.region("us-west-1")
.build();
var canary0 = createAndDeploy("canary0", "canary");
var default0 = tester.newDeploymentContext().submit(version6ApplicationPackage).deploy();
version = Version.fromString("7.0");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.triggerJobs();
assertEquals(2, tester.jobs().active().size());
canary0.deployPlatform(version);
assertEquals(0, tester.jobs().active().size());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(0, tester.jobs().active().size());
}
@Test
public void testPinningMajorVersionInApplication() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
var canary0 = createAndDeploy("canary", "canary");
var default0 = tester.newDeploymentContext().submit().deploy();
tester.applications().lockApplicationOrThrow(default0.application().id(),
a -> tester.applications().store(a.withMajorVersion(6)));
assertEquals(OptionalInt.of(6), default0.application().majorVersion());
version = Version.fromString("7.0");
tester.controllerTester().upgradeSystem(version);
assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(2, tester.jobs().active().size());
canary0.deployPlatform(version);
assertEquals(0, tester.jobs().active().size());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(0, tester.jobs().active().size());
}
@Test
public void testPinningMajorVersionInUpgrader() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage version7CanaryApplicationPackage = new ApplicationPackageBuilder()
.majorVersion(7)
.upgradePolicy("canary")
.region("us-west-1")
.build();
ApplicationPackage version7DefaultApplicationPackage = new ApplicationPackageBuilder()
.majorVersion(7)
.upgradePolicy("default")
.region("us-west-1")
.build();
var canary0 = tester.newDeploymentContext("tenant1", "canary0", "default").submit(version7CanaryApplicationPackage).deploy();
var default0 = tester.newDeploymentContext("tenant1", "default0", "default").submit(version7DefaultApplicationPackage).deploy();
var default1 = tester.newDeploymentContext("tenant1", "default1", "default").submit(DeploymentContext.applicationPackage).deploy();
tester.upgrader().setTargetMajorVersion(Optional.of(6));
version = Version.fromString("7.0");
tester.controllerTester().upgradeSystem(version);
assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(2, tester.jobs().active().size());
canary0.deployPlatform(version);
assertEquals(0, tester.jobs().active().size());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(2, tester.jobs().active().size());
default0.deployPlatform(version);
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(0, tester.jobs().active().size());
tester.upgrader().setTargetMajorVersion(Optional.empty());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(2, tester.jobs().active().size());
default1.deployPlatform(version);
}
@Test
public void testAllowApplicationChangeDuringFailingUpgrade() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
var app = createAndDeploy("app", "default");
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
app.runJob(systemTest).runJob(stagingTest).failDeployment(productionUsWest1);
app.submit(applicationPackage("default"));
String applicationVersion = app.lastSubmission().get().id();
assertTrue("Change contains both upgrade and application change",
app.application().change().platform().get().equals(version) &&
app.application().change().application().get().id().equals(applicationVersion));
app.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1).runJob(productionUsEast3);
assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
for (Deployment deployment : app.instance().deployments().values()) {
assertEquals(version, deployment.version());
assertEquals(applicationVersion, deployment.applicationVersion().id());
}
}
@Test
public void testBlockRevisionChangeHalfwayThoughThenUpgrade() {
tester.at(Instant.parse("2017-09-26T17:00:00.00Z"));
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("canary")
.blockChange(true, false, "tue", "18-19", "UTC")
.region("us-west-1")
.region("us-central-1")
.region("us-east-3")
.build();
var app = tester.newDeploymentContext().submit(applicationPackage).deploy();
app.submit(applicationPackage);
tester.clock().advance(Duration.ofHours(1));
app.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1);
tester.triggerJobs();
assertEquals(1, tester.jobs().active().size());
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(1, tester.jobs().active().size());
app.runJob(productionUsCentral1).runJob(productionUsEast3);
assertEquals(List.of(), tester.jobs().active());
tester.upgrader().maintain();
app.deployPlatform(version);
assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
}
@Test
public void testBlockRevisionChangeHalfwayThoughThenNewRevision() {
tester.at(Instant.parse("2017-09-26T17:00:00.00Z"));
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("canary")
.blockChange(true, false, "tue", "18-19", "UTC")
.region("us-west-1")
.region("us-central-1")
.region("us-east-3")
.build();
var app = tester.newDeploymentContext().submit(applicationPackage).deploy();
app.submit(applicationPackage);
tester.clock().advance(Duration.ofHours(1));
app.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1);
tester.triggerJobs();
assertEquals(1, tester.jobs().active().size());
app.submit(applicationPackage);
tester.triggerJobs();
assertEquals(3, tester.jobs().active().size());
app.runJob(systemTest).runJob(stagingTest).runJob(productionUsCentral1).runJob(productionUsEast3);
assertEquals(List.of(), tester.jobs().active());
tester.outstandingChangeDeployer().run();
assertFalse(app.application().change().hasTargets());
tester.clock().advance(Duration.ofHours(2));
tester.outstandingChangeDeployer().run();
assertTrue(app.application().change().hasTargets());
app.runJob(productionUsWest1).runJob(productionUsCentral1).runJob(productionUsEast3);
assertFalse(app.application().change().hasTargets());
}
@Test
public void testPinning() {
Version version0 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version0);
var context = tester.newDeploymentContext();
tester.deploymentTrigger().forceChange(context.application().id(), Change.empty().withPin());
context.submit().deploy();
assertFalse(context.application().change().hasTargets());
assertTrue(context.application().change().isPinned());
assertEquals(3, context.instance().deployments().size());
Version version1 = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version1);
tester.upgrader().maintain();
assertFalse(context.application().change().hasTargets());
assertTrue(context.application().change().isPinned());
context.submit().deploy();
assertFalse(context.application().change().hasTargets());
assertTrue(context.application().change().isPinned());
tester.deploymentTrigger().cancelChange(context.application().id(), PIN);
tester.upgrader().maintain();
assertTrue(context.application().change().hasTargets());
assertFalse(context.application().change().isPinned());
tester.deploymentTrigger().forceChange(context.application().id(), Change.empty().withPin());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(version1, context.application().change().platform().get());
context.runJob(systemTest).runJob(stagingTest).runJob(productionUsCentral1)
.timeOutUpgrade(productionUsWest1);
tester.deploymentTrigger().cancelChange(context.application().id(), ALL);
tester.deploymentTrigger().forceChange(context.application().id(), Change.of(version0).withPin());
assertEquals(version0, context.application().change().platform().get());
tester.abortAll();
context.runJob(stagingTest).runJob(productionUsCentral1);
assertTrue(context.application().change().hasTargets());
context.runJob(productionUsWest1);
assertFalse(context.application().change().hasTargets());
}
@Test
public void upgradesToLatestAllowedMajor() {
Version version0 = Version.fromString("6.1");
tester.controllerTester().upgradeSystem(version0);
tester.upgrader().setTargetMajorVersion(Optional.of(6));
var app1 = createAndDeploy("app1", "default");
var app2 = createAndDeploy("app2", "default");
tester.controller().applications().lockApplicationIfPresent(app1.application().id(), app ->
tester.controller().applications().store(app.withChange(app.get().change().withPin())));
Version version1 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version1);
tester.upgrader().maintain();
app2.deployPlatform(version1);
Version version2 = Version.fromString("7.1");
tester.controllerTester().upgradeSystem(version2);
tester.controller().applications().lockApplicationIfPresent(app2.application().id(), app -> tester.applications().store(app.withMajorVersion(7)));
tester.upgrader().maintain();
assertEquals(version2, app2.application().change().platform().orElseThrow());
tester.controller().applications().lockApplicationIfPresent(app1.application().id(), app ->
tester.controller().applications().store(app.withChange(app.get().change().withoutPin())));
tester.upgrader().maintain();
assertEquals("Application upgrades to latest allowed major", version1,
app1.application().change().platform().orElseThrow());
}
@Test
public void testsEachUpgradeCombinationWithFailingDeployments() {
Version v1 = Version.fromString("6.1");
tester.controllerTester().upgradeSystem(v1);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-central-1")
.region("us-west-1")
.region("us-east-3")
.build();
var application = tester.newDeploymentContext().submit(applicationPackage).deploy();
Version v2 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(v2);
tester.upgrader().maintain();
assertEquals(Change.of(v2), application.application().change());
application.runJob(systemTest).runJob(stagingTest).runJob(productionUsCentral1);
tester.triggerJobs();
tester.upgrader().overrideConfidence(v2, VespaVersion.Confidence.broken);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
application.runJob(productionUsWest1);
assertTrue(application.application().change().isEmpty());
Version v3 = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(v3);
tester.upgrader().maintain();
assertEquals(Change.of(v3), application.application().change());
application.runJob(systemTest).runJob(stagingTest);
tester.triggerJobs();
application.runJob(stagingTest);
assertEquals(v1, application.instance().deploymentJobs().jobStatus().get(stagingTest).lastSuccess().get().sourcePlatform().get());
assertEquals(v3, application.instance().deploymentJobs().jobStatus().get(stagingTest).lastSuccess().get().platform());
application.timeOutUpgrade(productionUsCentral1);
application.runJob(productionUsCentral1);
assertEquals(v3, application.deployment(ZoneId.from("prod", "us-central-1")).version());
assertEquals(v2, application.deployment(ZoneId.from("prod", "us-west-1")).version());
assertEquals(v1, application.deployment(ZoneId.from("prod", "us-east-3")).version());
application.runJob(productionUsWest1);
application.runJob(productionUsEast3);
assertTrue("Upgrade complete", application.application().change().isEmpty());
}
@Test
private ApplicationPackage applicationPackage(String upgradePolicy) {
return new ApplicationPackageBuilder().upgradePolicy(upgradePolicy)
.region("us-west-1")
.region("us-east-3")
.build();
}
private DeploymentContext createAndDeploy(String applicationName, String upgradePolicy) {
return tester.newDeploymentContext("tenant1", applicationName, "default")
.submit(applicationPackage(upgradePolicy))
.deploy();
}
} | class UpgraderTest {
private final DeploymentTester tester = new DeploymentTester().atHourOfDay(5);
@Test
public void testUpgrading() {
Version version0 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version0);
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("No applications: Nothing to do", 0, tester.jobs().active().size());
var canary0 = createAndDeploy("canary0", "canary");
var canary1 = createAndDeploy("canary1", "canary");
var default0 = createAndDeploy("default0", "default");
var default1 = createAndDeploy("default1", "default");
var default2 = createAndDeploy("default2", "default");
var conservative0 = createAndDeploy("conservative0", "conservative");
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("All already on the right version: Nothing to do", 0, tester.jobs().active().size());
Version version1 = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version1);
assertEquals(version1, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
canary0.deployPlatform(version1);
assertEquals(version1, tester.configServer().lastPrepareVersion().get());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("One canary pending; nothing else", 2, tester.jobs().active().size());
canary1.deployPlatform(version1);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Canaries done: Should upgrade defaults", 6, tester.jobs().active().size());
default0.deployPlatform(version1);
default1.deployPlatform(version1);
default2.deployPlatform(version1);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Normals done: Should upgrade conservatives", 2, tester.jobs().active().size());
conservative0.deployPlatform(version1);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Nothing to do", 0, tester.jobs().active().size());
Version version2 = Version.fromString("6.4");
tester.controllerTester().upgradeSystem(version2);
assertEquals(version2, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
canary0.runJob(systemTest);
canary0.timeOutUpgrade(stagingTest);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Version broken, but Canaries should keep trying", 3, tester.jobs().active().size());
Version version3 = Version.fromString("6.5");
tester.controllerTester().upgradeSystem(version3);
assertEquals(version3, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
canary0.abortJob(stagingTest);
canary1.abortJob(systemTest);
canary1.abortJob(stagingTest);
tester.triggerJobs();
assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
canary0.deployPlatform(version3);
assertEquals(version3, tester.configServer().lastPrepareVersion().get());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("One canary pending; nothing else", 2, tester.jobs().active().size());
canary1.deployPlatform(version3);
tester.controllerTester().computeVersionStatus();;
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Canaries done: Should upgrade defaults", 6, tester.jobs().active().size());
default0.runJob(systemTest);
default0.timeOutConvergence(stagingTest);
default1.deployPlatform(version3);
default2.deployPlatform(version3);
tester.controllerTester().computeVersionStatus();
assertEquals("Not enough evidence to mark this as neither broken nor high",
VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.triggerJobs();
assertEquals("Upgrade with error should retry", 1, tester.jobs().active().size());
default0.submit(applicationPackage("default"));
default0.jobAborted(stagingTest);
default0.deploy();
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Normals done: Should upgrade conservatives", 2, tester.jobs().active().size());
conservative0.deployPlatform(version3);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Applications are on " + version3 + " - nothing to do", 0, tester.jobs().active().size());
var default3 = createAndDeploy("default3", "default");
var default4 = createAndDeploy("default4", "default");
Version version4 = Version.fromString("6.6");
tester.controllerTester().upgradeSystem(version4);
tester.upgrader().maintain();
tester.triggerJobs();
canary0.deployPlatform(version4);
canary1.deployPlatform(version4);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Upgrade of defaults are scheduled", 10, tester.jobs().active().size());
for (var context : List.of(default0, default1, default2, default3, default4))
assertEquals(version4, context.application().change().platform().get());
default0.deployPlatform(version4);
Version version5 = Version.fromString("6.7");
tester.controllerTester().upgradeSystem(version5);
tester.upgrader().maintain();
tester.triggerJobs();
canary0.deployPlatform(version5);
canary1.deployPlatform(version5);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Upgrade of defaults are scheduled", 10, tester.jobs().active().size());
assertEquals(version5, default0.application().change().platform().get());
for (var context : List.of(default1, default2, default3, default4))
assertEquals(version4, context.application().change().platform().get());
default1.deployPlatform(version4);
default2.deployPlatform(version4);
default3.runJob(systemTest)
.failDeployment(stagingTest);
default4.runJob(systemTest)
.runJob(stagingTest)
.failDeployment(productionUsWest1);
tester.clock().advance(Duration.ofHours(1));
tester.upgrader().maintain();
default3.failDeployment(stagingTest);
default0.runJob(systemTest)
.failDeployment(stagingTest);
default1.runJob(systemTest)
.failDeployment(stagingTest);
default2.runJob(systemTest)
.failDeployment(stagingTest);
default3.runJob(systemTest)
.runJob(stagingTest)
.failDeployment(productionUsWest1);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
assertEquals(version4, default3.application().change().platform().get());
}
@Test
public void testUpgradingToVersionWhichBreaksSomeNonCanaries() {
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("No system version: Nothing to do", 0, tester.jobs().active().size());
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("No applications: Nothing to do", 0, tester.jobs().active().size());
var canary0 = createAndDeploy("canary0", "canary");
var canary1 = createAndDeploy("canary1", "canary");
var default0 = createAndDeploy("default0", "default");
var default1 = createAndDeploy("default1", "default");
var default2 = createAndDeploy("default2", "default");
var default3 = createAndDeploy("default3", "default");
var default4 = createAndDeploy("default4", "default");
var default5 = createAndDeploy("default5", "default");
var default6 = createAndDeploy("default6", "default");
var default7 = createAndDeploy("default7", "default");
var default8 = createAndDeploy("default8", "default");
var default9 = createAndDeploy("default9", "default");
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("All already on the right version: Nothing to do", 0, tester.jobs().active().size());
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
canary0.deployPlatform(version);
assertEquals(version, tester.configServer().lastPrepareVersion().get());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("One canary pending; nothing else", 2, tester.jobs().active().size());
canary1.deployPlatform(version);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Canaries done: Should upgrade defaults", 20, tester.jobs().active().size());
default0.deployPlatform(version);
for (var context : List.of(default1, default2, default3, default4))
context.failDeployment(systemTest);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.abortAll();
tester.triggerJobs();
assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence());
assertEquals("Upgrades are cancelled", 0, tester.jobs().active().size());
}
@Test
public void testVersionIsBrokenAfterAZoneIsLive() {
Version v0 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(v0);
var canary0 = createAndDeploy("canary0", "canary");
var canary1 = createAndDeploy("canary1", "canary");
var default0 = createAndDeploy("default0", "default");
var default1 = createAndDeploy("default1", "default");
var default2 = createAndDeploy("default2", "default");
var default3 = createAndDeploy("default3", "default");
var default4 = createAndDeploy("default4", "default");
Version v1 = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(v1);
assertEquals(v1, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
canary0.deployPlatform(v1);
canary1.deployPlatform(v1);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
Version v2 = Version.fromString("6.4");
tester.controllerTester().upgradeSystem(v2);
assertEquals(v2, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
canary0.deployPlatform(v2);
canary1.deployPlatform(v2);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.deploymentTrigger().cancelChange(default0.application().id(), ALL);
tester.deploymentTrigger().cancelChange(default1.application().id(), ALL);
tester.deploymentTrigger().cancelChange(default2.application().id(), ALL);
tester.deploymentTrigger().cancelChange(default3.application().id(), ALL);
default0.abortJob(systemTest).abortJob(stagingTest);
default1.abortJob(systemTest).abortJob(stagingTest);
default2.abortJob(systemTest).abortJob(stagingTest);
default3.abortJob(systemTest).abortJob(stagingTest);
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals("Upgrade scheduled for remaining apps", 10, tester.jobs().active().size());
assertEquals("default4 is still upgrading to 6.3", v1, default4.application().change().platform().get());
default0.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1).failDeployment(productionUsEast3);
default1.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1).failDeployment(productionUsEast3);
default2.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1).failDeployment(productionUsEast3);
default3.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1).failDeployment(productionUsEast3);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence());
assertEquals(v2, default0.deployment(ZoneId.from("prod.us-west-1")).version());
assertEquals(v0, default0.deployment(ZoneId.from("prod.us-east-3")).version());
tester.upgrader().maintain();
tester.abortAll();
tester.triggerJobs();
assertEquals("Upgrade to 5.1 scheduled for apps not completely on 5.1 or 5.2", 10, tester.jobs().active().size());
default0.runJob(systemTest).runJob(stagingTest).runJob(productionUsEast3);
assertEquals(v2, default0.deployment(ZoneId.from("prod.us-west-1")).version());
assertEquals("Last zone is upgraded to v1",
v1, default0.deployment(ZoneId.from("prod.us-east-3")).version());
assertFalse(default0.application().change().hasTargets());
}
@Test
public void testConfidenceIgnoresFailingApplicationChanges() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
var canary0 = createAndDeploy("canary0", "canary");
var canary1 = createAndDeploy("canary1", "canary");
var default0 = createAndDeploy("default0", "default");
var default1 = createAndDeploy("default1", "default");
var default2 = createAndDeploy("default2", "default");
var default3 = createAndDeploy("default3", "default");
var default4 = createAndDeploy("default4", "default");
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
canary0.deployPlatform(version);
canary1.deployPlatform(version);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
for (var context : List.of(default0, default1, default2, default3, default4))
context.deployPlatform(version);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence());
default0.submit(applicationPackage("default")).failDeployment(systemTest);
default1.submit(applicationPackage("default")).failDeployment(stagingTest);
default2.submit(applicationPackage("default")).failDeployment(systemTest);
default3.submit(applicationPackage("default")).failDeployment(stagingTest);
tester.controllerTester().computeVersionStatus();
assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence());
}
@Test
public void testBlockVersionChange() {
tester.at(Instant.parse("2017-09-26T18:00:00.00Z"));
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("canary")
.blockChange(false, true, "tue", "18-19", "UTC")
.region("us-west-1")
.build();
var app = tester.newDeploymentContext().submit(applicationPackage).deploy();
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
assertTrue("No jobs scheduled", tester.jobs().active().isEmpty());
tester.clock().advance(Duration.ofHours(1));
tester.upgrader().maintain();
tester.triggerJobs();
assertTrue("No jobs scheduled", tester.jobs().active().isEmpty());
tester.clock().advance(Duration.ofHours(1));
tester.upgrader().maintain();
tester.triggerJobs();
assertFalse("Job is scheduled", tester.jobs().active().isEmpty());
app.deployPlatform(version);
assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
}
@Test
public void testBlockVersionChangeHalfwayThough() {
tester.at(Instant.parse("2017-09-26T17:00:00.00Z"));
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("canary")
.blockChange(false, true, "tue", "18-19", "UTC")
.region("us-west-1")
.region("us-central-1")
.region("us-east-3")
.build();
var app = tester.newDeploymentContext().submit(applicationPackage).deploy();
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
app.runJob(systemTest).runJob(stagingTest);
tester.triggerJobs();
tester.clock().advance(Duration.ofHours(1));
app.runJob(productionUsWest1);
tester.triggerJobs();
assertEquals(1, tester.jobs().active().size());
app.runJob(productionUsCentral1).runJob(productionUsEast3);
assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
}
@Test
public void testBlockVersionChangeHalfwayThoughThenNewRevision() {
tester.at(Instant.parse("2017-09-29T16:00:00.00Z"));
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.blockChange(false, true, "mon-fri", "00-09,17-23", "UTC")
.blockChange(false, true, "sat-sun", "00-23", "UTC")
.region("us-west-1")
.region("us-central-1")
.region("us-east-3")
.build();
var app = tester.newDeploymentContext().submit(applicationPackage).deploy();
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
app.runJob(systemTest).runJob(stagingTest);
tester.clock().advance(Duration.ofHours(1));
app.runJob(productionUsWest1);
tester.triggerJobs();
assertEquals(1, tester.jobs().active().size());
app.failDeployment(productionUsCentral1);
app.submit(applicationPackage);
tester.triggerJobs();
assertEquals(2, tester.jobs().active().size());
app.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1);
app.runJob(stagingTest);
tester.triggerJobs();
tester.clock().advance(Duration.ofHours(17));
version = Version.fromString("6.4");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
app.runJob(productionUsCentral1);
app.runJob(systemTest).runJob(stagingTest).runJob(productionUsEast3);
assertEquals(List.of(), tester.jobs().active());
assertEquals(new Version("6.3"), app.deployment(ZoneId.from("prod", "us-central-1")).version());
assertEquals(new Version("6.2"), app.deployment(ZoneId.from("prod", "us-east-3")).version());
tester.clock().advance(Duration.ofDays(2));
tester.upgrader().maintain();
tester.triggerJobs();
app.runJob(systemTest)
.runJob(stagingTest)
.runJob(productionUsWest1)
.runJob(productionUsCentral1)
.runJob(stagingTest)
.runJob(productionUsEast3);
assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
for (Deployment deployment : app.instance().deployments().values())
assertEquals(version, deployment.version());
}
@Test
public void testThrottlesUpgrades() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10),
new JobControl(tester.controllerTester().curator()),
tester.controllerTester().curator());
upgrader.setUpgradesPerMinute(0.2);
var canary0 = createAndDeploy("canary0", "canary");
var canary1 = createAndDeploy("canary1", "canary");
var canary2 = createAndDeploy("canary2", "canary");
var default0 = createAndDeploy("default0", "default");
var default1 = createAndDeploy("default1", "default");
var default2 = createAndDeploy("default2", "default");
var default3 = createAndDeploy("default3", "default");
var dev0 = tester.newDeploymentContext("tenant1", "dev0", "default")
.runJob(devUsEast1, DeploymentContext.applicationPackage);
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber());
upgrader.maintain();
tester.triggerJobs();
assertEquals(6, tester.jobs().active().size());
canary0.deployPlatform(version);
canary1.deployPlatform(version);
canary2.deployPlatform(version);
assertEquals(0, tester.jobs().active().size());
tester.controllerTester().computeVersionStatus();
upgrader.maintain();
tester.triggerJobs();
assertEquals(4, tester.jobs().active().size());
upgrader.maintain();
tester.triggerJobs();
assertEquals(8, tester.jobs().active().size());
}
@Test
public void testPinningMajorVersionInDeploymentXml() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage version6ApplicationPackage = new ApplicationPackageBuilder().majorVersion(6)
.region("us-west-1")
.build();
var canary0 = createAndDeploy("canary0", "canary");
var default0 = tester.newDeploymentContext().submit(version6ApplicationPackage).deploy();
version = Version.fromString("7.0");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.triggerJobs();
assertEquals(2, tester.jobs().active().size());
canary0.deployPlatform(version);
assertEquals(0, tester.jobs().active().size());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(0, tester.jobs().active().size());
}
@Test
public void testPinningMajorVersionInApplication() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
var canary0 = createAndDeploy("canary", "canary");
var default0 = tester.newDeploymentContext().submit().deploy();
tester.applications().lockApplicationOrThrow(default0.application().id(),
a -> tester.applications().store(a.withMajorVersion(6)));
assertEquals(OptionalInt.of(6), default0.application().majorVersion());
version = Version.fromString("7.0");
tester.controllerTester().upgradeSystem(version);
assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(2, tester.jobs().active().size());
canary0.deployPlatform(version);
assertEquals(0, tester.jobs().active().size());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(0, tester.jobs().active().size());
}
@Test
public void testPinningMajorVersionInUpgrader() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage version7CanaryApplicationPackage = new ApplicationPackageBuilder()
.majorVersion(7)
.upgradePolicy("canary")
.region("us-west-1")
.build();
ApplicationPackage version7DefaultApplicationPackage = new ApplicationPackageBuilder()
.majorVersion(7)
.upgradePolicy("default")
.region("us-west-1")
.build();
var canary0 = tester.newDeploymentContext("tenant1", "canary0", "default").submit(version7CanaryApplicationPackage).deploy();
var default0 = tester.newDeploymentContext("tenant1", "default0", "default").submit(version7DefaultApplicationPackage).deploy();
var default1 = tester.newDeploymentContext("tenant1", "default1", "default").submit(DeploymentContext.applicationPackage).deploy();
tester.upgrader().setTargetMajorVersion(Optional.of(6));
version = Version.fromString("7.0");
tester.controllerTester().upgradeSystem(version);
assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(2, tester.jobs().active().size());
canary0.deployPlatform(version);
assertEquals(0, tester.jobs().active().size());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(2, tester.jobs().active().size());
default0.deployPlatform(version);
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(0, tester.jobs().active().size());
tester.upgrader().setTargetMajorVersion(Optional.empty());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(2, tester.jobs().active().size());
default1.deployPlatform(version);
}
@Test
public void testAllowApplicationChangeDuringFailingUpgrade() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
var app = createAndDeploy("app", "default");
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
app.runJob(systemTest).runJob(stagingTest).failDeployment(productionUsWest1);
app.submit(applicationPackage("default"));
String applicationVersion = app.lastSubmission().get().id();
assertTrue("Change contains both upgrade and application change",
app.application().change().platform().get().equals(version) &&
app.application().change().application().get().id().equals(applicationVersion));
app.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1).runJob(productionUsEast3);
assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
for (Deployment deployment : app.instance().deployments().values()) {
assertEquals(version, deployment.version());
assertEquals(applicationVersion, deployment.applicationVersion().id());
}
}
@Test
public void testBlockRevisionChangeHalfwayThoughThenUpgrade() {
tester.at(Instant.parse("2017-09-26T17:00:00.00Z"));
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("canary")
.blockChange(true, false, "tue", "18-19", "UTC")
.region("us-west-1")
.region("us-central-1")
.region("us-east-3")
.build();
var app = tester.newDeploymentContext().submit(applicationPackage).deploy();
app.submit(applicationPackage);
tester.clock().advance(Duration.ofHours(1));
app.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1);
tester.triggerJobs();
assertEquals(1, tester.jobs().active().size());
version = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(1, tester.jobs().active().size());
app.runJob(productionUsCentral1).runJob(productionUsEast3);
assertEquals(List.of(), tester.jobs().active());
tester.upgrader().maintain();
app.deployPlatform(version);
assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
}
@Test
public void testBlockRevisionChangeHalfwayThoughThenNewRevision() {
tester.at(Instant.parse("2017-09-26T17:00:00.00Z"));
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("canary")
.blockChange(true, false, "tue", "18-19", "UTC")
.region("us-west-1")
.region("us-central-1")
.region("us-east-3")
.build();
var app = tester.newDeploymentContext().submit(applicationPackage).deploy();
app.submit(applicationPackage);
tester.clock().advance(Duration.ofHours(1));
app.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1);
tester.triggerJobs();
assertEquals(1, tester.jobs().active().size());
app.submit(applicationPackage);
tester.triggerJobs();
assertEquals(3, tester.jobs().active().size());
app.runJob(systemTest).runJob(stagingTest).runJob(productionUsCentral1).runJob(productionUsEast3);
assertEquals(List.of(), tester.jobs().active());
tester.outstandingChangeDeployer().run();
assertFalse(app.application().change().hasTargets());
tester.clock().advance(Duration.ofHours(2));
tester.outstandingChangeDeployer().run();
assertTrue(app.application().change().hasTargets());
app.runJob(productionUsWest1).runJob(productionUsCentral1).runJob(productionUsEast3);
assertFalse(app.application().change().hasTargets());
}
@Test
public void testPinning() {
Version version0 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version0);
var context = tester.newDeploymentContext();
tester.deploymentTrigger().forceChange(context.application().id(), Change.empty().withPin());
context.submit().deploy();
assertFalse(context.application().change().hasTargets());
assertTrue(context.application().change().isPinned());
assertEquals(3, context.instance().deployments().size());
Version version1 = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(version1);
tester.upgrader().maintain();
assertFalse(context.application().change().hasTargets());
assertTrue(context.application().change().isPinned());
context.submit().deploy();
assertFalse(context.application().change().hasTargets());
assertTrue(context.application().change().isPinned());
tester.deploymentTrigger().cancelChange(context.application().id(), PIN);
tester.upgrader().maintain();
assertTrue(context.application().change().hasTargets());
assertFalse(context.application().change().isPinned());
tester.deploymentTrigger().forceChange(context.application().id(), Change.empty().withPin());
tester.upgrader().maintain();
tester.triggerJobs();
assertEquals(version1, context.application().change().platform().get());
context.runJob(systemTest).runJob(stagingTest).runJob(productionUsCentral1)
.timeOutUpgrade(productionUsWest1);
tester.deploymentTrigger().cancelChange(context.application().id(), ALL);
tester.deploymentTrigger().forceChange(context.application().id(), Change.of(version0).withPin());
assertEquals(version0, context.application().change().platform().get());
tester.abortAll();
context.runJob(stagingTest).runJob(productionUsCentral1);
assertTrue(context.application().change().hasTargets());
context.runJob(productionUsWest1);
assertFalse(context.application().change().hasTargets());
}
@Test
public void upgradesToLatestAllowedMajor() {
Version version0 = Version.fromString("6.1");
tester.controllerTester().upgradeSystem(version0);
tester.upgrader().setTargetMajorVersion(Optional.of(6));
var app1 = createAndDeploy("app1", "default");
var app2 = createAndDeploy("app2", "default");
tester.controller().applications().lockApplicationIfPresent(app1.application().id(), app ->
tester.controller().applications().store(app.withChange(app.get().change().withPin())));
Version version1 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version1);
tester.upgrader().maintain();
app2.deployPlatform(version1);
Version version2 = Version.fromString("7.1");
tester.controllerTester().upgradeSystem(version2);
tester.controller().applications().lockApplicationIfPresent(app2.application().id(), app -> tester.applications().store(app.withMajorVersion(7)));
tester.upgrader().maintain();
assertEquals(version2, app2.application().change().platform().orElseThrow());
tester.controller().applications().lockApplicationIfPresent(app1.application().id(), app ->
tester.controller().applications().store(app.withChange(app.get().change().withoutPin())));
tester.upgrader().maintain();
assertEquals("Application upgrades to latest allowed major", version1,
app1.application().change().platform().orElseThrow());
}
@Test
public void testsEachUpgradeCombinationWithFailingDeployments() {
Version v1 = Version.fromString("6.1");
tester.controllerTester().upgradeSystem(v1);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-central-1")
.region("us-west-1")
.region("us-east-3")
.build();
var application = tester.newDeploymentContext().submit(applicationPackage).deploy();
Version v2 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(v2);
tester.upgrader().maintain();
assertEquals(Change.of(v2), application.application().change());
application.runJob(systemTest).runJob(stagingTest).runJob(productionUsCentral1);
tester.triggerJobs();
tester.upgrader().overrideConfidence(v2, VespaVersion.Confidence.broken);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
application.runJob(productionUsWest1);
assertTrue(application.application().change().isEmpty());
Version v3 = Version.fromString("6.3");
tester.controllerTester().upgradeSystem(v3);
tester.upgrader().maintain();
assertEquals(Change.of(v3), application.application().change());
application.runJob(systemTest).runJob(stagingTest);
tester.triggerJobs();
application.runJob(stagingTest);
assertEquals(v1, application.instance().deploymentJobs().jobStatus().get(stagingTest).lastSuccess().get().sourcePlatform().get());
assertEquals(v3, application.instance().deploymentJobs().jobStatus().get(stagingTest).lastSuccess().get().platform());
application.timeOutUpgrade(productionUsCentral1);
application.runJob(productionUsCentral1);
assertEquals(v3, application.deployment(ZoneId.from("prod", "us-central-1")).version());
assertEquals(v2, application.deployment(ZoneId.from("prod", "us-west-1")).version());
assertEquals(v1, application.deployment(ZoneId.from("prod", "us-east-3")).version());
application.runJob(productionUsWest1);
application.runJob(productionUsEast3);
assertTrue("Upgrade complete", application.application().change().isEmpty());
}
@Test
private ApplicationPackage applicationPackage(String upgradePolicy) {
return new ApplicationPackageBuilder().upgradePolicy(upgradePolicy)
.region("us-west-1")
.region("us-east-3")
.build();
}
private DeploymentContext createAndDeploy(String applicationName, String upgradePolicy) {
return tester.newDeploymentContext("tenant1", applicationName, "default")
.submit(applicationPackage(upgradePolicy))
.deploy();
}
} |
Should be determined automatically by using `CuratorDatabaseClient#cluster`. | private boolean shouldReboot(Node node) {
if (node.status().reboot().pending()) return false;
var rebootEvents = EnumSet.of(History.Event.Type.provisioned, History.Event.Type.rebooted, History.Event.Type.osUpgraded);
var rebootInterval = Duration.ofDays(rebootIntervalInDays.value());
Optional<Duration> overdue = node.history().events().stream()
.filter(event -> rebootEvents.contains(event.type()))
.map(History.Event::at)
.max(Comparator.naturalOrder())
.map(lastReboot -> Duration.between(lastReboot, clock.instant()).minus(rebootInterval));
if (overdue.isEmpty())
return random.nextDouble() < interval().getSeconds() / (double) rebootInterval.getSeconds();
if (overdue.get().isNegative())
return false;
int configServers = 3;
long secondsRemaining = Math.max(0, rebootInterval.getSeconds() - overdue.get().getSeconds());
double runsRemaining = configServers * secondsRemaining / (double) interval().getSeconds();
double probability = 1 / (1 + runsRemaining);
return random.nextDouble() < probability;
} | int configServers = 3; | private boolean shouldReboot(Node node) {
if (node.status().reboot().pending()) return false;
var rebootEvents = EnumSet.of(History.Event.Type.provisioned, History.Event.Type.rebooted, History.Event.Type.osUpgraded);
var rebootInterval = Duration.ofDays(rebootIntervalInDays.value());
Optional<Duration> overdue = node.history().events().stream()
.filter(event -> rebootEvents.contains(event.type()))
.map(History.Event::at)
.max(Comparator.naturalOrder())
.map(lastReboot -> Duration.between(lastReboot, clock.instant()).minus(rebootInterval));
if (overdue.isEmpty())
return random.nextDouble() < interval().getSeconds() / (double) rebootInterval.getSeconds();
if (overdue.get().isNegative())
return false;
int configServers = 3;
long secondsRemaining = Math.max(0, rebootInterval.getSeconds() - overdue.get().getSeconds());
double runsRemaining = configServers * secondsRemaining / (double) interval().getSeconds();
double probability = 1 / (1 + runsRemaining);
return random.nextDouble() < probability;
} | class NodeRebooter extends Maintainer {
private final IntFlag rebootIntervalInDays;
private final Clock clock;
private final Random random;
NodeRebooter(NodeRepository nodeRepository, Clock clock, FlagSource flagSource) {
super(nodeRepository, Duration.ofMinutes(25));
this.rebootIntervalInDays = Flags.REBOOT_INTERVAL_IN_DAYS.bindTo(flagSource);
this.clock = clock;
this.random = new Random(clock.millis());
}
@Override
protected void maintain() {
List<Node> nodesToReboot = nodeRepository().getNodes(Node.State.active, Node.State.ready).stream()
.filter(node -> node.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.filter(this::shouldReboot)
.collect(Collectors.toList());
if (!nodesToReboot.isEmpty())
nodeRepository().reboot(NodeListFilter.from(nodesToReboot));
}
} | class NodeRebooter extends Maintainer {
private final IntFlag rebootIntervalInDays;
private final Clock clock;
private final Random random;
NodeRebooter(NodeRepository nodeRepository, Clock clock, FlagSource flagSource) {
super(nodeRepository, Duration.ofMinutes(25));
this.rebootIntervalInDays = Flags.REBOOT_INTERVAL_IN_DAYS.bindTo(flagSource);
this.clock = clock;
this.random = new Random(clock.millis());
}
@Override
protected void maintain() {
List<Node> nodesToReboot = nodeRepository().getNodes(Node.State.active, Node.State.ready).stream()
.filter(node -> node.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.filter(this::shouldReboot)
.collect(Collectors.toList());
if (!nodesToReboot.isEmpty())
nodeRepository().reboot(NodeListFilter.from(nodesToReboot));
}
} |
Fixed in #11313 | private boolean shouldReboot(Node node) {
if (node.status().reboot().pending()) return false;
var rebootEvents = EnumSet.of(History.Event.Type.provisioned, History.Event.Type.rebooted, History.Event.Type.osUpgraded);
var rebootInterval = Duration.ofDays(rebootIntervalInDays.value());
Optional<Duration> overdue = node.history().events().stream()
.filter(event -> rebootEvents.contains(event.type()))
.map(History.Event::at)
.max(Comparator.naturalOrder())
.map(lastReboot -> Duration.between(lastReboot, clock.instant()).minus(rebootInterval));
if (overdue.isEmpty())
return random.nextDouble() < interval().getSeconds() / (double) rebootInterval.getSeconds();
if (overdue.get().isNegative())
return false;
int configServers = 3;
long secondsRemaining = Math.max(0, rebootInterval.getSeconds() - overdue.get().getSeconds());
double runsRemaining = configServers * secondsRemaining / (double) interval().getSeconds();
double probability = 1 / (1 + runsRemaining);
return random.nextDouble() < probability;
} | int configServers = 3; | private boolean shouldReboot(Node node) {
if (node.status().reboot().pending()) return false;
var rebootEvents = EnumSet.of(History.Event.Type.provisioned, History.Event.Type.rebooted, History.Event.Type.osUpgraded);
var rebootInterval = Duration.ofDays(rebootIntervalInDays.value());
Optional<Duration> overdue = node.history().events().stream()
.filter(event -> rebootEvents.contains(event.type()))
.map(History.Event::at)
.max(Comparator.naturalOrder())
.map(lastReboot -> Duration.between(lastReboot, clock.instant()).minus(rebootInterval));
if (overdue.isEmpty())
return random.nextDouble() < interval().getSeconds() / (double) rebootInterval.getSeconds();
if (overdue.get().isNegative())
return false;
int configServers = 3;
long secondsRemaining = Math.max(0, rebootInterval.getSeconds() - overdue.get().getSeconds());
double runsRemaining = configServers * secondsRemaining / (double) interval().getSeconds();
double probability = 1 / (1 + runsRemaining);
return random.nextDouble() < probability;
} | class NodeRebooter extends Maintainer {
private final IntFlag rebootIntervalInDays;
private final Clock clock;
private final Random random;
NodeRebooter(NodeRepository nodeRepository, Clock clock, FlagSource flagSource) {
super(nodeRepository, Duration.ofMinutes(25));
this.rebootIntervalInDays = Flags.REBOOT_INTERVAL_IN_DAYS.bindTo(flagSource);
this.clock = clock;
this.random = new Random(clock.millis());
}
@Override
protected void maintain() {
List<Node> nodesToReboot = nodeRepository().getNodes(Node.State.active, Node.State.ready).stream()
.filter(node -> node.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.filter(this::shouldReboot)
.collect(Collectors.toList());
if (!nodesToReboot.isEmpty())
nodeRepository().reboot(NodeListFilter.from(nodesToReboot));
}
} | class NodeRebooter extends Maintainer {
private final IntFlag rebootIntervalInDays;
private final Clock clock;
private final Random random;
NodeRebooter(NodeRepository nodeRepository, Clock clock, FlagSource flagSource) {
super(nodeRepository, Duration.ofMinutes(25));
this.rebootIntervalInDays = Flags.REBOOT_INTERVAL_IN_DAYS.bindTo(flagSource);
this.clock = clock;
this.random = new Random(clock.millis());
}
@Override
protected void maintain() {
List<Node> nodesToReboot = nodeRepository().getNodes(Node.State.active, Node.State.ready).stream()
.filter(node -> node.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.filter(this::shouldReboot)
.collect(Collectors.toList());
if (!nodesToReboot.isEmpty())
nodeRepository().reboot(NodeListFilter.from(nodesToReboot));
}
} |
Why not always serialize like we do for `diskSpeed`? | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
if (resources.storageType() != NodeResources.StorageType.any)
object.setString("storageType", serializer.toString(resources.storageType()));
} | if (resources.storageType() != NodeResources.StorageType.any) | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
if ( ! resources.diskSpeed().isDefault())
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
if ( ! resources.storageType().isDefault())
object.setString("storageType", serializer.toString(resources.storageType()));
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
if (node.flavor().resources().storageType() != NodeResources.StorageType.any)
object.setBool("remoteStorage", node.flavor().resources().storageType() == NodeResources.StorageType.remote);
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
if (node.flavor().resources().storageType() != NodeResources.StorageType.any)
object.setBool("remoteStorage", node.flavor().resources().storageType() == NodeResources.StorageType.remote);
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} |
😛 | 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;
} | List<NewDocumentType> indexedDocTypes = new ArrayList<>(); | 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;
}
} |
These responses are becoming bloated, and I don't think this will be used that much. I don't really have a strong opinion on it though. | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
if (resources.storageType() != NodeResources.StorageType.any)
object.setString("storageType", serializer.toString(resources.storageType()));
} | if (resources.storageType() != NodeResources.StorageType.any) | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
if ( ! resources.diskSpeed().isDefault())
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
if ( ! resources.storageType().isDefault())
object.setString("storageType", serializer.toString(resources.storageType()));
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
if (node.flavor().resources().storageType() != NodeResources.StorageType.any)
object.setBool("remoteStorage", node.flavor().resources().storageType() == NodeResources.StorageType.remote);
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
if (node.flavor().resources().storageType() != NodeResources.StorageType.any)
object.setBool("remoteStorage", node.flavor().resources().storageType() == NodeResources.StorageType.remote);
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} |
Don't show `diskSpeed` when it is `any` then? | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
if (resources.storageType() != NodeResources.StorageType.any)
object.setString("storageType", serializer.toString(resources.storageType()));
} | if (resources.storageType() != NodeResources.StorageType.any) | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
if ( ! resources.diskSpeed().isDefault())
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
if ( ! resources.storageType().isDefault())
object.setString("storageType", serializer.toString(resources.storageType()));
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
if (node.flavor().resources().storageType() != NodeResources.StorageType.any)
object.setBool("remoteStorage", node.flavor().resources().storageType() == NodeResources.StorageType.remote);
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
if (node.flavor().resources().storageType() != NodeResources.StorageType.any)
object.setBool("remoteStorage", node.flavor().resources().storageType() == NodeResources.StorageType.remote);
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} |
Yes, but then I need to check if that works with clients ... | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
if (resources.storageType() != NodeResources.StorageType.any)
object.setString("storageType", serializer.toString(resources.storageType()));
} | if (resources.storageType() != NodeResources.StorageType.any) | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
if ( ! resources.diskSpeed().isDefault())
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
if ( ! resources.storageType().isDefault())
object.setString("storageType", serializer.toString(resources.storageType()));
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
if (node.flavor().resources().storageType() != NodeResources.StorageType.any)
object.setBool("remoteStorage", node.flavor().resources().storageType() == NodeResources.StorageType.remote);
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
if (node.flavor().resources().storageType() != NodeResources.StorageType.any)
object.setBool("remoteStorage", node.flavor().resources().storageType() == NodeResources.StorageType.remote);
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} |
None of our clients use anything under `requestedResources` (no bindings either) | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
if (resources.storageType() != NodeResources.StorageType.any)
object.setString("storageType", serializer.toString(resources.storageType()));
} | if (resources.storageType() != NodeResources.StorageType.any) | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
if ( ! resources.diskSpeed().isDefault())
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
if ( ! resources.storageType().isDefault())
object.setString("storageType", serializer.toString(resources.storageType()));
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
if (node.flavor().resources().storageType() != NodeResources.StorageType.any)
object.setBool("remoteStorage", node.flavor().resources().storageType() == NodeResources.StorageType.remote);
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
if (node.flavor().resources().storageType() != NodeResources.StorageType.any)
object.setBool("remoteStorage", node.flavor().resources().storageType() == NodeResources.StorageType.remote);
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} |
Good point! | 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;
}
} |
Ah, yes it's only used for that. The other problem is that the default for diskSpeed isn't "any" but "fast". Ok, ok. Let me do this properly then. | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
if (resources.storageType() != NodeResources.StorageType.any)
object.setString("storageType", serializer.toString(resources.storageType()));
} | if (resources.storageType() != NodeResources.StorageType.any) | private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
if ( ! resources.diskSpeed().isDefault())
object.setString("diskSpeed", serializer.toString(resources.diskSpeed()));
if ( ! resources.storageType().isDefault())
object.setString("storageType", serializer.toString(resources.storageType()));
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
if (node.flavor().resources().storageType() != NodeResources.StorageType.any)
object.setBool("remoteStorage", node.flavor().resources().storageType() == NodeResources.StorageType.remote);
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} | class NodesResponse extends HttpResponse {
/** The responses this can create */
public enum ResponseType { nodeList, stateList, nodesInStateList, singleNode }
/** The request url minus parameters, with a trailing slash added if missing */
private final String parentUrl;
/** The parent url of nodes */
private final String nodeParentUrl;
private final NodeFilter filter;
private final boolean recursive;
private final Function<HostName, Optional<HostStatus>> orchestrator;
private final NodeRepository nodeRepository;
private final Slime slime;
private final NodeSerializer serializer = new NodeSerializer();
public NodesResponse(ResponseType responseType, HttpRequest request,
Orchestrator orchestrator, NodeRepository nodeRepository) {
super(200);
this.parentUrl = toParentUrl(request);
this.nodeParentUrl = toNodeParentUrl(request);
filter = NodesApiHandler.toNodeFilter(request);
this.recursive = request.getBooleanProperty("recursive");
this.orchestrator = orchestrator.getNodeStatuses();
this.nodeRepository = nodeRepository;
slime = new Slime();
Cursor root = slime.setObject();
switch (responseType) {
case nodeList: nodesToSlime(root); break;
case stateList : statesToSlime(root); break;
case nodesInStateList: nodesToSlime(serializer.stateFrom(lastElement(parentUrl)), root); break;
case singleNode : nodeToSlime(lastElement(parentUrl), root); break;
default: throw new IllegalArgumentException();
}
}
private String toParentUrl(HttpRequest request) {
URI uri = request.getUri();
String parentUrl = uri.getScheme() + ":
if ( ! parentUrl.endsWith("/"))
parentUrl = parentUrl + "/";
return parentUrl;
}
private String toNodeParentUrl(HttpRequest request) {
URI uri = request.getUri();
return uri.getScheme() + ":
}
@Override
public void render(OutputStream stream) throws IOException {
new JsonFormat(true).encode(stream, slime);
}
@Override
public String getContentType() {
return "application/json";
}
private void statesToSlime(Cursor root) {
Cursor states = root.setObject("states");
for (Node.State state : Node.State.values())
toSlime(state, states.setObject(serializer.toString(state)));
}
private void toSlime(Node.State state, Cursor object) {
object.setString("url", parentUrl + serializer.toString(state));
if (recursive)
nodesToSlime(state, object);
}
/** Outputs the nodes in the given state to a node array */
private void nodesToSlime(Node.State state, Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
for (NodeType type : NodeType.values())
toSlime(nodeRepository.getNodes(type, state), nodeArray);
}
/** Outputs all the nodes to a node array */
private void nodesToSlime(Cursor parentObject) {
Cursor nodeArray = parentObject.setArray("nodes");
toSlime(nodeRepository.getNodes(), nodeArray);
}
private void toSlime(List<Node> nodes, Cursor array) {
for (Node node : nodes) {
if ( ! filter.matches(node)) continue;
toSlime(node, recursive, array.addObject());
}
}
private void nodeToSlime(String hostname, Cursor object) {
Node node = nodeRepository.getNode(hostname).orElseThrow(() ->
new NotFoundException("No node with hostname '" + hostname + "'"));
toSlime(node, true, object);
}
private void toSlime(Node node, boolean allFields, Cursor object) {
object.setString("url", nodeParentUrl + node.hostname());
if ( ! allFields) return;
object.setString("id", node.hostname());
object.setString("state", serializer.toString(node.state()));
object.setString("type", node.type().name());
object.setString("hostname", node.hostname());
object.setString("type", serializer.toString(node.type()));
if (node.parentHostname().isPresent()) {
object.setString("parentHostname", node.parentHostname().get());
}
object.setString("openStackId", node.id());
object.setString("flavor", node.flavor().name());
object.setString("canonicalFlavor", node.flavor().name());
object.setDouble("minDiskAvailableGb", node.flavor().getMinDiskAvailableGb());
object.setDouble("minMainMemoryAvailableGb", node.flavor().getMinMainMemoryAvailableGb());
object.setDouble("minCpuCores", node.flavor().getMinCpuCores());
if (node.flavor().cost() > 0)
object.setLong("cost", node.flavor().cost());
object.setBool("fastDisk", node.flavor().hasFastDisk());
if (node.flavor().resources().storageType() != NodeResources.StorageType.any)
object.setBool("remoteStorage", node.flavor().resources().storageType() == NodeResources.StorageType.remote);
object.setDouble("bandwidthGbps", node.flavor().getBandwidthGbps());
object.setString("environment", node.flavor().getType().name());
node.allocation().ifPresent(allocation -> {
toSlime(allocation.owner(), object.setObject("owner"));
toSlime(allocation.membership(), object.setObject("membership"));
object.setLong("restartGeneration", allocation.restartGeneration().wanted());
object.setLong("currentRestartGeneration", allocation.restartGeneration().current());
object.setString("wantedDockerImage", dockerImageFor(node.type()).withTag(allocation.membership().cluster().vespaVersion()).asString());
object.setString("wantedVespaVersion", allocation.membership().cluster().vespaVersion().toFullString());
toSlime(allocation.requestedResources(), object.setObject("requestedResources"));
allocation.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray("networkPorts")));
orchestrator.apply(new HostName(node.hostname()))
.map(status -> status == HostStatus.ALLOWED_TO_BE_DOWN)
.ifPresent(allowedToBeDown -> object.setBool("allowedToBeDown", allowedToBeDown));
});
object.setLong("rebootGeneration", node.status().reboot().wanted());
object.setLong("currentRebootGeneration", node.status().reboot().current());
node.status().osVersion().ifPresent(version -> object.setString("currentOsVersion", version.toFullString()));
nodeRepository.osVersions().targetFor(node.type())
.filter(OsVersion::active)
.map(OsVersion::version)
.ifPresent(version -> object.setString("wantedOsVersion", version.toFullString()));
node.status().firmwareVerifiedAt().ifPresent(instant -> object.setLong("currentFirmwareCheck", instant.toEpochMilli()));
if (node.type().isDockerHost())
nodeRepository.firmwareChecks().requiredAfter().ifPresent(after -> object.setLong("wantedFirmwareCheck", after.toEpochMilli()));
node.status().vespaVersion().ifPresent(version -> object.setString("vespaVersion", version.toFullString()));
currentDockerImage(node).ifPresent(dockerImage -> object.setString("currentDockerImage", dockerImage.asString()));
object.setLong("failCount", node.status().failCount());
object.setBool("wantToRetire", node.status().wantToRetire());
object.setBool("wantToDeprovision", node.status().wantToDeprovision());
toSlime(node.history(), object.setArray("history"));
ipAddressesToSlime(node.ipAddresses(), object.setArray("ipAddresses"));
ipAddressesToSlime(node.ipAddressPool().asSet(), object.setArray("additionalIpAddresses"));
node.reports().toSlime(object, "reports");
node.modelName().ifPresent(modelName -> object.setString("modelName", modelName));
}
private void toSlime(ApplicationId id, Cursor object) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
}
private void toSlime(ClusterMembership membership, Cursor object) {
object.setString("clustertype", membership.cluster().type().name());
object.setString("clusterid", membership.cluster().id().value());
object.setString("group", String.valueOf(membership.cluster().group().get().index()));
object.setLong("index", membership.index());
object.setBool("retired", membership.retired());
}
private void toSlime(History history, Cursor array) {
for (History.Event event : history.events()) {
Cursor object = array.addObject();
object.setString("event", event.type().name());
object.setLong("at", event.at().toEpochMilli());
object.setString("agent", normalizedAgentUntilV6IsGone(event.agent()).name());
}
}
private Optional<DockerImage> currentDockerImage(Node node) {
return node.status().dockerImage()
.or(() -> Optional.of(node)
.filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER)
.flatMap(n -> n.status().vespaVersion()
.map(version -> dockerImageFor(n.type()).withTag(version))));
}
private DockerImage dockerImageFor(NodeType nodeType) {
return nodeRepository.dockerImage(nodeType.isDockerHost() ? nodeType.childNodeType() : nodeType);
}
/** maven-vespa-plugin @ v6 needs to deserialize nodes w/history. */
private Agent normalizedAgentUntilV6IsGone(Agent agent) {
return agent == Agent.NodeFailer ? Agent.system : agent;
}
private void ipAddressesToSlime(Set<String> ipAddresses, Cursor array) {
ipAddresses.forEach(array::addString);
}
private String lastElement(String path) {
if (path.endsWith("/"))
path = path.substring(0, path.length()-1);
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0) return path;
return path.substring(lastSlash+1);
}
} |
This should set to 'TLS'. It's effectively setting max TLS version, disabling TLSv1.3 even when it's listed in `enableProtocols`. See table in https://bugs.openjdk.java.net/browse/JDK-8202625. | private String createTlsQuorumConfig(ZookeeperServerConfig config) {
StringBuilder sb = new StringBuilder();
sb.append("ssl.quorum.hostnameVerification=false\n");
sb.append("ssl.quorum.clientAuth=NEED\n");
sb.append("ssl.quorum.ciphersuites=").append(String.join(",", new TreeSet<>(TlsContext.ALLOWED_CIPHER_SUITES))).append("\n");
sb.append("ssl.quorum.enabledProtocols=").append(String.join(",", new TreeSet<>(TlsContext.ALLOWED_PROTOCOLS))).append("\n");
sb.append("ssl.quorum.protocol=TLSv1.2\n");
String tlsSetting = config.tlsForQuorumCommunication().name();
switch (tlsSetting) {
case "OFF":
sb.append("sslQuorum=false\n");
sb.append("portUnification=false\n");
break;
case "PORT_UNIFICATION":
sb.append("sslQuorum=false\n");
sb.append("portUnification=true\n");
break;
case "TLS_WITH_PORT_UNIFICATION":
sb.append("sslQuorum=true\n");
sb.append("portUnification=true\n");
break;
case "TLS_ONLY":
sb.append("sslQuorum=true\n");
sb.append("portUnification=false\n");
break;
default: throw new IllegalArgumentException("Unknown value of config setting tlsForQuorumCommunication: " + tlsSetting);
}
return sb.toString();
} | sb.append("ssl.quorum.protocol=TLSv1.2\n"); | private String createTlsQuorumConfig(ZookeeperServerConfig config) {
StringBuilder sb = new StringBuilder();
sb.append("ssl.quorum.hostnameVerification=false\n");
sb.append("ssl.quorum.clientAuth=NEED\n");
sb.append("ssl.quorum.ciphersuites=").append(String.join(",", new TreeSet<>(TlsContext.ALLOWED_CIPHER_SUITES))).append("\n");
sb.append("ssl.quorum.enabledProtocols=").append(String.join(",", new TreeSet<>(TlsContext.ALLOWED_PROTOCOLS))).append("\n");
sb.append("ssl.quorum.protocol=TLS\n");
String tlsSetting = config.tlsForQuorumCommunication().name();
switch (tlsSetting) {
case "OFF":
sb.append("sslQuorum=false\n");
sb.append("portUnification=false\n");
break;
case "PORT_UNIFICATION":
sb.append("sslQuorum=false\n");
sb.append("portUnification=true\n");
break;
case "TLS_WITH_PORT_UNIFICATION":
sb.append("sslQuorum=true\n");
sb.append("portUnification=true\n");
break;
case "TLS_ONLY":
sb.append("sslQuorum=true\n");
sb.append("portUnification=false\n");
break;
default: throw new IllegalArgumentException("Unknown value of config setting tlsForQuorumCommunication: " + tlsSetting);
}
return sb.toString();
} | class VespaZooKeeperServerImpl extends AbstractComponent implements Runnable, VespaZooKeeperServer {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(VespaZooKeeperServerImpl.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;
VespaZooKeeperServerImpl(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 VespaZooKeeperServerImpl(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,dirs,dump,envi,mntr,ruok,srst,srvr,stat,wchs").append("\n");
sb.append("admin.enableServer=false").append("\n");
sb.append("serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory").append("\n");
ensureThisServerIsRepresented(config.myid(), config.server());
config.server().forEach(server -> addServerToCfg(sb, server));
sb.append(createTlsQuorumConfig(config));
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
public void run() {
System.setProperty(ZOOKEEPER_JMX_LOG4J_DISABLE, "true");
String[] args = new String[]{getDefaults().underVespaHome(zookeeperServerConfig.zooKeeperConfigFile())};
log.log(LogLevel.INFO, "Starting ZooKeeper server with config file " + args[0] +
". Trying to establish ZooKeeper quorum (members: " + zookeeperServerHostnames(zookeeperServerConfig) + ")");
org.apache.zookeeper.server.quorum.QuorumPeerMain.main(args);
}
@Override
public void deconstruct() {
shutdown();
super.deconstruct();
}
private static Set<String> zookeeperServerHostnames(ZookeeperServerConfig zookeeperServerConfig) {
return zookeeperServerConfig.server().stream().map(ZookeeperServerConfig.Server::hostname).collect(Collectors.toSet());
}
} | class VespaZooKeeperServerImpl extends AbstractComponent implements Runnable, VespaZooKeeperServer {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(VespaZooKeeperServerImpl.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;
VespaZooKeeperServerImpl(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 VespaZooKeeperServerImpl(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,dirs,dump,envi,mntr,ruok,srst,srvr,stat,wchs").append("\n");
sb.append("admin.enableServer=false").append("\n");
sb.append("serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory").append("\n");
ensureThisServerIsRepresented(config.myid(), config.server());
config.server().forEach(server -> addServerToCfg(sb, server));
sb.append(createTlsQuorumConfig(config));
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
public void run() {
System.setProperty(ZOOKEEPER_JMX_LOG4J_DISABLE, "true");
String[] args = new String[]{getDefaults().underVespaHome(zookeeperServerConfig.zooKeeperConfigFile())};
log.log(LogLevel.INFO, "Starting ZooKeeper server with config file " + args[0] +
". Trying to establish ZooKeeper quorum (members: " + zookeeperServerHostnames(zookeeperServerConfig) + ")");
org.apache.zookeeper.server.quorum.QuorumPeerMain.main(args);
}
@Override
public void deconstruct() {
shutdown();
super.deconstruct();
}
private static Set<String> zookeeperServerHostnames(ZookeeperServerConfig zookeeperServerConfig) {
return zookeeperServerConfig.server().stream().map(ZookeeperServerConfig.Server::hostname).collect(Collectors.toSet());
}
} |
ZooKeeper doc just says that 'TLSv1.2' is default value, but not anything about other possible values. But this makes sense, thanks, will fix | private String createTlsQuorumConfig(ZookeeperServerConfig config) {
StringBuilder sb = new StringBuilder();
sb.append("ssl.quorum.hostnameVerification=false\n");
sb.append("ssl.quorum.clientAuth=NEED\n");
sb.append("ssl.quorum.ciphersuites=").append(String.join(",", new TreeSet<>(TlsContext.ALLOWED_CIPHER_SUITES))).append("\n");
sb.append("ssl.quorum.enabledProtocols=").append(String.join(",", new TreeSet<>(TlsContext.ALLOWED_PROTOCOLS))).append("\n");
sb.append("ssl.quorum.protocol=TLSv1.2\n");
String tlsSetting = config.tlsForQuorumCommunication().name();
switch (tlsSetting) {
case "OFF":
sb.append("sslQuorum=false\n");
sb.append("portUnification=false\n");
break;
case "PORT_UNIFICATION":
sb.append("sslQuorum=false\n");
sb.append("portUnification=true\n");
break;
case "TLS_WITH_PORT_UNIFICATION":
sb.append("sslQuorum=true\n");
sb.append("portUnification=true\n");
break;
case "TLS_ONLY":
sb.append("sslQuorum=true\n");
sb.append("portUnification=false\n");
break;
default: throw new IllegalArgumentException("Unknown value of config setting tlsForQuorumCommunication: " + tlsSetting);
}
return sb.toString();
} | sb.append("ssl.quorum.protocol=TLSv1.2\n"); | private String createTlsQuorumConfig(ZookeeperServerConfig config) {
StringBuilder sb = new StringBuilder();
sb.append("ssl.quorum.hostnameVerification=false\n");
sb.append("ssl.quorum.clientAuth=NEED\n");
sb.append("ssl.quorum.ciphersuites=").append(String.join(",", new TreeSet<>(TlsContext.ALLOWED_CIPHER_SUITES))).append("\n");
sb.append("ssl.quorum.enabledProtocols=").append(String.join(",", new TreeSet<>(TlsContext.ALLOWED_PROTOCOLS))).append("\n");
sb.append("ssl.quorum.protocol=TLS\n");
String tlsSetting = config.tlsForQuorumCommunication().name();
switch (tlsSetting) {
case "OFF":
sb.append("sslQuorum=false\n");
sb.append("portUnification=false\n");
break;
case "PORT_UNIFICATION":
sb.append("sslQuorum=false\n");
sb.append("portUnification=true\n");
break;
case "TLS_WITH_PORT_UNIFICATION":
sb.append("sslQuorum=true\n");
sb.append("portUnification=true\n");
break;
case "TLS_ONLY":
sb.append("sslQuorum=true\n");
sb.append("portUnification=false\n");
break;
default: throw new IllegalArgumentException("Unknown value of config setting tlsForQuorumCommunication: " + tlsSetting);
}
return sb.toString();
} | class VespaZooKeeperServerImpl extends AbstractComponent implements Runnable, VespaZooKeeperServer {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(VespaZooKeeperServerImpl.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;
VespaZooKeeperServerImpl(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 VespaZooKeeperServerImpl(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,dirs,dump,envi,mntr,ruok,srst,srvr,stat,wchs").append("\n");
sb.append("admin.enableServer=false").append("\n");
sb.append("serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory").append("\n");
ensureThisServerIsRepresented(config.myid(), config.server());
config.server().forEach(server -> addServerToCfg(sb, server));
sb.append(createTlsQuorumConfig(config));
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
public void run() {
System.setProperty(ZOOKEEPER_JMX_LOG4J_DISABLE, "true");
String[] args = new String[]{getDefaults().underVespaHome(zookeeperServerConfig.zooKeeperConfigFile())};
log.log(LogLevel.INFO, "Starting ZooKeeper server with config file " + args[0] +
". Trying to establish ZooKeeper quorum (members: " + zookeeperServerHostnames(zookeeperServerConfig) + ")");
org.apache.zookeeper.server.quorum.QuorumPeerMain.main(args);
}
@Override
public void deconstruct() {
shutdown();
super.deconstruct();
}
private static Set<String> zookeeperServerHostnames(ZookeeperServerConfig zookeeperServerConfig) {
return zookeeperServerConfig.server().stream().map(ZookeeperServerConfig.Server::hostname).collect(Collectors.toSet());
}
} | class VespaZooKeeperServerImpl extends AbstractComponent implements Runnable, VespaZooKeeperServer {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(VespaZooKeeperServerImpl.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;
VespaZooKeeperServerImpl(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 VespaZooKeeperServerImpl(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,dirs,dump,envi,mntr,ruok,srst,srvr,stat,wchs").append("\n");
sb.append("admin.enableServer=false").append("\n");
sb.append("serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory").append("\n");
ensureThisServerIsRepresented(config.myid(), config.server());
config.server().forEach(server -> addServerToCfg(sb, server));
sb.append(createTlsQuorumConfig(config));
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
public void run() {
System.setProperty(ZOOKEEPER_JMX_LOG4J_DISABLE, "true");
String[] args = new String[]{getDefaults().underVespaHome(zookeeperServerConfig.zooKeeperConfigFile())};
log.log(LogLevel.INFO, "Starting ZooKeeper server with config file " + args[0] +
". Trying to establish ZooKeeper quorum (members: " + zookeeperServerHostnames(zookeeperServerConfig) + ")");
org.apache.zookeeper.server.quorum.QuorumPeerMain.main(args);
}
@Override
public void deconstruct() {
shutdown();
super.deconstruct();
}
private static Set<String> zookeeperServerHostnames(ZookeeperServerConfig zookeeperServerConfig) {
return zookeeperServerConfig.server().stream().map(ZookeeperServerConfig.Server::hostname).collect(Collectors.toSet());
}
} |
Shouldn't this be millis? | private static void setRequestConfigOverride(Params paramsOrNull, HttpRequestBase request) {
if (paramsOrNull == null) return;
RequestConfig.Builder builder = RequestConfig.copy(request.getConfig());
paramsOrNull.getConnectionTimeout().ifPresent(connectionTimeout -> {
builder.setConnectTimeout((int) connectionTimeout.getSeconds());
builder.setSocketTimeout((int) connectionTimeout.getSeconds());
});
request.setConfig(builder.build());
} | builder.setConnectTimeout((int) connectionTimeout.getSeconds()); | private static void setRequestConfigOverride(Params paramsOrNull, HttpRequestBase request) {
if (paramsOrNull == null) return;
RequestConfig.Builder builder = RequestConfig.copy(request.getConfig());
paramsOrNull.getConnectionTimeout().ifPresent(connectionTimeout -> {
builder.setConnectTimeout((int) connectionTimeout.toMillis());
builder.setSocketTimeout((int) connectionTimeout.toMillis());
});
request.setConfig(builder.build());
} | class ConfigServerApiImpl implements ConfigServerApi {
private static final Logger logger = Logger.getLogger(ConfigServerApiImpl.class.getName());
private final ObjectMapper mapper = new ObjectMapper();
private final List<URI> configServers;
private final CloseableHttpClient client;
public static ConfigServerApiImpl create(ConfigServerInfo info,
ServiceIdentityProvider provider,
HostnameVerifier hostnameVerifier) {
return new ConfigServerApiImpl(
info.getConfigServerUris(),
hostnameVerifier,
provider);
}
public static ConfigServerApiImpl createFor(ConfigServerInfo info,
ServiceIdentityProvider provider,
HostnameVerifier hostnameVerifier,
HostName configServerHostname) {
return new ConfigServerApiImpl(
Collections.singleton(info.getConfigServerUri(configServerHostname.value())),
hostnameVerifier,
provider);
}
private ConfigServerApiImpl(Collection<URI> configServers,
HostnameVerifier verifier,
ServiceIdentityProvider identityProvider) {
this(configServers, createClient(new SSLConnectionSocketFactory(new ServiceIdentitySslSocketFactory(identityProvider), verifier)));
}
private ConfigServerApiImpl(Collection<URI> configServers, CloseableHttpClient client) {
this.configServers = randomizeConfigServerUris(configServers);
this.client = client;
}
public static ConfigServerApiImpl createForTesting(List<URI> configServerHosts) {
return new ConfigServerApiImpl(configServerHosts, createClient(SSLConnectionSocketFactory.getSocketFactory()));
}
static ConfigServerApiImpl createForTestingWithClient(List<URI> configServerHosts,
CloseableHttpClient client) {
return new ConfigServerApiImpl(configServerHosts, client);
}
interface CreateRequest {
HttpUriRequest createRequest(URI configServerUri) throws JsonProcessingException, UnsupportedEncodingException;
}
private <T> T tryAllConfigServers(CreateRequest requestFactory, Class<T> wantedReturnType) {
Exception lastException = null;
for (URI configServer : configServers) {
try (CloseableHttpResponse response = client.execute(requestFactory.createRequest(configServer))) {
HttpException.handleStatusCode(
response.getStatusLine().getStatusCode(), "Config server " + configServer);
try {
return mapper.readValue(response.getEntity().getContent(), wantedReturnType);
} catch (IOException e) {
throw new UncheckedIOException("Failed parse response from config server", e);
}
} catch (HttpException e) {
if (!e.isRetryable()) throw e;
lastException = e;
} catch (Exception e) {
lastException = e;
if (configServers.size() == 1) break;
if (ConnectionException.isKnownConnectionException(e)) {
logger.info("Failed to connect to " + configServer + ", will try next: " + e.getMessage());
} else {
logger.warning("Failed to communicate with " + configServer + ", will try next: " + e.getMessage());
}
}
}
String prefix = configServers.size() == 1 ?
"Request against " + configServers.get(0) + " failed: " :
"All requests against the config servers (" + configServers + ") failed, last as follows: ";
throw ConnectionException.handleException(prefix, lastException);
}
@Override
public <T> T put(String path, Optional<Object> bodyJsonPojo, Class<T> wantedReturnType) {
return put(null, path, bodyJsonPojo, wantedReturnType);
}
@Override
public <T> T put(Params paramsOrNull, String path, Optional<Object> bodyJsonPojo, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer -> {
HttpPut put = new HttpPut(configServer.resolve(path));
setRequestConfigOverride(paramsOrNull, put);
setContentTypeToApplicationJson(put);
if (bodyJsonPojo.isPresent()) {
put.setEntity(new StringEntity(mapper.writeValueAsString(bodyJsonPojo.get())));
}
return put;
}, wantedReturnType);
}
@Override
public <T> T patch(String path, Object bodyJsonPojo, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer -> {
HttpPatch patch = new HttpPatch(configServer.resolve(path));
setContentTypeToApplicationJson(patch);
patch.setEntity(new StringEntity(mapper.writeValueAsString(bodyJsonPojo)));
return patch;
}, wantedReturnType);
}
@Override
public <T> T delete(String path, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer ->
new HttpDelete(configServer.resolve(path)), wantedReturnType);
}
@Override
public <T> T get(String path, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer ->
new HttpGet(configServer.resolve(path)), wantedReturnType);
}
@Override
public <T> T post(String path, Object bodyJsonPojo, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer -> {
HttpPost post = new HttpPost(configServer.resolve(path));
setContentTypeToApplicationJson(post);
post.setEntity(new StringEntity(mapper.writeValueAsString(bodyJsonPojo)));
return post;
}, wantedReturnType);
}
@Override
public void close() {
try {
client.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void setContentTypeToApplicationJson(HttpRequestBase request) {
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
}
private static CloseableHttpClient createClient(SSLConnectionSocketFactory socketFactory) {
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", socketFactory)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(200);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(1_000)
.setConnectTimeout(10_000)
.setSocketTimeout(10_000)
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(defaultRequestConfig)
.disableAutomaticRetries()
.setUserAgent("node-admin")
.setConnectionManager(cm)
.build();
}
private static List<URI> randomizeConfigServerUris(Collection<URI> configServerUris) {
List<URI> shuffledConfigServerHosts = new ArrayList<>(configServerUris);
Collections.shuffle(shuffledConfigServerHosts);
return shuffledConfigServerHosts;
}
} | class ConfigServerApiImpl implements ConfigServerApi {
private static final Logger logger = Logger.getLogger(ConfigServerApiImpl.class.getName());
private final ObjectMapper mapper = new ObjectMapper();
private final List<URI> configServers;
private final CloseableHttpClient client;
public static ConfigServerApiImpl create(ConfigServerInfo info,
ServiceIdentityProvider provider,
HostnameVerifier hostnameVerifier) {
return new ConfigServerApiImpl(
info.getConfigServerUris(),
hostnameVerifier,
provider);
}
public static ConfigServerApiImpl createFor(ConfigServerInfo info,
ServiceIdentityProvider provider,
HostnameVerifier hostnameVerifier,
HostName configServerHostname) {
return new ConfigServerApiImpl(
Collections.singleton(info.getConfigServerUri(configServerHostname.value())),
hostnameVerifier,
provider);
}
private ConfigServerApiImpl(Collection<URI> configServers,
HostnameVerifier verifier,
ServiceIdentityProvider identityProvider) {
this(configServers, createClient(new SSLConnectionSocketFactory(new ServiceIdentitySslSocketFactory(identityProvider), verifier)));
}
private ConfigServerApiImpl(Collection<URI> configServers, CloseableHttpClient client) {
this.configServers = randomizeConfigServerUris(configServers);
this.client = client;
}
public static ConfigServerApiImpl createForTesting(List<URI> configServerHosts) {
return new ConfigServerApiImpl(configServerHosts, createClient(SSLConnectionSocketFactory.getSocketFactory()));
}
static ConfigServerApiImpl createForTestingWithClient(List<URI> configServerHosts,
CloseableHttpClient client) {
return new ConfigServerApiImpl(configServerHosts, client);
}
interface CreateRequest {
HttpUriRequest createRequest(URI configServerUri) throws JsonProcessingException, UnsupportedEncodingException;
}
private <T> T tryAllConfigServers(CreateRequest requestFactory, Class<T> wantedReturnType) {
Exception lastException = null;
for (URI configServer : configServers) {
try (CloseableHttpResponse response = client.execute(requestFactory.createRequest(configServer))) {
HttpException.handleStatusCode(
response.getStatusLine().getStatusCode(), "Config server " + configServer);
try {
return mapper.readValue(response.getEntity().getContent(), wantedReturnType);
} catch (IOException e) {
throw new UncheckedIOException("Failed parse response from config server", e);
}
} catch (HttpException e) {
if (!e.isRetryable()) throw e;
lastException = e;
} catch (Exception e) {
lastException = e;
if (configServers.size() == 1) break;
if (ConnectionException.isKnownConnectionException(e)) {
logger.info("Failed to connect to " + configServer + ", will try next: " + e.getMessage());
} else {
logger.warning("Failed to communicate with " + configServer + ", will try next: " + e.getMessage());
}
}
}
String prefix = configServers.size() == 1 ?
"Request against " + configServers.get(0) + " failed: " :
"All requests against the config servers (" + configServers + ") failed, last as follows: ";
throw ConnectionException.handleException(prefix, lastException);
}
@Override
public <T> T put(String path, Optional<Object> bodyJsonPojo, Class<T> wantedReturnType) {
return put(path, bodyJsonPojo, wantedReturnType, null);
}
@Override
public <T> T put(String path, Optional<Object> bodyJsonPojo, Class<T> wantedReturnType, Params paramsOrNull) {
return tryAllConfigServers(configServer -> {
HttpPut put = new HttpPut(configServer.resolve(path));
setRequestConfigOverride(paramsOrNull, put);
setContentTypeToApplicationJson(put);
if (bodyJsonPojo.isPresent()) {
put.setEntity(new StringEntity(mapper.writeValueAsString(bodyJsonPojo.get())));
}
return put;
}, wantedReturnType);
}
@Override
public <T> T patch(String path, Object bodyJsonPojo, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer -> {
HttpPatch patch = new HttpPatch(configServer.resolve(path));
setContentTypeToApplicationJson(patch);
patch.setEntity(new StringEntity(mapper.writeValueAsString(bodyJsonPojo)));
return patch;
}, wantedReturnType);
}
@Override
public <T> T delete(String path, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer ->
new HttpDelete(configServer.resolve(path)), wantedReturnType);
}
@Override
public <T> T get(String path, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer ->
new HttpGet(configServer.resolve(path)), wantedReturnType);
}
@Override
public <T> T post(String path, Object bodyJsonPojo, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer -> {
HttpPost post = new HttpPost(configServer.resolve(path));
setContentTypeToApplicationJson(post);
post.setEntity(new StringEntity(mapper.writeValueAsString(bodyJsonPojo)));
return post;
}, wantedReturnType);
}
@Override
public void close() {
try {
client.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void setContentTypeToApplicationJson(HttpRequestBase request) {
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
}
private static CloseableHttpClient createClient(SSLConnectionSocketFactory socketFactory) {
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", socketFactory)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(200);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(1_000)
.setConnectTimeout(10_000)
.setSocketTimeout(10_000)
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(defaultRequestConfig)
.disableAutomaticRetries()
.setUserAgent("node-admin")
.setConnectionManager(cm)
.build();
}
private static List<URI> randomizeConfigServerUris(Collection<URI> configServerUris) {
List<URI> shuffledConfigServerHosts = new ArrayList<>(configServerUris);
Collections.shuffle(shuffledConfigServerHosts);
return shuffledConfigServerHosts;
}
} |
Great catch - I just verified this but forgot to update the code... | private static void setRequestConfigOverride(Params paramsOrNull, HttpRequestBase request) {
if (paramsOrNull == null) return;
RequestConfig.Builder builder = RequestConfig.copy(request.getConfig());
paramsOrNull.getConnectionTimeout().ifPresent(connectionTimeout -> {
builder.setConnectTimeout((int) connectionTimeout.getSeconds());
builder.setSocketTimeout((int) connectionTimeout.getSeconds());
});
request.setConfig(builder.build());
} | builder.setConnectTimeout((int) connectionTimeout.getSeconds()); | private static void setRequestConfigOverride(Params paramsOrNull, HttpRequestBase request) {
if (paramsOrNull == null) return;
RequestConfig.Builder builder = RequestConfig.copy(request.getConfig());
paramsOrNull.getConnectionTimeout().ifPresent(connectionTimeout -> {
builder.setConnectTimeout((int) connectionTimeout.toMillis());
builder.setSocketTimeout((int) connectionTimeout.toMillis());
});
request.setConfig(builder.build());
} | class ConfigServerApiImpl implements ConfigServerApi {
private static final Logger logger = Logger.getLogger(ConfigServerApiImpl.class.getName());
private final ObjectMapper mapper = new ObjectMapper();
private final List<URI> configServers;
private final CloseableHttpClient client;
public static ConfigServerApiImpl create(ConfigServerInfo info,
ServiceIdentityProvider provider,
HostnameVerifier hostnameVerifier) {
return new ConfigServerApiImpl(
info.getConfigServerUris(),
hostnameVerifier,
provider);
}
public static ConfigServerApiImpl createFor(ConfigServerInfo info,
ServiceIdentityProvider provider,
HostnameVerifier hostnameVerifier,
HostName configServerHostname) {
return new ConfigServerApiImpl(
Collections.singleton(info.getConfigServerUri(configServerHostname.value())),
hostnameVerifier,
provider);
}
private ConfigServerApiImpl(Collection<URI> configServers,
HostnameVerifier verifier,
ServiceIdentityProvider identityProvider) {
this(configServers, createClient(new SSLConnectionSocketFactory(new ServiceIdentitySslSocketFactory(identityProvider), verifier)));
}
private ConfigServerApiImpl(Collection<URI> configServers, CloseableHttpClient client) {
this.configServers = randomizeConfigServerUris(configServers);
this.client = client;
}
public static ConfigServerApiImpl createForTesting(List<URI> configServerHosts) {
return new ConfigServerApiImpl(configServerHosts, createClient(SSLConnectionSocketFactory.getSocketFactory()));
}
static ConfigServerApiImpl createForTestingWithClient(List<URI> configServerHosts,
CloseableHttpClient client) {
return new ConfigServerApiImpl(configServerHosts, client);
}
interface CreateRequest {
HttpUriRequest createRequest(URI configServerUri) throws JsonProcessingException, UnsupportedEncodingException;
}
private <T> T tryAllConfigServers(CreateRequest requestFactory, Class<T> wantedReturnType) {
Exception lastException = null;
for (URI configServer : configServers) {
try (CloseableHttpResponse response = client.execute(requestFactory.createRequest(configServer))) {
HttpException.handleStatusCode(
response.getStatusLine().getStatusCode(), "Config server " + configServer);
try {
return mapper.readValue(response.getEntity().getContent(), wantedReturnType);
} catch (IOException e) {
throw new UncheckedIOException("Failed parse response from config server", e);
}
} catch (HttpException e) {
if (!e.isRetryable()) throw e;
lastException = e;
} catch (Exception e) {
lastException = e;
if (configServers.size() == 1) break;
if (ConnectionException.isKnownConnectionException(e)) {
logger.info("Failed to connect to " + configServer + ", will try next: " + e.getMessage());
} else {
logger.warning("Failed to communicate with " + configServer + ", will try next: " + e.getMessage());
}
}
}
String prefix = configServers.size() == 1 ?
"Request against " + configServers.get(0) + " failed: " :
"All requests against the config servers (" + configServers + ") failed, last as follows: ";
throw ConnectionException.handleException(prefix, lastException);
}
@Override
public <T> T put(String path, Optional<Object> bodyJsonPojo, Class<T> wantedReturnType) {
return put(null, path, bodyJsonPojo, wantedReturnType);
}
@Override
public <T> T put(Params paramsOrNull, String path, Optional<Object> bodyJsonPojo, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer -> {
HttpPut put = new HttpPut(configServer.resolve(path));
setRequestConfigOverride(paramsOrNull, put);
setContentTypeToApplicationJson(put);
if (bodyJsonPojo.isPresent()) {
put.setEntity(new StringEntity(mapper.writeValueAsString(bodyJsonPojo.get())));
}
return put;
}, wantedReturnType);
}
@Override
public <T> T patch(String path, Object bodyJsonPojo, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer -> {
HttpPatch patch = new HttpPatch(configServer.resolve(path));
setContentTypeToApplicationJson(patch);
patch.setEntity(new StringEntity(mapper.writeValueAsString(bodyJsonPojo)));
return patch;
}, wantedReturnType);
}
@Override
public <T> T delete(String path, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer ->
new HttpDelete(configServer.resolve(path)), wantedReturnType);
}
@Override
public <T> T get(String path, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer ->
new HttpGet(configServer.resolve(path)), wantedReturnType);
}
@Override
public <T> T post(String path, Object bodyJsonPojo, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer -> {
HttpPost post = new HttpPost(configServer.resolve(path));
setContentTypeToApplicationJson(post);
post.setEntity(new StringEntity(mapper.writeValueAsString(bodyJsonPojo)));
return post;
}, wantedReturnType);
}
@Override
public void close() {
try {
client.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void setContentTypeToApplicationJson(HttpRequestBase request) {
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
}
private static CloseableHttpClient createClient(SSLConnectionSocketFactory socketFactory) {
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", socketFactory)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(200);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(1_000)
.setConnectTimeout(10_000)
.setSocketTimeout(10_000)
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(defaultRequestConfig)
.disableAutomaticRetries()
.setUserAgent("node-admin")
.setConnectionManager(cm)
.build();
}
private static List<URI> randomizeConfigServerUris(Collection<URI> configServerUris) {
List<URI> shuffledConfigServerHosts = new ArrayList<>(configServerUris);
Collections.shuffle(shuffledConfigServerHosts);
return shuffledConfigServerHosts;
}
} | class ConfigServerApiImpl implements ConfigServerApi {
private static final Logger logger = Logger.getLogger(ConfigServerApiImpl.class.getName());
private final ObjectMapper mapper = new ObjectMapper();
private final List<URI> configServers;
private final CloseableHttpClient client;
public static ConfigServerApiImpl create(ConfigServerInfo info,
ServiceIdentityProvider provider,
HostnameVerifier hostnameVerifier) {
return new ConfigServerApiImpl(
info.getConfigServerUris(),
hostnameVerifier,
provider);
}
public static ConfigServerApiImpl createFor(ConfigServerInfo info,
ServiceIdentityProvider provider,
HostnameVerifier hostnameVerifier,
HostName configServerHostname) {
return new ConfigServerApiImpl(
Collections.singleton(info.getConfigServerUri(configServerHostname.value())),
hostnameVerifier,
provider);
}
private ConfigServerApiImpl(Collection<URI> configServers,
HostnameVerifier verifier,
ServiceIdentityProvider identityProvider) {
this(configServers, createClient(new SSLConnectionSocketFactory(new ServiceIdentitySslSocketFactory(identityProvider), verifier)));
}
private ConfigServerApiImpl(Collection<URI> configServers, CloseableHttpClient client) {
this.configServers = randomizeConfigServerUris(configServers);
this.client = client;
}
public static ConfigServerApiImpl createForTesting(List<URI> configServerHosts) {
return new ConfigServerApiImpl(configServerHosts, createClient(SSLConnectionSocketFactory.getSocketFactory()));
}
static ConfigServerApiImpl createForTestingWithClient(List<URI> configServerHosts,
CloseableHttpClient client) {
return new ConfigServerApiImpl(configServerHosts, client);
}
interface CreateRequest {
HttpUriRequest createRequest(URI configServerUri) throws JsonProcessingException, UnsupportedEncodingException;
}
private <T> T tryAllConfigServers(CreateRequest requestFactory, Class<T> wantedReturnType) {
Exception lastException = null;
for (URI configServer : configServers) {
try (CloseableHttpResponse response = client.execute(requestFactory.createRequest(configServer))) {
HttpException.handleStatusCode(
response.getStatusLine().getStatusCode(), "Config server " + configServer);
try {
return mapper.readValue(response.getEntity().getContent(), wantedReturnType);
} catch (IOException e) {
throw new UncheckedIOException("Failed parse response from config server", e);
}
} catch (HttpException e) {
if (!e.isRetryable()) throw e;
lastException = e;
} catch (Exception e) {
lastException = e;
if (configServers.size() == 1) break;
if (ConnectionException.isKnownConnectionException(e)) {
logger.info("Failed to connect to " + configServer + ", will try next: " + e.getMessage());
} else {
logger.warning("Failed to communicate with " + configServer + ", will try next: " + e.getMessage());
}
}
}
String prefix = configServers.size() == 1 ?
"Request against " + configServers.get(0) + " failed: " :
"All requests against the config servers (" + configServers + ") failed, last as follows: ";
throw ConnectionException.handleException(prefix, lastException);
}
@Override
public <T> T put(String path, Optional<Object> bodyJsonPojo, Class<T> wantedReturnType) {
return put(path, bodyJsonPojo, wantedReturnType, null);
}
@Override
public <T> T put(String path, Optional<Object> bodyJsonPojo, Class<T> wantedReturnType, Params paramsOrNull) {
return tryAllConfigServers(configServer -> {
HttpPut put = new HttpPut(configServer.resolve(path));
setRequestConfigOverride(paramsOrNull, put);
setContentTypeToApplicationJson(put);
if (bodyJsonPojo.isPresent()) {
put.setEntity(new StringEntity(mapper.writeValueAsString(bodyJsonPojo.get())));
}
return put;
}, wantedReturnType);
}
@Override
public <T> T patch(String path, Object bodyJsonPojo, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer -> {
HttpPatch patch = new HttpPatch(configServer.resolve(path));
setContentTypeToApplicationJson(patch);
patch.setEntity(new StringEntity(mapper.writeValueAsString(bodyJsonPojo)));
return patch;
}, wantedReturnType);
}
@Override
public <T> T delete(String path, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer ->
new HttpDelete(configServer.resolve(path)), wantedReturnType);
}
@Override
public <T> T get(String path, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer ->
new HttpGet(configServer.resolve(path)), wantedReturnType);
}
@Override
public <T> T post(String path, Object bodyJsonPojo, Class<T> wantedReturnType) {
return tryAllConfigServers(configServer -> {
HttpPost post = new HttpPost(configServer.resolve(path));
setContentTypeToApplicationJson(post);
post.setEntity(new StringEntity(mapper.writeValueAsString(bodyJsonPojo)));
return post;
}, wantedReturnType);
}
@Override
public void close() {
try {
client.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void setContentTypeToApplicationJson(HttpRequestBase request) {
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
}
private static CloseableHttpClient createClient(SSLConnectionSocketFactory socketFactory) {
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", socketFactory)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(200);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(1_000)
.setConnectTimeout(10_000)
.setSocketTimeout(10_000)
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(defaultRequestConfig)
.disableAutomaticRetries()
.setUserAgent("node-admin")
.setConnectionManager(cm)
.build();
}
private static List<URI> randomizeConfigServerUris(Collection<URI> configServerUris) {
List<URI> shuffledConfigServerHosts = new ArrayList<>(configServerUris);
Collections.shuffle(shuffledConfigServerHosts);
return shuffledConfigServerHosts;
}
} |
This will log "Stopping services" on every tick. | void doConverge(NodeAgentContext context) {
NodeSpec node = context.node();
Optional<Container> container = getContainer(context);
if (!node.equals(lastNode)) {
logChangesToNodeSpec(context, lastNode, node);
if (currentRebootGeneration < node.currentRebootGeneration())
currentRebootGeneration = node.currentRebootGeneration();
if (currentRestartGeneration.isPresent() != node.currentRestartGeneration().isPresent() ||
currentRestartGeneration.map(current -> current < node.currentRestartGeneration().get()).orElse(false))
currentRestartGeneration = node.currentRestartGeneration();
lastNode = node;
}
switch (node.state()) {
case ready:
case reserved:
case failed:
case inactive:
removeContainerIfNeededUpdateContainerState(context, container);
updateNodeRepoWithCurrentAttributes(context);
break;
case parked:
updateNodeRepoWithCurrentAttributes(context);
stopServices(context);
break;
case active:
storageMaintainer.handleCoreDumpsForContainer(context, container);
storageMaintainer.getDiskUsageFor(context)
.map(diskUsage -> (double) diskUsage / BYTES_IN_GB / node.diskGb())
.filter(diskUtil -> diskUtil >= 0.8)
.ifPresent(diskUtil -> storageMaintainer.removeOldFilesFromNode(context));
if (downloadImageIfNeeded(node, container)) {
context.log(logger, "Waiting for image to download " + context.node().wantedDockerImage().get().asString());
return;
}
container = removeContainerIfNeededUpdateContainerState(context, container);
credentialsMaintainer.ifPresent(maintainer -> maintainer.converge(context));
if (! container.isPresent()) {
containerState = STARTING;
startContainer(context);
containerState = UNKNOWN;
} else {
updateContainerIfNeeded(context, container.get());
}
aclMaintainer.ifPresent(maintainer -> maintainer.converge(context));
startServicesIfNeeded(context);
resumeNodeIfNeeded(context);
healthChecker.ifPresent(checker -> checker.verifyHealth(context));
updateNodeRepoWithCurrentAttributes(context);
context.log(logger, "Call resume against Orchestrator");
orchestrator.resume(context.hostname().value());
break;
case provisioned:
nodeRepository.setNodeState(context.hostname().value(), NodeState.dirty);
break;
case dirty:
removeContainerIfNeededUpdateContainerState(context, container);
context.log(logger, "State is " + node.state() + ", will delete application storage and mark node as ready");
credentialsMaintainer.ifPresent(maintainer -> maintainer.clearCredentials(context));
storageMaintainer.archiveNodeStorage(context);
updateNodeRepoWithCurrentAttributes(context);
nodeRepository.setNodeState(context.hostname().value(), NodeState.ready);
break;
default:
throw new ConvergenceException("UNKNOWN STATE " + node.state().name());
}
} | stopServices(context); | void doConverge(NodeAgentContext context) {
NodeSpec node = context.node();
Optional<Container> container = getContainer(context);
if (!node.equals(lastNode)) {
logChangesToNodeSpec(context, lastNode, node);
if (currentRebootGeneration < node.currentRebootGeneration())
currentRebootGeneration = node.currentRebootGeneration();
if (currentRestartGeneration.isPresent() != node.currentRestartGeneration().isPresent() ||
currentRestartGeneration.map(current -> current < node.currentRestartGeneration().get()).orElse(false))
currentRestartGeneration = node.currentRestartGeneration();
lastNode = node;
}
switch (node.state()) {
case ready:
case reserved:
case failed:
case inactive:
removeContainerIfNeededUpdateContainerState(context, container);
updateNodeRepoWithCurrentAttributes(context);
break;
case parked:
updateNodeRepoWithCurrentAttributes(context);
stopServicesIfNeeded(context);
break;
case active:
storageMaintainer.handleCoreDumpsForContainer(context, container);
storageMaintainer.getDiskUsageFor(context)
.map(diskUsage -> (double) diskUsage / BYTES_IN_GB / node.diskGb())
.filter(diskUtil -> diskUtil >= 0.8)
.ifPresent(diskUtil -> storageMaintainer.removeOldFilesFromNode(context));
if (downloadImageIfNeeded(node, container)) {
context.log(logger, "Waiting for image to download " + context.node().wantedDockerImage().get().asString());
return;
}
container = removeContainerIfNeededUpdateContainerState(context, container);
credentialsMaintainer.ifPresent(maintainer -> maintainer.converge(context));
if (! container.isPresent()) {
containerState = STARTING;
startContainer(context);
containerState = UNKNOWN;
} else {
updateContainerIfNeeded(context, container.get());
}
aclMaintainer.ifPresent(maintainer -> maintainer.converge(context));
startServicesIfNeeded(context);
resumeNodeIfNeeded(context);
healthChecker.ifPresent(checker -> checker.verifyHealth(context));
updateNodeRepoWithCurrentAttributes(context);
context.log(logger, "Call resume against Orchestrator");
orchestrator.resume(context.hostname().value());
break;
case provisioned:
nodeRepository.setNodeState(context.hostname().value(), NodeState.dirty);
break;
case dirty:
removeContainerIfNeededUpdateContainerState(context, container);
context.log(logger, "State is " + node.state() + ", will delete application storage and mark node as ready");
credentialsMaintainer.ifPresent(maintainer -> maintainer.clearCredentials(context));
storageMaintainer.archiveNodeStorage(context);
updateNodeRepoWithCurrentAttributes(context);
nodeRepository.setNodeState(context.hostname().value(), NodeState.ready);
break;
default:
throw new ConvergenceException("UNKNOWN STATE " + node.state().name());
}
} | class NodeAgentImpl implements NodeAgent {
private static final long BYTES_IN_GB = 1_000_000_000L;
private static final Logger logger = Logger.getLogger(NodeAgentImpl.class.getName());
private final AtomicBoolean terminated = new AtomicBoolean(false);
private boolean hasResumedNode = false;
private boolean hasStartedServices = true;
private final NodeAgentContextSupplier contextSupplier;
private final NodeRepository nodeRepository;
private final Orchestrator orchestrator;
private final DockerOperations dockerOperations;
private final StorageMaintainer storageMaintainer;
private final Optional<CredentialsMaintainer> credentialsMaintainer;
private final Optional<AclMaintainer> aclMaintainer;
private final Optional<HealthChecker> healthChecker;
private final DoubleFlag containerCpuCap;
private Thread loopThread;
private ContainerState containerState = UNKNOWN;
private NodeSpec lastNode;
private int numberOfUnhandledException = 0;
private long currentRebootGeneration = 0;
private Optional<Long> currentRestartGeneration = Optional.empty();
/**
* ABSENT means container is definitely absent - A container that was absent will not suddenly appear without
* NodeAgent explicitly starting it.
* STARTING state is set just before we attempt to start a container, if successful we move to the next state.
* Otherwise we can't be certain. A container that was running a minute ago may no longer be running without
* NodeAgent doing anything (container could have crashed). Therefore we always have to ask docker daemon
* to get updated state of the container.
*/
enum ContainerState {
ABSENT,
STARTING,
UNKNOWN
}
public NodeAgentImpl(
final NodeAgentContextSupplier contextSupplier,
final NodeRepository nodeRepository,
final Orchestrator orchestrator,
final DockerOperations dockerOperations,
final StorageMaintainer storageMaintainer,
final FlagSource flagSource,
final Optional<CredentialsMaintainer> credentialsMaintainer,
final Optional<AclMaintainer> aclMaintainer,
final Optional<HealthChecker> healthChecker) {
this.contextSupplier = contextSupplier;
this.nodeRepository = nodeRepository;
this.orchestrator = orchestrator;
this.dockerOperations = dockerOperations;
this.storageMaintainer = storageMaintainer;
this.credentialsMaintainer = credentialsMaintainer;
this.aclMaintainer = aclMaintainer;
this.healthChecker = healthChecker;
this.containerCpuCap = Flags.CONTAINER_CPU_CAP.bindTo(flagSource);
}
@Override
public void start(NodeAgentContext initialContext) {
if (loopThread != null)
throw new IllegalStateException("Can not re-start a node agent.");
loopThread = new Thread(() -> {
while (!terminated.get()) {
try {
NodeAgentContext context = contextSupplier.nextContext();
converge(context);
} catch (InterruptedException ignored) { }
}
});
loopThread.setName("tick-" + initialContext.hostname());
loopThread.start();
}
@Override
public void stopForRemoval(NodeAgentContext context) {
if (!terminated.compareAndSet(false, true))
throw new IllegalStateException("Can not re-stop a node agent.");
contextSupplier.interrupt();
do {
try {
loopThread.join();
} catch (InterruptedException ignored) { }
} while (loopThread.isAlive());
context.log(logger, "Stopped");
}
void startServicesIfNeeded(NodeAgentContext context) {
if (!hasStartedServices) {
context.log(logger, "Starting services");
dockerOperations.startServices(context);
hasStartedServices = true;
}
}
void resumeNodeIfNeeded(NodeAgentContext context) {
if (!hasResumedNode) {
context.log(logger, LogLevel.DEBUG, "Starting optional node program resume command");
dockerOperations.resumeNode(context);
hasResumedNode = true;
}
}
private void updateNodeRepoWithCurrentAttributes(NodeAgentContext context) {
final NodeAttributes currentNodeAttributes = new NodeAttributes();
final NodeAttributes newNodeAttributes = new NodeAttributes();
if (context.node().wantedRestartGeneration().isPresent() &&
!Objects.equals(context.node().currentRestartGeneration(), currentRestartGeneration)) {
currentNodeAttributes.withRestartGeneration(context.node().currentRestartGeneration());
newNodeAttributes.withRestartGeneration(currentRestartGeneration);
}
if (!Objects.equals(context.node().currentRebootGeneration(), currentRebootGeneration)) {
currentNodeAttributes.withRebootGeneration(context.node().currentRebootGeneration());
newNodeAttributes.withRebootGeneration(currentRebootGeneration);
}
Optional<DockerImage> actualDockerImage = context.node().wantedDockerImage().filter(n -> containerState == UNKNOWN);
if (!Objects.equals(context.node().currentDockerImage(), actualDockerImage)) {
DockerImage currentImage = context.node().currentDockerImage().orElse(DockerImage.EMPTY);
DockerImage newImage = actualDockerImage.orElse(DockerImage.EMPTY);
currentNodeAttributes.withDockerImage(currentImage);
currentNodeAttributes.withVespaVersion(currentImage.tagAsVersion());
newNodeAttributes.withDockerImage(newImage);
newNodeAttributes.withVespaVersion(newImage.tagAsVersion());
}
publishStateToNodeRepoIfChanged(context, currentNodeAttributes, newNodeAttributes);
}
private void publishStateToNodeRepoIfChanged(NodeAgentContext context, NodeAttributes currentAttributes, NodeAttributes newAttributes) {
if (!currentAttributes.equals(newAttributes)) {
context.log(logger, "Publishing new set of attributes to node repo: %s -> %s",
currentAttributes, newAttributes);
nodeRepository.updateNodeAttributes(context.hostname().value(), newAttributes);
}
}
private void startContainer(NodeAgentContext context) {
ContainerData containerData = createContainerData(context);
dockerOperations.createContainer(context, containerData, getContainerResources(context));
dockerOperations.startContainer(context);
hasStartedServices = true;
hasResumedNode = false;
context.log(logger, "Container successfully started, new containerState is " + containerState);
}
private Optional<Container> removeContainerIfNeededUpdateContainerState(
NodeAgentContext context, Optional<Container> existingContainer) {
if (existingContainer.isPresent()) {
Optional<String> reason = shouldRemoveContainer(context, existingContainer.get());
if (reason.isPresent()) {
removeContainer(context, existingContainer.get(), reason.get(), false);
return Optional.empty();
}
shouldRestartServices(context, existingContainer.get()).ifPresent(restartReason -> {
context.log(logger, "Will restart services: " + restartReason);
restartServices(context, existingContainer.get());
currentRestartGeneration = context.node().wantedRestartGeneration();
});
}
return existingContainer;
}
private Optional<String> shouldRestartServices( NodeAgentContext context, Container existingContainer) {
NodeSpec node = context.node();
if (node.wantedRestartGeneration().isEmpty()) return Optional.empty();
if (currentRestartGeneration.get() < node.wantedRestartGeneration().get()) {
return Optional.of("Restart requested - wanted restart generation has been bumped: "
+ currentRestartGeneration.get() + " -> " + node.wantedRestartGeneration().get());
}
ContainerResources wantedContainerResources = getContainerResources(context);
if (!wantedContainerResources.equalsMemory(existingContainer.resources)) {
return Optional.of("Container should be running with different memory allocation, wanted: " +
wantedContainerResources.toStringMemory() + ", actual: " + existingContainer.resources.toStringMemory());
}
return Optional.empty();
}
private void restartServices(NodeAgentContext context, Container existingContainer) {
if (existingContainer.state.isRunning() && context.node().state() == NodeState.active) {
context.log(logger, "Restarting services");
orchestratorSuspendNode(context);
dockerOperations.restartVespa(context);
}
}
private void stopServices(NodeAgentContext context) {
context.log(logger, "Stopping services");
if (containerState == ABSENT) return;
try {
hasStartedServices = hasResumedNode = false;
dockerOperations.stopServices(context);
} catch (ContainerNotFoundException e) {
containerState = ABSENT;
}
}
@Override
public void stopForHostSuspension(NodeAgentContext context) {
getContainer(context).ifPresent(container -> removeContainer(context, container, "suspending host", true));
}
public void suspend(NodeAgentContext context) {
context.log(logger, "Suspending services on node");
if (containerState == ABSENT) return;
try {
hasResumedNode = false;
dockerOperations.suspendNode(context);
} catch (ContainerNotFoundException e) {
containerState = ABSENT;
} catch (RuntimeException e) {
context.log(logger, LogLevel.WARNING, "Failed trying to suspend container", e);
}
}
private Optional<String> shouldRemoveContainer(NodeAgentContext context, Container existingContainer) {
final NodeState nodeState = context.node().state();
if (nodeState == NodeState.dirty || nodeState == NodeState.provisioned) {
return Optional.of("Node in state " + nodeState + ", container should no longer be running");
}
if (context.node().wantedDockerImage().isPresent() &&
!context.node().wantedDockerImage().get().equals(existingContainer.image)) {
return Optional.of("The node is supposed to run a new Docker image: "
+ existingContainer.image.asString() + " -> " + context.node().wantedDockerImage().get().asString());
}
if (!existingContainer.state.isRunning()) {
return Optional.of("Container no longer running");
}
if (currentRebootGeneration < context.node().wantedRebootGeneration()) {
return Optional.of(String.format("Container reboot wanted. Current: %d, Wanted: %d",
currentRebootGeneration, context.node().wantedRebootGeneration()));
}
if (containerState == STARTING) return Optional.of("Container failed to start");
return Optional.empty();
}
private void removeContainer(NodeAgentContext context, Container existingContainer, String reason, boolean alreadySuspended) {
context.log(logger, "Will remove container: " + reason);
if (existingContainer.state.isRunning()) {
if (!alreadySuspended) {
orchestratorSuspendNode(context);
}
try {
if (context.node().state() != NodeState.dirty) {
suspend(context);
}
stopServices(context);
} catch (Exception e) {
context.log(logger, LogLevel.WARNING, "Failed stopping services, ignoring", e);
}
}
storageMaintainer.handleCoreDumpsForContainer(context, Optional.of(existingContainer));
dockerOperations.removeContainer(context, existingContainer);
currentRebootGeneration = context.node().wantedRebootGeneration();
containerState = ABSENT;
context.log(logger, "Container successfully removed, new containerState is " + containerState);
}
private void updateContainerIfNeeded(NodeAgentContext context, Container existingContainer) {
ContainerResources wantedContainerResources = getContainerResources(context);
if (wantedContainerResources.equalsCpu(existingContainer.resources)) return;
context.log(logger, "Container should be running with different CPU allocation, wanted: %s, current: %s",
wantedContainerResources.toStringCpu(), existingContainer.resources.toStringCpu());
orchestratorSuspendNode(context);
dockerOperations.updateContainer(context, wantedContainerResources);
}
private ContainerResources getContainerResources(NodeAgentContext context) {
double cpuCap = noCpuCap(context.zone()) ?
0 :
context.node().owner()
.map(appId -> containerCpuCap.with(FetchVector.Dimension.APPLICATION_ID, appId.serializedForm()))
.orElse(containerCpuCap)
.with(FetchVector.Dimension.HOSTNAME, context.node().hostname())
.value() * context.node().vcpus();
return ContainerResources.from(cpuCap, context.node().vcpus(), context.node().memoryGb());
}
private boolean noCpuCap(ZoneApi zone) {
return zone.getEnvironment() == Environment.dev || zone.getSystemName().isCd();
}
private boolean downloadImageIfNeeded(NodeSpec node, Optional<Container> container) {
if (node.wantedDockerImage().equals(container.map(c -> c.image))) return false;
return node.wantedDockerImage().map(dockerOperations::pullImageAsyncIfNeeded).orElse(false);
}
public void converge(NodeAgentContext context) {
try {
doConverge(context);
} catch (ConvergenceException e) {
context.log(logger, e.getMessage());
} catch (ContainerNotFoundException e) {
containerState = ABSENT;
context.log(logger, LogLevel.WARNING, "Container unexpectedly gone, resetting containerState to " + containerState);
} catch (DockerException e) {
numberOfUnhandledException++;
context.log(logger, LogLevel.ERROR, "Caught a DockerException", e);
} catch (Throwable e) {
numberOfUnhandledException++;
context.log(logger, LogLevel.ERROR, "Unhandled exception, ignoring", e);
}
}
private static void logChangesToNodeSpec(NodeAgentContext context, NodeSpec lastNode, NodeSpec node) {
StringBuilder builder = new StringBuilder();
appendIfDifferent(builder, "state", lastNode, node, NodeSpec::state);
if (builder.length() > 0) {
context.log(logger, LogLevel.INFO, "Changes to node: " + builder.toString());
}
}
private static <T> String fieldDescription(T value) {
return value == null ? "[absent]" : value.toString();
}
private static <T> void appendIfDifferent(StringBuilder builder, String name, NodeSpec oldNode, NodeSpec newNode, Function<NodeSpec, T> getter) {
T oldValue = oldNode == null ? null : getter.apply(oldNode);
T newValue = getter.apply(newNode);
if (!Objects.equals(oldValue, newValue)) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(name).append(" ").append(fieldDescription(oldValue)).append(" -> ").append(fieldDescription(newValue));
}
}
private Optional<Container> getContainer(NodeAgentContext context) {
if (containerState == ABSENT) return Optional.empty();
Optional<Container> container = dockerOperations.getContainer(context);
if (! container.isPresent()) containerState = ABSENT;
return container;
}
@Override
public int getAndResetNumberOfUnhandledExceptions() {
int temp = numberOfUnhandledException;
numberOfUnhandledException = 0;
return temp;
}
private void orchestratorSuspendNode(NodeAgentContext context) {
if (context.node().state() != NodeState.active) return;
context.log(logger, "Ask Orchestrator for permission to suspend node");
try {
orchestrator.suspend(context.hostname().value());
} catch (OrchestratorException e) {
try {
aclMaintainer.ifPresent(maintainer -> maintainer.converge(context));
} catch (RuntimeException suppressed) {
logger.log(LogLevel.WARNING, "Suppressing ACL update failure: " + suppressed);
e.addSuppressed(suppressed);
}
throw e;
}
}
protected ContainerData createContainerData(NodeAgentContext context) {
return new ContainerData() {
@Override
public void addFile(Path pathInContainer, String data) {
throw new UnsupportedOperationException("addFile not implemented");
}
@Override
public void addDirectory(Path pathInContainer) {
throw new UnsupportedOperationException("addDirectory not implemented");
}
@Override
public void createSymlink(Path symlink, Path target) {
throw new UnsupportedOperationException("createSymlink not implemented");
}
};
}
protected Optional<CredentialsMaintainer> credentialsMaintainer() {
return credentialsMaintainer;
}
} | class NodeAgentImpl implements NodeAgent {
private static final long BYTES_IN_GB = 1_000_000_000L;
private static final Logger logger = Logger.getLogger(NodeAgentImpl.class.getName());
private final AtomicBoolean terminated = new AtomicBoolean(false);
private boolean hasResumedNode = false;
private boolean hasStartedServices = true;
private final NodeAgentContextSupplier contextSupplier;
private final NodeRepository nodeRepository;
private final Orchestrator orchestrator;
private final DockerOperations dockerOperations;
private final StorageMaintainer storageMaintainer;
private final Optional<CredentialsMaintainer> credentialsMaintainer;
private final Optional<AclMaintainer> aclMaintainer;
private final Optional<HealthChecker> healthChecker;
private final DoubleFlag containerCpuCap;
private Thread loopThread;
private ContainerState containerState = UNKNOWN;
private NodeSpec lastNode;
private int numberOfUnhandledException = 0;
private long currentRebootGeneration = 0;
private Optional<Long> currentRestartGeneration = Optional.empty();
/**
* ABSENT means container is definitely absent - A container that was absent will not suddenly appear without
* NodeAgent explicitly starting it.
* STARTING state is set just before we attempt to start a container, if successful we move to the next state.
* Otherwise we can't be certain. A container that was running a minute ago may no longer be running without
* NodeAgent doing anything (container could have crashed). Therefore we always have to ask docker daemon
* to get updated state of the container.
*/
enum ContainerState {
ABSENT,
STARTING,
UNKNOWN
}
public NodeAgentImpl(
final NodeAgentContextSupplier contextSupplier,
final NodeRepository nodeRepository,
final Orchestrator orchestrator,
final DockerOperations dockerOperations,
final StorageMaintainer storageMaintainer,
final FlagSource flagSource,
final Optional<CredentialsMaintainer> credentialsMaintainer,
final Optional<AclMaintainer> aclMaintainer,
final Optional<HealthChecker> healthChecker) {
this.contextSupplier = contextSupplier;
this.nodeRepository = nodeRepository;
this.orchestrator = orchestrator;
this.dockerOperations = dockerOperations;
this.storageMaintainer = storageMaintainer;
this.credentialsMaintainer = credentialsMaintainer;
this.aclMaintainer = aclMaintainer;
this.healthChecker = healthChecker;
this.containerCpuCap = Flags.CONTAINER_CPU_CAP.bindTo(flagSource);
}
@Override
public void start(NodeAgentContext initialContext) {
if (loopThread != null)
throw new IllegalStateException("Can not re-start a node agent.");
loopThread = new Thread(() -> {
while (!terminated.get()) {
try {
NodeAgentContext context = contextSupplier.nextContext();
converge(context);
} catch (InterruptedException ignored) { }
}
});
loopThread.setName("tick-" + initialContext.hostname());
loopThread.start();
}
@Override
public void stopForRemoval(NodeAgentContext context) {
if (!terminated.compareAndSet(false, true))
throw new IllegalStateException("Can not re-stop a node agent.");
contextSupplier.interrupt();
do {
try {
loopThread.join();
} catch (InterruptedException ignored) { }
} while (loopThread.isAlive());
context.log(logger, "Stopped");
}
void startServicesIfNeeded(NodeAgentContext context) {
if (!hasStartedServices) {
context.log(logger, "Starting services");
dockerOperations.startServices(context);
hasStartedServices = true;
}
}
void resumeNodeIfNeeded(NodeAgentContext context) {
if (!hasResumedNode) {
context.log(logger, LogLevel.DEBUG, "Starting optional node program resume command");
dockerOperations.resumeNode(context);
hasResumedNode = true;
}
}
private void updateNodeRepoWithCurrentAttributes(NodeAgentContext context) {
final NodeAttributes currentNodeAttributes = new NodeAttributes();
final NodeAttributes newNodeAttributes = new NodeAttributes();
if (context.node().wantedRestartGeneration().isPresent() &&
!Objects.equals(context.node().currentRestartGeneration(), currentRestartGeneration)) {
currentNodeAttributes.withRestartGeneration(context.node().currentRestartGeneration());
newNodeAttributes.withRestartGeneration(currentRestartGeneration);
}
if (!Objects.equals(context.node().currentRebootGeneration(), currentRebootGeneration)) {
currentNodeAttributes.withRebootGeneration(context.node().currentRebootGeneration());
newNodeAttributes.withRebootGeneration(currentRebootGeneration);
}
Optional<DockerImage> actualDockerImage = context.node().wantedDockerImage().filter(n -> containerState == UNKNOWN);
if (!Objects.equals(context.node().currentDockerImage(), actualDockerImage)) {
DockerImage currentImage = context.node().currentDockerImage().orElse(DockerImage.EMPTY);
DockerImage newImage = actualDockerImage.orElse(DockerImage.EMPTY);
currentNodeAttributes.withDockerImage(currentImage);
currentNodeAttributes.withVespaVersion(currentImage.tagAsVersion());
newNodeAttributes.withDockerImage(newImage);
newNodeAttributes.withVespaVersion(newImage.tagAsVersion());
}
publishStateToNodeRepoIfChanged(context, currentNodeAttributes, newNodeAttributes);
}
private void publishStateToNodeRepoIfChanged(NodeAgentContext context, NodeAttributes currentAttributes, NodeAttributes newAttributes) {
if (!currentAttributes.equals(newAttributes)) {
context.log(logger, "Publishing new set of attributes to node repo: %s -> %s",
currentAttributes, newAttributes);
nodeRepository.updateNodeAttributes(context.hostname().value(), newAttributes);
}
}
private void startContainer(NodeAgentContext context) {
ContainerData containerData = createContainerData(context);
dockerOperations.createContainer(context, containerData, getContainerResources(context));
dockerOperations.startContainer(context);
hasStartedServices = true;
hasResumedNode = false;
context.log(logger, "Container successfully started, new containerState is " + containerState);
}
private Optional<Container> removeContainerIfNeededUpdateContainerState(
NodeAgentContext context, Optional<Container> existingContainer) {
if (existingContainer.isPresent()) {
Optional<String> reason = shouldRemoveContainer(context, existingContainer.get());
if (reason.isPresent()) {
removeContainer(context, existingContainer.get(), reason.get(), false);
return Optional.empty();
}
shouldRestartServices(context, existingContainer.get()).ifPresent(restartReason -> {
context.log(logger, "Will restart services: " + restartReason);
restartServices(context, existingContainer.get());
currentRestartGeneration = context.node().wantedRestartGeneration();
});
}
return existingContainer;
}
private Optional<String> shouldRestartServices( NodeAgentContext context, Container existingContainer) {
NodeSpec node = context.node();
if (node.wantedRestartGeneration().isEmpty()) return Optional.empty();
if (currentRestartGeneration.get() < node.wantedRestartGeneration().get()) {
return Optional.of("Restart requested - wanted restart generation has been bumped: "
+ currentRestartGeneration.get() + " -> " + node.wantedRestartGeneration().get());
}
ContainerResources wantedContainerResources = getContainerResources(context);
if (!wantedContainerResources.equalsMemory(existingContainer.resources)) {
return Optional.of("Container should be running with different memory allocation, wanted: " +
wantedContainerResources.toStringMemory() + ", actual: " + existingContainer.resources.toStringMemory());
}
return Optional.empty();
}
private void restartServices(NodeAgentContext context, Container existingContainer) {
if (existingContainer.state.isRunning() && context.node().state() == NodeState.active) {
context.log(logger, "Restarting services");
orchestratorSuspendNode(context);
dockerOperations.restartVespa(context);
}
}
private void stopServicesIfNeeded(NodeAgentContext context) {
if (hasStartedServices)
stopServices(context);
}
private void stopServices(NodeAgentContext context) {
context.log(logger, "Stopping services");
if (containerState == ABSENT) return;
try {
hasStartedServices = hasResumedNode = false;
dockerOperations.stopServices(context);
} catch (ContainerNotFoundException e) {
containerState = ABSENT;
}
}
@Override
public void stopForHostSuspension(NodeAgentContext context) {
getContainer(context).ifPresent(container -> removeContainer(context, container, "suspending host", true));
}
public void suspend(NodeAgentContext context) {
context.log(logger, "Suspending services on node");
if (containerState == ABSENT) return;
try {
hasResumedNode = false;
dockerOperations.suspendNode(context);
} catch (ContainerNotFoundException e) {
containerState = ABSENT;
} catch (RuntimeException e) {
context.log(logger, LogLevel.WARNING, "Failed trying to suspend container", e);
}
}
private Optional<String> shouldRemoveContainer(NodeAgentContext context, Container existingContainer) {
final NodeState nodeState = context.node().state();
if (nodeState == NodeState.dirty || nodeState == NodeState.provisioned) {
return Optional.of("Node in state " + nodeState + ", container should no longer be running");
}
if (context.node().wantedDockerImage().isPresent() &&
!context.node().wantedDockerImage().get().equals(existingContainer.image)) {
return Optional.of("The node is supposed to run a new Docker image: "
+ existingContainer.image.asString() + " -> " + context.node().wantedDockerImage().get().asString());
}
if (!existingContainer.state.isRunning()) {
return Optional.of("Container no longer running");
}
if (currentRebootGeneration < context.node().wantedRebootGeneration()) {
return Optional.of(String.format("Container reboot wanted. Current: %d, Wanted: %d",
currentRebootGeneration, context.node().wantedRebootGeneration()));
}
if (containerState == STARTING) return Optional.of("Container failed to start");
return Optional.empty();
}
private void removeContainer(NodeAgentContext context, Container existingContainer, String reason, boolean alreadySuspended) {
context.log(logger, "Will remove container: " + reason);
if (existingContainer.state.isRunning()) {
if (!alreadySuspended) {
orchestratorSuspendNode(context);
}
try {
if (context.node().state() != NodeState.dirty) {
suspend(context);
}
stopServices(context);
} catch (Exception e) {
context.log(logger, LogLevel.WARNING, "Failed stopping services, ignoring", e);
}
}
storageMaintainer.handleCoreDumpsForContainer(context, Optional.of(existingContainer));
dockerOperations.removeContainer(context, existingContainer);
currentRebootGeneration = context.node().wantedRebootGeneration();
containerState = ABSENT;
context.log(logger, "Container successfully removed, new containerState is " + containerState);
}
private void updateContainerIfNeeded(NodeAgentContext context, Container existingContainer) {
ContainerResources wantedContainerResources = getContainerResources(context);
if (wantedContainerResources.equalsCpu(existingContainer.resources)) return;
context.log(logger, "Container should be running with different CPU allocation, wanted: %s, current: %s",
wantedContainerResources.toStringCpu(), existingContainer.resources.toStringCpu());
orchestratorSuspendNode(context);
dockerOperations.updateContainer(context, wantedContainerResources);
}
private ContainerResources getContainerResources(NodeAgentContext context) {
double cpuCap = noCpuCap(context.zone()) ?
0 :
context.node().owner()
.map(appId -> containerCpuCap.with(FetchVector.Dimension.APPLICATION_ID, appId.serializedForm()))
.orElse(containerCpuCap)
.with(FetchVector.Dimension.HOSTNAME, context.node().hostname())
.value() * context.node().vcpus();
return ContainerResources.from(cpuCap, context.node().vcpus(), context.node().memoryGb());
}
private boolean noCpuCap(ZoneApi zone) {
return zone.getEnvironment() == Environment.dev || zone.getSystemName().isCd();
}
private boolean downloadImageIfNeeded(NodeSpec node, Optional<Container> container) {
if (node.wantedDockerImage().equals(container.map(c -> c.image))) return false;
return node.wantedDockerImage().map(dockerOperations::pullImageAsyncIfNeeded).orElse(false);
}
public void converge(NodeAgentContext context) {
try {
doConverge(context);
} catch (ConvergenceException e) {
context.log(logger, e.getMessage());
} catch (ContainerNotFoundException e) {
containerState = ABSENT;
context.log(logger, LogLevel.WARNING, "Container unexpectedly gone, resetting containerState to " + containerState);
} catch (DockerException e) {
numberOfUnhandledException++;
context.log(logger, LogLevel.ERROR, "Caught a DockerException", e);
} catch (Throwable e) {
numberOfUnhandledException++;
context.log(logger, LogLevel.ERROR, "Unhandled exception, ignoring", e);
}
}
private static void logChangesToNodeSpec(NodeAgentContext context, NodeSpec lastNode, NodeSpec node) {
StringBuilder builder = new StringBuilder();
appendIfDifferent(builder, "state", lastNode, node, NodeSpec::state);
if (builder.length() > 0) {
context.log(logger, LogLevel.INFO, "Changes to node: " + builder.toString());
}
}
private static <T> String fieldDescription(T value) {
return value == null ? "[absent]" : value.toString();
}
private static <T> void appendIfDifferent(StringBuilder builder, String name, NodeSpec oldNode, NodeSpec newNode, Function<NodeSpec, T> getter) {
T oldValue = oldNode == null ? null : getter.apply(oldNode);
T newValue = getter.apply(newNode);
if (!Objects.equals(oldValue, newValue)) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(name).append(" ").append(fieldDescription(oldValue)).append(" -> ").append(fieldDescription(newValue));
}
}
private Optional<Container> getContainer(NodeAgentContext context) {
if (containerState == ABSENT) return Optional.empty();
Optional<Container> container = dockerOperations.getContainer(context);
if (! container.isPresent()) containerState = ABSENT;
return container;
}
@Override
public int getAndResetNumberOfUnhandledExceptions() {
int temp = numberOfUnhandledException;
numberOfUnhandledException = 0;
return temp;
}
private void orchestratorSuspendNode(NodeAgentContext context) {
if (context.node().state() != NodeState.active) return;
context.log(logger, "Ask Orchestrator for permission to suspend node");
try {
orchestrator.suspend(context.hostname().value());
} catch (OrchestratorException e) {
try {
aclMaintainer.ifPresent(maintainer -> maintainer.converge(context));
} catch (RuntimeException suppressed) {
logger.log(LogLevel.WARNING, "Suppressing ACL update failure: " + suppressed);
e.addSuppressed(suppressed);
}
throw e;
}
}
protected ContainerData createContainerData(NodeAgentContext context) {
return new ContainerData() {
@Override
public void addFile(Path pathInContainer, String data) {
throw new UnsupportedOperationException("addFile not implemented");
}
@Override
public void addDirectory(Path pathInContainer) {
throw new UnsupportedOperationException("addDirectory not implemented");
}
@Override
public void createSymlink(Path symlink, Path target) {
throw new UnsupportedOperationException("createSymlink not implemented");
}
};
}
protected Optional<CredentialsMaintainer> credentialsMaintainer() {
return credentialsMaintainer;
}
} |
Yeah, good point, will add a stopServicesIfNeeded() and use that instead | void doConverge(NodeAgentContext context) {
NodeSpec node = context.node();
Optional<Container> container = getContainer(context);
if (!node.equals(lastNode)) {
logChangesToNodeSpec(context, lastNode, node);
if (currentRebootGeneration < node.currentRebootGeneration())
currentRebootGeneration = node.currentRebootGeneration();
if (currentRestartGeneration.isPresent() != node.currentRestartGeneration().isPresent() ||
currentRestartGeneration.map(current -> current < node.currentRestartGeneration().get()).orElse(false))
currentRestartGeneration = node.currentRestartGeneration();
lastNode = node;
}
switch (node.state()) {
case ready:
case reserved:
case failed:
case inactive:
removeContainerIfNeededUpdateContainerState(context, container);
updateNodeRepoWithCurrentAttributes(context);
break;
case parked:
updateNodeRepoWithCurrentAttributes(context);
stopServices(context);
break;
case active:
storageMaintainer.handleCoreDumpsForContainer(context, container);
storageMaintainer.getDiskUsageFor(context)
.map(diskUsage -> (double) diskUsage / BYTES_IN_GB / node.diskGb())
.filter(diskUtil -> diskUtil >= 0.8)
.ifPresent(diskUtil -> storageMaintainer.removeOldFilesFromNode(context));
if (downloadImageIfNeeded(node, container)) {
context.log(logger, "Waiting for image to download " + context.node().wantedDockerImage().get().asString());
return;
}
container = removeContainerIfNeededUpdateContainerState(context, container);
credentialsMaintainer.ifPresent(maintainer -> maintainer.converge(context));
if (! container.isPresent()) {
containerState = STARTING;
startContainer(context);
containerState = UNKNOWN;
} else {
updateContainerIfNeeded(context, container.get());
}
aclMaintainer.ifPresent(maintainer -> maintainer.converge(context));
startServicesIfNeeded(context);
resumeNodeIfNeeded(context);
healthChecker.ifPresent(checker -> checker.verifyHealth(context));
updateNodeRepoWithCurrentAttributes(context);
context.log(logger, "Call resume against Orchestrator");
orchestrator.resume(context.hostname().value());
break;
case provisioned:
nodeRepository.setNodeState(context.hostname().value(), NodeState.dirty);
break;
case dirty:
removeContainerIfNeededUpdateContainerState(context, container);
context.log(logger, "State is " + node.state() + ", will delete application storage and mark node as ready");
credentialsMaintainer.ifPresent(maintainer -> maintainer.clearCredentials(context));
storageMaintainer.archiveNodeStorage(context);
updateNodeRepoWithCurrentAttributes(context);
nodeRepository.setNodeState(context.hostname().value(), NodeState.ready);
break;
default:
throw new ConvergenceException("UNKNOWN STATE " + node.state().name());
}
} | stopServices(context); | void doConverge(NodeAgentContext context) {
NodeSpec node = context.node();
Optional<Container> container = getContainer(context);
if (!node.equals(lastNode)) {
logChangesToNodeSpec(context, lastNode, node);
if (currentRebootGeneration < node.currentRebootGeneration())
currentRebootGeneration = node.currentRebootGeneration();
if (currentRestartGeneration.isPresent() != node.currentRestartGeneration().isPresent() ||
currentRestartGeneration.map(current -> current < node.currentRestartGeneration().get()).orElse(false))
currentRestartGeneration = node.currentRestartGeneration();
lastNode = node;
}
switch (node.state()) {
case ready:
case reserved:
case failed:
case inactive:
removeContainerIfNeededUpdateContainerState(context, container);
updateNodeRepoWithCurrentAttributes(context);
break;
case parked:
updateNodeRepoWithCurrentAttributes(context);
stopServicesIfNeeded(context);
break;
case active:
storageMaintainer.handleCoreDumpsForContainer(context, container);
storageMaintainer.getDiskUsageFor(context)
.map(diskUsage -> (double) diskUsage / BYTES_IN_GB / node.diskGb())
.filter(diskUtil -> diskUtil >= 0.8)
.ifPresent(diskUtil -> storageMaintainer.removeOldFilesFromNode(context));
if (downloadImageIfNeeded(node, container)) {
context.log(logger, "Waiting for image to download " + context.node().wantedDockerImage().get().asString());
return;
}
container = removeContainerIfNeededUpdateContainerState(context, container);
credentialsMaintainer.ifPresent(maintainer -> maintainer.converge(context));
if (! container.isPresent()) {
containerState = STARTING;
startContainer(context);
containerState = UNKNOWN;
} else {
updateContainerIfNeeded(context, container.get());
}
aclMaintainer.ifPresent(maintainer -> maintainer.converge(context));
startServicesIfNeeded(context);
resumeNodeIfNeeded(context);
healthChecker.ifPresent(checker -> checker.verifyHealth(context));
updateNodeRepoWithCurrentAttributes(context);
context.log(logger, "Call resume against Orchestrator");
orchestrator.resume(context.hostname().value());
break;
case provisioned:
nodeRepository.setNodeState(context.hostname().value(), NodeState.dirty);
break;
case dirty:
removeContainerIfNeededUpdateContainerState(context, container);
context.log(logger, "State is " + node.state() + ", will delete application storage and mark node as ready");
credentialsMaintainer.ifPresent(maintainer -> maintainer.clearCredentials(context));
storageMaintainer.archiveNodeStorage(context);
updateNodeRepoWithCurrentAttributes(context);
nodeRepository.setNodeState(context.hostname().value(), NodeState.ready);
break;
default:
throw new ConvergenceException("UNKNOWN STATE " + node.state().name());
}
} | class NodeAgentImpl implements NodeAgent {
private static final long BYTES_IN_GB = 1_000_000_000L;
private static final Logger logger = Logger.getLogger(NodeAgentImpl.class.getName());
private final AtomicBoolean terminated = new AtomicBoolean(false);
private boolean hasResumedNode = false;
private boolean hasStartedServices = true;
private final NodeAgentContextSupplier contextSupplier;
private final NodeRepository nodeRepository;
private final Orchestrator orchestrator;
private final DockerOperations dockerOperations;
private final StorageMaintainer storageMaintainer;
private final Optional<CredentialsMaintainer> credentialsMaintainer;
private final Optional<AclMaintainer> aclMaintainer;
private final Optional<HealthChecker> healthChecker;
private final DoubleFlag containerCpuCap;
private Thread loopThread;
private ContainerState containerState = UNKNOWN;
private NodeSpec lastNode;
private int numberOfUnhandledException = 0;
private long currentRebootGeneration = 0;
private Optional<Long> currentRestartGeneration = Optional.empty();
/**
* ABSENT means container is definitely absent - A container that was absent will not suddenly appear without
* NodeAgent explicitly starting it.
* STARTING state is set just before we attempt to start a container, if successful we move to the next state.
* Otherwise we can't be certain. A container that was running a minute ago may no longer be running without
* NodeAgent doing anything (container could have crashed). Therefore we always have to ask docker daemon
* to get updated state of the container.
*/
enum ContainerState {
ABSENT,
STARTING,
UNKNOWN
}
public NodeAgentImpl(
final NodeAgentContextSupplier contextSupplier,
final NodeRepository nodeRepository,
final Orchestrator orchestrator,
final DockerOperations dockerOperations,
final StorageMaintainer storageMaintainer,
final FlagSource flagSource,
final Optional<CredentialsMaintainer> credentialsMaintainer,
final Optional<AclMaintainer> aclMaintainer,
final Optional<HealthChecker> healthChecker) {
this.contextSupplier = contextSupplier;
this.nodeRepository = nodeRepository;
this.orchestrator = orchestrator;
this.dockerOperations = dockerOperations;
this.storageMaintainer = storageMaintainer;
this.credentialsMaintainer = credentialsMaintainer;
this.aclMaintainer = aclMaintainer;
this.healthChecker = healthChecker;
this.containerCpuCap = Flags.CONTAINER_CPU_CAP.bindTo(flagSource);
}
@Override
public void start(NodeAgentContext initialContext) {
if (loopThread != null)
throw new IllegalStateException("Can not re-start a node agent.");
loopThread = new Thread(() -> {
while (!terminated.get()) {
try {
NodeAgentContext context = contextSupplier.nextContext();
converge(context);
} catch (InterruptedException ignored) { }
}
});
loopThread.setName("tick-" + initialContext.hostname());
loopThread.start();
}
@Override
public void stopForRemoval(NodeAgentContext context) {
if (!terminated.compareAndSet(false, true))
throw new IllegalStateException("Can not re-stop a node agent.");
contextSupplier.interrupt();
do {
try {
loopThread.join();
} catch (InterruptedException ignored) { }
} while (loopThread.isAlive());
context.log(logger, "Stopped");
}
void startServicesIfNeeded(NodeAgentContext context) {
if (!hasStartedServices) {
context.log(logger, "Starting services");
dockerOperations.startServices(context);
hasStartedServices = true;
}
}
void resumeNodeIfNeeded(NodeAgentContext context) {
if (!hasResumedNode) {
context.log(logger, LogLevel.DEBUG, "Starting optional node program resume command");
dockerOperations.resumeNode(context);
hasResumedNode = true;
}
}
private void updateNodeRepoWithCurrentAttributes(NodeAgentContext context) {
final NodeAttributes currentNodeAttributes = new NodeAttributes();
final NodeAttributes newNodeAttributes = new NodeAttributes();
if (context.node().wantedRestartGeneration().isPresent() &&
!Objects.equals(context.node().currentRestartGeneration(), currentRestartGeneration)) {
currentNodeAttributes.withRestartGeneration(context.node().currentRestartGeneration());
newNodeAttributes.withRestartGeneration(currentRestartGeneration);
}
if (!Objects.equals(context.node().currentRebootGeneration(), currentRebootGeneration)) {
currentNodeAttributes.withRebootGeneration(context.node().currentRebootGeneration());
newNodeAttributes.withRebootGeneration(currentRebootGeneration);
}
Optional<DockerImage> actualDockerImage = context.node().wantedDockerImage().filter(n -> containerState == UNKNOWN);
if (!Objects.equals(context.node().currentDockerImage(), actualDockerImage)) {
DockerImage currentImage = context.node().currentDockerImage().orElse(DockerImage.EMPTY);
DockerImage newImage = actualDockerImage.orElse(DockerImage.EMPTY);
currentNodeAttributes.withDockerImage(currentImage);
currentNodeAttributes.withVespaVersion(currentImage.tagAsVersion());
newNodeAttributes.withDockerImage(newImage);
newNodeAttributes.withVespaVersion(newImage.tagAsVersion());
}
publishStateToNodeRepoIfChanged(context, currentNodeAttributes, newNodeAttributes);
}
private void publishStateToNodeRepoIfChanged(NodeAgentContext context, NodeAttributes currentAttributes, NodeAttributes newAttributes) {
if (!currentAttributes.equals(newAttributes)) {
context.log(logger, "Publishing new set of attributes to node repo: %s -> %s",
currentAttributes, newAttributes);
nodeRepository.updateNodeAttributes(context.hostname().value(), newAttributes);
}
}
private void startContainer(NodeAgentContext context) {
ContainerData containerData = createContainerData(context);
dockerOperations.createContainer(context, containerData, getContainerResources(context));
dockerOperations.startContainer(context);
hasStartedServices = true;
hasResumedNode = false;
context.log(logger, "Container successfully started, new containerState is " + containerState);
}
private Optional<Container> removeContainerIfNeededUpdateContainerState(
NodeAgentContext context, Optional<Container> existingContainer) {
if (existingContainer.isPresent()) {
Optional<String> reason = shouldRemoveContainer(context, existingContainer.get());
if (reason.isPresent()) {
removeContainer(context, existingContainer.get(), reason.get(), false);
return Optional.empty();
}
shouldRestartServices(context, existingContainer.get()).ifPresent(restartReason -> {
context.log(logger, "Will restart services: " + restartReason);
restartServices(context, existingContainer.get());
currentRestartGeneration = context.node().wantedRestartGeneration();
});
}
return existingContainer;
}
private Optional<String> shouldRestartServices( NodeAgentContext context, Container existingContainer) {
NodeSpec node = context.node();
if (node.wantedRestartGeneration().isEmpty()) return Optional.empty();
if (currentRestartGeneration.get() < node.wantedRestartGeneration().get()) {
return Optional.of("Restart requested - wanted restart generation has been bumped: "
+ currentRestartGeneration.get() + " -> " + node.wantedRestartGeneration().get());
}
ContainerResources wantedContainerResources = getContainerResources(context);
if (!wantedContainerResources.equalsMemory(existingContainer.resources)) {
return Optional.of("Container should be running with different memory allocation, wanted: " +
wantedContainerResources.toStringMemory() + ", actual: " + existingContainer.resources.toStringMemory());
}
return Optional.empty();
}
private void restartServices(NodeAgentContext context, Container existingContainer) {
if (existingContainer.state.isRunning() && context.node().state() == NodeState.active) {
context.log(logger, "Restarting services");
orchestratorSuspendNode(context);
dockerOperations.restartVespa(context);
}
}
private void stopServices(NodeAgentContext context) {
context.log(logger, "Stopping services");
if (containerState == ABSENT) return;
try {
hasStartedServices = hasResumedNode = false;
dockerOperations.stopServices(context);
} catch (ContainerNotFoundException e) {
containerState = ABSENT;
}
}
@Override
public void stopForHostSuspension(NodeAgentContext context) {
getContainer(context).ifPresent(container -> removeContainer(context, container, "suspending host", true));
}
public void suspend(NodeAgentContext context) {
context.log(logger, "Suspending services on node");
if (containerState == ABSENT) return;
try {
hasResumedNode = false;
dockerOperations.suspendNode(context);
} catch (ContainerNotFoundException e) {
containerState = ABSENT;
} catch (RuntimeException e) {
context.log(logger, LogLevel.WARNING, "Failed trying to suspend container", e);
}
}
private Optional<String> shouldRemoveContainer(NodeAgentContext context, Container existingContainer) {
final NodeState nodeState = context.node().state();
if (nodeState == NodeState.dirty || nodeState == NodeState.provisioned) {
return Optional.of("Node in state " + nodeState + ", container should no longer be running");
}
if (context.node().wantedDockerImage().isPresent() &&
!context.node().wantedDockerImage().get().equals(existingContainer.image)) {
return Optional.of("The node is supposed to run a new Docker image: "
+ existingContainer.image.asString() + " -> " + context.node().wantedDockerImage().get().asString());
}
if (!existingContainer.state.isRunning()) {
return Optional.of("Container no longer running");
}
if (currentRebootGeneration < context.node().wantedRebootGeneration()) {
return Optional.of(String.format("Container reboot wanted. Current: %d, Wanted: %d",
currentRebootGeneration, context.node().wantedRebootGeneration()));
}
if (containerState == STARTING) return Optional.of("Container failed to start");
return Optional.empty();
}
private void removeContainer(NodeAgentContext context, Container existingContainer, String reason, boolean alreadySuspended) {
context.log(logger, "Will remove container: " + reason);
if (existingContainer.state.isRunning()) {
if (!alreadySuspended) {
orchestratorSuspendNode(context);
}
try {
if (context.node().state() != NodeState.dirty) {
suspend(context);
}
stopServices(context);
} catch (Exception e) {
context.log(logger, LogLevel.WARNING, "Failed stopping services, ignoring", e);
}
}
storageMaintainer.handleCoreDumpsForContainer(context, Optional.of(existingContainer));
dockerOperations.removeContainer(context, existingContainer);
currentRebootGeneration = context.node().wantedRebootGeneration();
containerState = ABSENT;
context.log(logger, "Container successfully removed, new containerState is " + containerState);
}
private void updateContainerIfNeeded(NodeAgentContext context, Container existingContainer) {
ContainerResources wantedContainerResources = getContainerResources(context);
if (wantedContainerResources.equalsCpu(existingContainer.resources)) return;
context.log(logger, "Container should be running with different CPU allocation, wanted: %s, current: %s",
wantedContainerResources.toStringCpu(), existingContainer.resources.toStringCpu());
orchestratorSuspendNode(context);
dockerOperations.updateContainer(context, wantedContainerResources);
}
private ContainerResources getContainerResources(NodeAgentContext context) {
double cpuCap = noCpuCap(context.zone()) ?
0 :
context.node().owner()
.map(appId -> containerCpuCap.with(FetchVector.Dimension.APPLICATION_ID, appId.serializedForm()))
.orElse(containerCpuCap)
.with(FetchVector.Dimension.HOSTNAME, context.node().hostname())
.value() * context.node().vcpus();
return ContainerResources.from(cpuCap, context.node().vcpus(), context.node().memoryGb());
}
private boolean noCpuCap(ZoneApi zone) {
return zone.getEnvironment() == Environment.dev || zone.getSystemName().isCd();
}
private boolean downloadImageIfNeeded(NodeSpec node, Optional<Container> container) {
if (node.wantedDockerImage().equals(container.map(c -> c.image))) return false;
return node.wantedDockerImage().map(dockerOperations::pullImageAsyncIfNeeded).orElse(false);
}
public void converge(NodeAgentContext context) {
try {
doConverge(context);
} catch (ConvergenceException e) {
context.log(logger, e.getMessage());
} catch (ContainerNotFoundException e) {
containerState = ABSENT;
context.log(logger, LogLevel.WARNING, "Container unexpectedly gone, resetting containerState to " + containerState);
} catch (DockerException e) {
numberOfUnhandledException++;
context.log(logger, LogLevel.ERROR, "Caught a DockerException", e);
} catch (Throwable e) {
numberOfUnhandledException++;
context.log(logger, LogLevel.ERROR, "Unhandled exception, ignoring", e);
}
}
private static void logChangesToNodeSpec(NodeAgentContext context, NodeSpec lastNode, NodeSpec node) {
StringBuilder builder = new StringBuilder();
appendIfDifferent(builder, "state", lastNode, node, NodeSpec::state);
if (builder.length() > 0) {
context.log(logger, LogLevel.INFO, "Changes to node: " + builder.toString());
}
}
private static <T> String fieldDescription(T value) {
return value == null ? "[absent]" : value.toString();
}
private static <T> void appendIfDifferent(StringBuilder builder, String name, NodeSpec oldNode, NodeSpec newNode, Function<NodeSpec, T> getter) {
T oldValue = oldNode == null ? null : getter.apply(oldNode);
T newValue = getter.apply(newNode);
if (!Objects.equals(oldValue, newValue)) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(name).append(" ").append(fieldDescription(oldValue)).append(" -> ").append(fieldDescription(newValue));
}
}
private Optional<Container> getContainer(NodeAgentContext context) {
if (containerState == ABSENT) return Optional.empty();
Optional<Container> container = dockerOperations.getContainer(context);
if (! container.isPresent()) containerState = ABSENT;
return container;
}
@Override
public int getAndResetNumberOfUnhandledExceptions() {
int temp = numberOfUnhandledException;
numberOfUnhandledException = 0;
return temp;
}
private void orchestratorSuspendNode(NodeAgentContext context) {
if (context.node().state() != NodeState.active) return;
context.log(logger, "Ask Orchestrator for permission to suspend node");
try {
orchestrator.suspend(context.hostname().value());
} catch (OrchestratorException e) {
try {
aclMaintainer.ifPresent(maintainer -> maintainer.converge(context));
} catch (RuntimeException suppressed) {
logger.log(LogLevel.WARNING, "Suppressing ACL update failure: " + suppressed);
e.addSuppressed(suppressed);
}
throw e;
}
}
protected ContainerData createContainerData(NodeAgentContext context) {
return new ContainerData() {
@Override
public void addFile(Path pathInContainer, String data) {
throw new UnsupportedOperationException("addFile not implemented");
}
@Override
public void addDirectory(Path pathInContainer) {
throw new UnsupportedOperationException("addDirectory not implemented");
}
@Override
public void createSymlink(Path symlink, Path target) {
throw new UnsupportedOperationException("createSymlink not implemented");
}
};
}
protected Optional<CredentialsMaintainer> credentialsMaintainer() {
return credentialsMaintainer;
}
} | class NodeAgentImpl implements NodeAgent {
private static final long BYTES_IN_GB = 1_000_000_000L;
private static final Logger logger = Logger.getLogger(NodeAgentImpl.class.getName());
private final AtomicBoolean terminated = new AtomicBoolean(false);
private boolean hasResumedNode = false;
private boolean hasStartedServices = true;
private final NodeAgentContextSupplier contextSupplier;
private final NodeRepository nodeRepository;
private final Orchestrator orchestrator;
private final DockerOperations dockerOperations;
private final StorageMaintainer storageMaintainer;
private final Optional<CredentialsMaintainer> credentialsMaintainer;
private final Optional<AclMaintainer> aclMaintainer;
private final Optional<HealthChecker> healthChecker;
private final DoubleFlag containerCpuCap;
private Thread loopThread;
private ContainerState containerState = UNKNOWN;
private NodeSpec lastNode;
private int numberOfUnhandledException = 0;
private long currentRebootGeneration = 0;
private Optional<Long> currentRestartGeneration = Optional.empty();
/**
* ABSENT means container is definitely absent - A container that was absent will not suddenly appear without
* NodeAgent explicitly starting it.
* STARTING state is set just before we attempt to start a container, if successful we move to the next state.
* Otherwise we can't be certain. A container that was running a minute ago may no longer be running without
* NodeAgent doing anything (container could have crashed). Therefore we always have to ask docker daemon
* to get updated state of the container.
*/
enum ContainerState {
ABSENT,
STARTING,
UNKNOWN
}
public NodeAgentImpl(
final NodeAgentContextSupplier contextSupplier,
final NodeRepository nodeRepository,
final Orchestrator orchestrator,
final DockerOperations dockerOperations,
final StorageMaintainer storageMaintainer,
final FlagSource flagSource,
final Optional<CredentialsMaintainer> credentialsMaintainer,
final Optional<AclMaintainer> aclMaintainer,
final Optional<HealthChecker> healthChecker) {
this.contextSupplier = contextSupplier;
this.nodeRepository = nodeRepository;
this.orchestrator = orchestrator;
this.dockerOperations = dockerOperations;
this.storageMaintainer = storageMaintainer;
this.credentialsMaintainer = credentialsMaintainer;
this.aclMaintainer = aclMaintainer;
this.healthChecker = healthChecker;
this.containerCpuCap = Flags.CONTAINER_CPU_CAP.bindTo(flagSource);
}
@Override
public void start(NodeAgentContext initialContext) {
if (loopThread != null)
throw new IllegalStateException("Can not re-start a node agent.");
loopThread = new Thread(() -> {
while (!terminated.get()) {
try {
NodeAgentContext context = contextSupplier.nextContext();
converge(context);
} catch (InterruptedException ignored) { }
}
});
loopThread.setName("tick-" + initialContext.hostname());
loopThread.start();
}
@Override
public void stopForRemoval(NodeAgentContext context) {
if (!terminated.compareAndSet(false, true))
throw new IllegalStateException("Can not re-stop a node agent.");
contextSupplier.interrupt();
do {
try {
loopThread.join();
} catch (InterruptedException ignored) { }
} while (loopThread.isAlive());
context.log(logger, "Stopped");
}
void startServicesIfNeeded(NodeAgentContext context) {
if (!hasStartedServices) {
context.log(logger, "Starting services");
dockerOperations.startServices(context);
hasStartedServices = true;
}
}
void resumeNodeIfNeeded(NodeAgentContext context) {
if (!hasResumedNode) {
context.log(logger, LogLevel.DEBUG, "Starting optional node program resume command");
dockerOperations.resumeNode(context);
hasResumedNode = true;
}
}
private void updateNodeRepoWithCurrentAttributes(NodeAgentContext context) {
final NodeAttributes currentNodeAttributes = new NodeAttributes();
final NodeAttributes newNodeAttributes = new NodeAttributes();
if (context.node().wantedRestartGeneration().isPresent() &&
!Objects.equals(context.node().currentRestartGeneration(), currentRestartGeneration)) {
currentNodeAttributes.withRestartGeneration(context.node().currentRestartGeneration());
newNodeAttributes.withRestartGeneration(currentRestartGeneration);
}
if (!Objects.equals(context.node().currentRebootGeneration(), currentRebootGeneration)) {
currentNodeAttributes.withRebootGeneration(context.node().currentRebootGeneration());
newNodeAttributes.withRebootGeneration(currentRebootGeneration);
}
Optional<DockerImage> actualDockerImage = context.node().wantedDockerImage().filter(n -> containerState == UNKNOWN);
if (!Objects.equals(context.node().currentDockerImage(), actualDockerImage)) {
DockerImage currentImage = context.node().currentDockerImage().orElse(DockerImage.EMPTY);
DockerImage newImage = actualDockerImage.orElse(DockerImage.EMPTY);
currentNodeAttributes.withDockerImage(currentImage);
currentNodeAttributes.withVespaVersion(currentImage.tagAsVersion());
newNodeAttributes.withDockerImage(newImage);
newNodeAttributes.withVespaVersion(newImage.tagAsVersion());
}
publishStateToNodeRepoIfChanged(context, currentNodeAttributes, newNodeAttributes);
}
private void publishStateToNodeRepoIfChanged(NodeAgentContext context, NodeAttributes currentAttributes, NodeAttributes newAttributes) {
if (!currentAttributes.equals(newAttributes)) {
context.log(logger, "Publishing new set of attributes to node repo: %s -> %s",
currentAttributes, newAttributes);
nodeRepository.updateNodeAttributes(context.hostname().value(), newAttributes);
}
}
private void startContainer(NodeAgentContext context) {
ContainerData containerData = createContainerData(context);
dockerOperations.createContainer(context, containerData, getContainerResources(context));
dockerOperations.startContainer(context);
hasStartedServices = true;
hasResumedNode = false;
context.log(logger, "Container successfully started, new containerState is " + containerState);
}
private Optional<Container> removeContainerIfNeededUpdateContainerState(
NodeAgentContext context, Optional<Container> existingContainer) {
if (existingContainer.isPresent()) {
Optional<String> reason = shouldRemoveContainer(context, existingContainer.get());
if (reason.isPresent()) {
removeContainer(context, existingContainer.get(), reason.get(), false);
return Optional.empty();
}
shouldRestartServices(context, existingContainer.get()).ifPresent(restartReason -> {
context.log(logger, "Will restart services: " + restartReason);
restartServices(context, existingContainer.get());
currentRestartGeneration = context.node().wantedRestartGeneration();
});
}
return existingContainer;
}
private Optional<String> shouldRestartServices( NodeAgentContext context, Container existingContainer) {
NodeSpec node = context.node();
if (node.wantedRestartGeneration().isEmpty()) return Optional.empty();
if (currentRestartGeneration.get() < node.wantedRestartGeneration().get()) {
return Optional.of("Restart requested - wanted restart generation has been bumped: "
+ currentRestartGeneration.get() + " -> " + node.wantedRestartGeneration().get());
}
ContainerResources wantedContainerResources = getContainerResources(context);
if (!wantedContainerResources.equalsMemory(existingContainer.resources)) {
return Optional.of("Container should be running with different memory allocation, wanted: " +
wantedContainerResources.toStringMemory() + ", actual: " + existingContainer.resources.toStringMemory());
}
return Optional.empty();
}
private void restartServices(NodeAgentContext context, Container existingContainer) {
if (existingContainer.state.isRunning() && context.node().state() == NodeState.active) {
context.log(logger, "Restarting services");
orchestratorSuspendNode(context);
dockerOperations.restartVespa(context);
}
}
private void stopServicesIfNeeded(NodeAgentContext context) {
if (hasStartedServices)
stopServices(context);
}
private void stopServices(NodeAgentContext context) {
context.log(logger, "Stopping services");
if (containerState == ABSENT) return;
try {
hasStartedServices = hasResumedNode = false;
dockerOperations.stopServices(context);
} catch (ContainerNotFoundException e) {
containerState = ABSENT;
}
}
@Override
public void stopForHostSuspension(NodeAgentContext context) {
getContainer(context).ifPresent(container -> removeContainer(context, container, "suspending host", true));
}
public void suspend(NodeAgentContext context) {
context.log(logger, "Suspending services on node");
if (containerState == ABSENT) return;
try {
hasResumedNode = false;
dockerOperations.suspendNode(context);
} catch (ContainerNotFoundException e) {
containerState = ABSENT;
} catch (RuntimeException e) {
context.log(logger, LogLevel.WARNING, "Failed trying to suspend container", e);
}
}
private Optional<String> shouldRemoveContainer(NodeAgentContext context, Container existingContainer) {
final NodeState nodeState = context.node().state();
if (nodeState == NodeState.dirty || nodeState == NodeState.provisioned) {
return Optional.of("Node in state " + nodeState + ", container should no longer be running");
}
if (context.node().wantedDockerImage().isPresent() &&
!context.node().wantedDockerImage().get().equals(existingContainer.image)) {
return Optional.of("The node is supposed to run a new Docker image: "
+ existingContainer.image.asString() + " -> " + context.node().wantedDockerImage().get().asString());
}
if (!existingContainer.state.isRunning()) {
return Optional.of("Container no longer running");
}
if (currentRebootGeneration < context.node().wantedRebootGeneration()) {
return Optional.of(String.format("Container reboot wanted. Current: %d, Wanted: %d",
currentRebootGeneration, context.node().wantedRebootGeneration()));
}
if (containerState == STARTING) return Optional.of("Container failed to start");
return Optional.empty();
}
private void removeContainer(NodeAgentContext context, Container existingContainer, String reason, boolean alreadySuspended) {
context.log(logger, "Will remove container: " + reason);
if (existingContainer.state.isRunning()) {
if (!alreadySuspended) {
orchestratorSuspendNode(context);
}
try {
if (context.node().state() != NodeState.dirty) {
suspend(context);
}
stopServices(context);
} catch (Exception e) {
context.log(logger, LogLevel.WARNING, "Failed stopping services, ignoring", e);
}
}
storageMaintainer.handleCoreDumpsForContainer(context, Optional.of(existingContainer));
dockerOperations.removeContainer(context, existingContainer);
currentRebootGeneration = context.node().wantedRebootGeneration();
containerState = ABSENT;
context.log(logger, "Container successfully removed, new containerState is " + containerState);
}
private void updateContainerIfNeeded(NodeAgentContext context, Container existingContainer) {
ContainerResources wantedContainerResources = getContainerResources(context);
if (wantedContainerResources.equalsCpu(existingContainer.resources)) return;
context.log(logger, "Container should be running with different CPU allocation, wanted: %s, current: %s",
wantedContainerResources.toStringCpu(), existingContainer.resources.toStringCpu());
orchestratorSuspendNode(context);
dockerOperations.updateContainer(context, wantedContainerResources);
}
private ContainerResources getContainerResources(NodeAgentContext context) {
double cpuCap = noCpuCap(context.zone()) ?
0 :
context.node().owner()
.map(appId -> containerCpuCap.with(FetchVector.Dimension.APPLICATION_ID, appId.serializedForm()))
.orElse(containerCpuCap)
.with(FetchVector.Dimension.HOSTNAME, context.node().hostname())
.value() * context.node().vcpus();
return ContainerResources.from(cpuCap, context.node().vcpus(), context.node().memoryGb());
}
private boolean noCpuCap(ZoneApi zone) {
return zone.getEnvironment() == Environment.dev || zone.getSystemName().isCd();
}
private boolean downloadImageIfNeeded(NodeSpec node, Optional<Container> container) {
if (node.wantedDockerImage().equals(container.map(c -> c.image))) return false;
return node.wantedDockerImage().map(dockerOperations::pullImageAsyncIfNeeded).orElse(false);
}
public void converge(NodeAgentContext context) {
try {
doConverge(context);
} catch (ConvergenceException e) {
context.log(logger, e.getMessage());
} catch (ContainerNotFoundException e) {
containerState = ABSENT;
context.log(logger, LogLevel.WARNING, "Container unexpectedly gone, resetting containerState to " + containerState);
} catch (DockerException e) {
numberOfUnhandledException++;
context.log(logger, LogLevel.ERROR, "Caught a DockerException", e);
} catch (Throwable e) {
numberOfUnhandledException++;
context.log(logger, LogLevel.ERROR, "Unhandled exception, ignoring", e);
}
}
private static void logChangesToNodeSpec(NodeAgentContext context, NodeSpec lastNode, NodeSpec node) {
StringBuilder builder = new StringBuilder();
appendIfDifferent(builder, "state", lastNode, node, NodeSpec::state);
if (builder.length() > 0) {
context.log(logger, LogLevel.INFO, "Changes to node: " + builder.toString());
}
}
private static <T> String fieldDescription(T value) {
return value == null ? "[absent]" : value.toString();
}
private static <T> void appendIfDifferent(StringBuilder builder, String name, NodeSpec oldNode, NodeSpec newNode, Function<NodeSpec, T> getter) {
T oldValue = oldNode == null ? null : getter.apply(oldNode);
T newValue = getter.apply(newNode);
if (!Objects.equals(oldValue, newValue)) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(name).append(" ").append(fieldDescription(oldValue)).append(" -> ").append(fieldDescription(newValue));
}
}
private Optional<Container> getContainer(NodeAgentContext context) {
if (containerState == ABSENT) return Optional.empty();
Optional<Container> container = dockerOperations.getContainer(context);
if (! container.isPresent()) containerState = ABSENT;
return container;
}
@Override
public int getAndResetNumberOfUnhandledExceptions() {
int temp = numberOfUnhandledException;
numberOfUnhandledException = 0;
return temp;
}
private void orchestratorSuspendNode(NodeAgentContext context) {
if (context.node().state() != NodeState.active) return;
context.log(logger, "Ask Orchestrator for permission to suspend node");
try {
orchestrator.suspend(context.hostname().value());
} catch (OrchestratorException e) {
try {
aclMaintainer.ifPresent(maintainer -> maintainer.converge(context));
} catch (RuntimeException suppressed) {
logger.log(LogLevel.WARNING, "Suppressing ACL update failure: " + suppressed);
e.addSuppressed(suppressed);
}
throw e;
}
}
protected ContainerData createContainerData(NodeAgentContext context) {
return new ContainerData() {
@Override
public void addFile(Path pathInContainer, String data) {
throw new UnsupportedOperationException("addFile not implemented");
}
@Override
public void addDirectory(Path pathInContainer) {
throw new UnsupportedOperationException("addDirectory not implemented");
}
@Override
public void createSymlink(Path symlink, Path target) {
throw new UnsupportedOperationException("createSymlink not implemented");
}
};
}
protected Optional<CredentialsMaintainer> credentialsMaintainer() {
return credentialsMaintainer;
}
} |
indentation | public LoadBalancerInstance create(ApplicationId application, ClusterSpec.Id cluster, Set<Real> reals, boolean force) {
var proxyNodes = new ArrayList<>(nodeRepository.getNodes(NodeType.proxy));
proxyNodes.sort(hostnameComparator);
if (proxyNodes.size() == 0) {
throw new IllegalStateException("Missing proxy nodes in node repository");
}
var firstProxyNode = proxyNodes.get(0);
var networkNames = proxyNodes.stream()
.flatMap(node -> node.ipAddresses().stream())
.map(SharedLoadBalancerService::withPrefixLength)
.collect(Collectors.toSet());
return new LoadBalancerInstance(
HostName.from(firstProxyNode.hostname()),
Optional.empty(),
Set.of(4080, 4443),
networkNames,
reals
);
} | .flatMap(node -> node.ipAddresses().stream()) | public LoadBalancerInstance create(ApplicationId application, ClusterSpec.Id cluster, Set<Real> reals, boolean force) {
var proxyNodes = new ArrayList<>(nodeRepository.getNodes(NodeType.proxy));
proxyNodes.sort(hostnameComparator);
if (proxyNodes.size() == 0) {
throw new IllegalStateException("Missing proxy nodes in node repository");
}
var firstProxyNode = proxyNodes.get(0);
var networkNames = proxyNodes.stream()
.flatMap(node -> node.ipAddresses().stream())
.map(SharedLoadBalancerService::withPrefixLength)
.collect(Collectors.toSet());
return new LoadBalancerInstance(
HostName.from(firstProxyNode.hostname()),
Optional.empty(),
Set.of(4080, 4443),
networkNames,
reals
);
} | class SharedLoadBalancerService implements LoadBalancerService {
private static final Comparator<Node> hostnameComparator = Comparator.comparing(Node::hostname);
private final NodeRepository nodeRepository;
@Inject
public SharedLoadBalancerService(NodeRepository nodeRepository) {
this.nodeRepository = Objects.requireNonNull(nodeRepository, "nodeRepository must be non-null");
}
@Override
@Override
public void remove(ApplicationId application, ClusterSpec.Id cluster) {
}
@Override
public Protocol protocol() {
return Protocol.dualstack;
}
private static String withPrefixLength(String address) {
if (IP.isV6(address)) {
return address + "/128";
}
return address + "/32";
}
} | class SharedLoadBalancerService implements LoadBalancerService {
private static final Comparator<Node> hostnameComparator = Comparator.comparing(Node::hostname);
private final NodeRepository nodeRepository;
@Inject
public SharedLoadBalancerService(NodeRepository nodeRepository) {
this.nodeRepository = Objects.requireNonNull(nodeRepository, "nodeRepository must be non-null");
}
@Override
@Override
public void remove(ApplicationId application, ClusterSpec.Id cluster) {
}
@Override
public Protocol protocol() {
return Protocol.dualstack;
}
private static String withPrefixLength(String address) {
if (IP.isV6(address)) {
return address + "/128";
}
return address + "/32";
}
} |
```suggestion if ((certificateFile == null) != (privateKeyFile == null)) { ``` | Optional<CertificateAndKey> certificateAndKey() throws CliArgumentsException {
Path certificateFile = fileValue(CERTIFICATE_OPTION).orElse(null);
Path privateKeyFile = fileValue(PRIVATE_KEY_OPTION).orElse(null);
if ((certificateFile != null && privateKeyFile == null) || (certificateFile == null && privateKeyFile != null)) {
throw new CliArgumentsException(String.format("Both '%s' and '%s' must be specified together", CERTIFICATE_OPTION, PRIVATE_KEY_OPTION));
}
if (privateKeyFile == null && certificateFile == null) return Optional.empty();
return Optional.of(new CertificateAndKey(certificateFile, privateKeyFile));
} | if ((certificateFile != null && privateKeyFile == null) || (certificateFile == null && privateKeyFile != null)) { | Optional<CertificateAndKey> certificateAndKey() throws CliArgumentsException {
Path certificateFile = fileValue(CERTIFICATE_OPTION).orElse(null);
Path privateKeyFile = fileValue(PRIVATE_KEY_OPTION).orElse(null);
if ((certificateFile == null) != (privateKeyFile == null)) {
throw new CliArgumentsException(String.format("Both '%s' and '%s' must be specified together", CERTIFICATE_OPTION, PRIVATE_KEY_OPTION));
}
if (privateKeyFile == null && certificateFile == null) return Optional.empty();
return Optional.of(new CertificateAndKey(certificateFile, privateKeyFile));
} | class CliArguments {
private static final Options optionsDefinition = createOptions();
private static final String HELP_OPTION = "help";
private static final String VERSION_OPTION = "version";
private static final String ENDPOINT_OPTION = "endpoint";
private static final String FILE_OPTION = "file";
private static final String CONNECTIONS_OPTION = "connections";
private static final String MAX_STREAMS_PER_CONNECTION = "max-streams-per-connection";
private static final String CERTIFICATE_OPTION = "certificate";
private static final String PRIVATE_KEY_OPTION = "private-key";
private static final String CA_CERTIFICATES_OPTION = "ca-certificates";
private static final String DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION = "disable-ssl-hostname-verification";
private final CommandLine arguments;
private CliArguments(CommandLine arguments) {
this.arguments = arguments;
}
static CliArguments fromRawArgs(String[] rawArgs) throws CliArgumentsException {
CommandLineParser parser = new DefaultParser();
try {
return new CliArguments(parser.parse(optionsDefinition, rawArgs));
} catch (ParseException e) {
throw new CliArgumentsException(e);
}
}
URI endpoint() throws CliArgumentsException {
try {
URL url = (URL) arguments.getParsedOptionValue(ENDPOINT_OPTION);
if (url == null) throw new CliArgumentsException("Endpoint must be specified");
return url.toURI();
} catch (ParseException | URISyntaxException e) {
throw new CliArgumentsException("Invalid endpoint: " + e.getMessage(), e);
}
}
boolean helpSpecified() { return has(HELP_OPTION); }
boolean versionSpecified() { return has(VERSION_OPTION); }
OptionalInt connections() throws CliArgumentsException { return intValue(CONNECTIONS_OPTION); }
OptionalInt maxStreamsPerConnection() throws CliArgumentsException { return intValue(MAX_STREAMS_PER_CONNECTION); }
Optional<Path> caCertificates() throws CliArgumentsException { return fileValue(CA_CERTIFICATES_OPTION); }
Path inputFile() throws CliArgumentsException {
return fileValue(FILE_OPTION)
.orElseThrow(() -> new CliArgumentsException("Feed file must be specified"));
}
boolean sslHostnameVerificationDisabled() { return has(DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION); }
private OptionalInt intValue(String option) throws CliArgumentsException {
try {
Number number = (Number) arguments.getParsedOptionValue(option);
return number != null ? OptionalInt.of(number.intValue()) : OptionalInt.empty();
} catch (ParseException e) {
throw new CliArgumentsException(String.format("Invalid value for '%s': %s", option, e.getMessage()), e);
}
}
private Optional<Path> fileValue(String option) throws CliArgumentsException {
try {
File certificateFile = (File) arguments.getParsedOptionValue(option);
if (certificateFile == null) return Optional.empty();
return Optional.of(certificateFile.toPath());
} catch (ParseException e) {
throw new CliArgumentsException(String.format("Invalid value for '%s': %s", option, e.getMessage()), e);
}
}
private boolean has(String option) { return arguments.hasOption(option); }
private static Options createOptions() {
return new Options()
.addOption(Option.builder()
.longOpt(HELP_OPTION)
.build())
.addOption(Option.builder()
.longOpt(VERSION_OPTION)
.build())
.addOption(Option.builder()
.longOpt(ENDPOINT_OPTION)
.hasArg()
.type(URL.class)
.build())
.addOption(Option.builder()
.longOpt(FILE_OPTION)
.type(File.class)
.hasArg()
.build())
.addOption(Option.builder()
.longOpt(CONNECTIONS_OPTION)
.hasArg()
.type(Number.class)
.build())
.addOption(Option.builder()
.longOpt(MAX_STREAMS_PER_CONNECTION)
.hasArg()
.type(Number.class)
.build())
.addOption(Option.builder()
.longOpt(CONNECTIONS_OPTION)
.hasArg()
.type(Number.class)
.build())
.addOption(Option.builder()
.longOpt(CERTIFICATE_OPTION)
.type(File.class)
.hasArg()
.build())
.addOption(Option.builder()
.longOpt(PRIVATE_KEY_OPTION)
.type(File.class)
.hasArg()
.build())
.addOption(Option.builder()
.longOpt(CA_CERTIFICATES_OPTION)
.type(File.class)
.hasArg()
.build())
.addOption(Option.builder()
.longOpt(DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION)
.build());
}
void printHelp(OutputStream out) {
HelpFormatter formatter = new HelpFormatter();
PrintWriter writer = new PrintWriter(out);
formatter.printHelp(
writer,
formatter.getWidth(),
"vespa-feed-client <options>",
"Vespa feed client (" + Vespa.VERSION + ")",
optionsDefinition,
formatter.getLeftPadding(),
formatter.getDescPadding(),
"");
writer.flush();
}
static class CliArgumentsException extends Exception {
CliArgumentsException(String message, Throwable cause) { super(message, cause); }
CliArgumentsException(Throwable cause) { super(cause.getMessage(), cause); }
CliArgumentsException(String message) { super(message); }
}
static class CertificateAndKey {
final Path certificateFile;
final Path privateKeyFile;
CertificateAndKey(Path certificateFile, Path privateKeyFile) {
this.certificateFile = certificateFile;
this.privateKeyFile = privateKeyFile;
}
}
} | class CliArguments {
private static final Options optionsDefinition = createOptions();
private static final String HELP_OPTION = "help";
private static final String VERSION_OPTION = "version";
private static final String ENDPOINT_OPTION = "endpoint";
private static final String FILE_OPTION = "file";
private static final String CONNECTIONS_OPTION = "connections";
private static final String MAX_STREAMS_PER_CONNECTION = "max-streams-per-connection";
private static final String CERTIFICATE_OPTION = "certificate";
private static final String PRIVATE_KEY_OPTION = "private-key";
private static final String CA_CERTIFICATES_OPTION = "ca-certificates";
private static final String DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION = "disable-ssl-hostname-verification";
private final CommandLine arguments;
private CliArguments(CommandLine arguments) {
this.arguments = arguments;
}
static CliArguments fromRawArgs(String[] rawArgs) throws CliArgumentsException {
CommandLineParser parser = new DefaultParser();
try {
return new CliArguments(parser.parse(optionsDefinition, rawArgs));
} catch (ParseException e) {
throw new CliArgumentsException(e);
}
}
URI endpoint() throws CliArgumentsException {
try {
URL url = (URL) arguments.getParsedOptionValue(ENDPOINT_OPTION);
if (url == null) throw new CliArgumentsException("Endpoint must be specified");
return url.toURI();
} catch (ParseException | URISyntaxException e) {
throw new CliArgumentsException("Invalid endpoint: " + e.getMessage(), e);
}
}
boolean helpSpecified() { return has(HELP_OPTION); }
boolean versionSpecified() { return has(VERSION_OPTION); }
OptionalInt connections() throws CliArgumentsException { return intValue(CONNECTIONS_OPTION); }
OptionalInt maxStreamsPerConnection() throws CliArgumentsException { return intValue(MAX_STREAMS_PER_CONNECTION); }
Optional<Path> caCertificates() throws CliArgumentsException { return fileValue(CA_CERTIFICATES_OPTION); }
Path inputFile() throws CliArgumentsException {
return fileValue(FILE_OPTION)
.orElseThrow(() -> new CliArgumentsException("Feed file must be specified"));
}
boolean sslHostnameVerificationDisabled() { return has(DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION); }
private OptionalInt intValue(String option) throws CliArgumentsException {
try {
Number number = (Number) arguments.getParsedOptionValue(option);
return number != null ? OptionalInt.of(number.intValue()) : OptionalInt.empty();
} catch (ParseException e) {
throw new CliArgumentsException(String.format("Invalid value for '%s': %s", option, e.getMessage()), e);
}
}
private Optional<Path> fileValue(String option) throws CliArgumentsException {
try {
File certificateFile = (File) arguments.getParsedOptionValue(option);
if (certificateFile == null) return Optional.empty();
return Optional.of(certificateFile.toPath());
} catch (ParseException e) {
throw new CliArgumentsException(String.format("Invalid value for '%s': %s", option, e.getMessage()), e);
}
}
private boolean has(String option) { return arguments.hasOption(option); }
private static Options createOptions() {
return new Options()
.addOption(Option.builder()
.longOpt(HELP_OPTION)
.build())
.addOption(Option.builder()
.longOpt(VERSION_OPTION)
.build())
.addOption(Option.builder()
.longOpt(ENDPOINT_OPTION)
.hasArg()
.type(URL.class)
.build())
.addOption(Option.builder()
.longOpt(FILE_OPTION)
.type(File.class)
.hasArg()
.build())
.addOption(Option.builder()
.longOpt(CONNECTIONS_OPTION)
.hasArg()
.type(Number.class)
.build())
.addOption(Option.builder()
.longOpt(MAX_STREAMS_PER_CONNECTION)
.hasArg()
.type(Number.class)
.build())
.addOption(Option.builder()
.longOpt(CONNECTIONS_OPTION)
.hasArg()
.type(Number.class)
.build())
.addOption(Option.builder()
.longOpt(CERTIFICATE_OPTION)
.type(File.class)
.hasArg()
.build())
.addOption(Option.builder()
.longOpt(PRIVATE_KEY_OPTION)
.type(File.class)
.hasArg()
.build())
.addOption(Option.builder()
.longOpt(CA_CERTIFICATES_OPTION)
.type(File.class)
.hasArg()
.build())
.addOption(Option.builder()
.longOpt(DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION)
.build());
}
void printHelp(OutputStream out) {
HelpFormatter formatter = new HelpFormatter();
PrintWriter writer = new PrintWriter(out);
formatter.printHelp(
writer,
formatter.getWidth(),
"vespa-feed-client <options>",
"Vespa feed client (" + Vespa.VERSION + ")",
optionsDefinition,
formatter.getLeftPadding(),
formatter.getDescPadding(),
"");
writer.flush();
}
static class CliArgumentsException extends Exception {
CliArgumentsException(String message, Throwable cause) { super(message, cause); }
CliArgumentsException(Throwable cause) { super(cause.getMessage(), cause); }
CliArgumentsException(String message) { super(message); }
}
static class CertificateAndKey {
final Path certificateFile;
final Path privateKeyFile;
CertificateAndKey(Path certificateFile, Path privateKeyFile) {
this.certificateFile = certificateFile;
this.privateKeyFile = privateKeyFile;
}
}
} |
this is now a dead link | public void missing_security_clients_pem_fails_in_public() {
Element clusterElem = DomBuilderTest.parse("<container version='1.0' />");
try {
DeployState state = new DeployState.Builder()
.properties(
new TestProperties()
.setHostedVespa(true)
.setTlsSecrets(Optional.of(new TlsSecrets("CERT", "KEY"))))
.zone(new Zone(SystemName.Public, Environment.prod, RegionName.defaultName()))
.build();
createModel(root, state, null, clusterElem);
} catch (RuntimeException e) {
assertEquals(e.getMessage(), "Client certificate authority security/clients.pem is missing - see: https:
return;
}
fail();
} | assertEquals(e.getMessage(), "Client certificate authority security/clients.pem is missing - see: https: | public void missing_security_clients_pem_fails_in_public() {
Element clusterElem = DomBuilderTest.parse("<container version='1.0' />");
try {
DeployState state = new DeployState.Builder()
.properties(
new TestProperties()
.setHostedVespa(true)
.setTlsSecrets(Optional.of(new TlsSecrets("CERT", "KEY"))))
.zone(new Zone(SystemName.Public, Environment.prod, RegionName.defaultName()))
.build();
createModel(root, state, null, clusterElem);
} catch (RuntimeException e) {
assertEquals(e.getMessage(), "Client certificate authority security/clients.pem is missing - see: https:
return;
}
fail();
} | class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
@Rule
public TemporaryFolder applicationFolder = new TemporaryFolder();
@Test
public void deprecated_jdisc_tag_is_allowed() {
Element clusterElem = DomBuilderTest.parse(
"<jdisc version='1.0'>",
nodesXml,
"</jdisc>" );
TestLogger logger = new TestLogger();
createModel(root, logger, clusterElem);
AbstractService container = (AbstractService)root.getProducer("jdisc/container.0");
assertNotNull(container);
assertFalse(logger.msgs.isEmpty());
assertEquals(Level.WARNING, logger.msgs.get(0).getFirst());
assertEquals("'jdisc' is deprecated as tag name. Use 'container' instead.", logger.msgs.get(0).getSecond());
}
@Test
public void default_port_is_4080() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
nodesXml,
"</container>" );
createModel(root, clusterElem);
AbstractService container = (AbstractService)root.getProducer("container/container.0");
assertThat(container.getRelativePort(0), is(getDefaults().vespaWebServicePort()));
}
@Test
public void http_server_port_is_configurable_and_does_not_affect_other_ports() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <http>",
" <server port='9000' id='foo' />",
" </http>",
nodesXml,
"</container>" );
createModel(root, clusterElem);
AbstractService container = (AbstractService)root.getProducer("container/container.0");
assertThat(container.getRelativePort(0), is(9000));
assertThat(container.getRelativePort(1), is(not(9001)));
}
@Test
public void fail_if_http_port_is_not_4080_in_hosted_vespa() throws Exception {
String servicesXml =
"<services>" +
"<admin version='3.0'>" +
" <nodes count='1'/>" +
"</admin>" +
"<container version='1.0'>" +
" <http>" +
" <server port='9000' id='foo' />" +
" </http>" +
nodesXml +
"</container>" +
"</services>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
final TestLogger logger = new TestLogger();
new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(applicationPackage)
.deployLogger(logger)
.properties(new TestProperties().setHostedVespa(true))
.build());
assertFalse(logger.msgs.isEmpty());
assertThat(logger.msgs.get(0).getSecond(), containsString(String.format("You cannot set port to anything else than %d", Container.BASEPORT)));
}
@Test
public void one_cluster_with_explicit_port_and_one_without_is_ok() {
Element cluster1Elem = DomBuilderTest.parse(
"<container id='cluster1' version='1.0' />");
Element cluster2Elem = DomBuilderTest.parse(
"<container id='cluster2' version='1.0'>",
" <http>",
" <server port='8000' id='foo' />",
" </http>",
"</container>");
createModel(root, cluster1Elem, cluster2Elem);
}
@Test
public void two_clusters_without_explicit_port_throws_exception() {
Element cluster1Elem = DomBuilderTest.parse(
"<container id='cluster1' version='1.0'>",
nodesXml,
"</container>" );
Element cluster2Elem = DomBuilderTest.parse(
"<container id='cluster2' version='1.0'>",
nodesXml,
"</container>" );
try {
createModel(root, cluster1Elem, cluster2Elem);
fail("Expected exception");
} catch (RuntimeException e) {
assertThat(e.getMessage(), containsString("cannot reserve port"));
}
}
@Test
public void verify_bindings_for_builtin_handlers() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0' />"
);
createModel(root, clusterElem);
JdiscBindingsConfig config = root.getConfig(JdiscBindingsConfig.class, "default/container.0");
JdiscBindingsConfig.Handlers defaultRootHandler = config.handlers(BindingsOverviewHandler.class.getName());
assertThat(defaultRootHandler.serverBindings(), contains("http:
JdiscBindingsConfig.Handlers applicationStatusHandler = config.handlers(ApplicationStatusHandler.class.getName());
assertThat(applicationStatusHandler.serverBindings(),
contains("http:
JdiscBindingsConfig.Handlers fileRequestHandler = config.handlers(VipStatusHandler.class.getName());
assertThat(fileRequestHandler.serverBindings(),
contains("http:
}
@Test
public void default_root_handler_is_disabled_when_user_adds_a_handler_with_same_binding() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>" +
" <handler id='userRootHandler'>" +
" <binding>" + ContainerCluster.ROOT_HANDLER_BINDING + "</binding>" +
" </handler>" +
"</container>");
createModel(root, clusterElem);
ComponentsConfig.Components userRootHandler = getComponent(componentsConfig(), BindingsOverviewHandler.class.getName());
assertThat(userRootHandler, nullValue());
}
@Test
public void handler_bindings_are_included_in_discBindings_config() {
createClusterWithJDiscHandler();
String discBindingsConfig = root.getConfig(JdiscBindingsConfig.class, "default").toString();
assertThat(discBindingsConfig, containsString("{discHandler}"));
assertThat(discBindingsConfig, containsString(".serverBindings[0] \"binding0\""));
assertThat(discBindingsConfig, containsString(".serverBindings[1] \"binding1\""));
assertThat(discBindingsConfig, containsString(".clientBindings[0] \"clientBinding\""));
}
@Test
public void handlers_are_included_in_components_config() {
createClusterWithJDiscHandler();
assertThat(componentsConfig().toString(), containsString(".id \"discHandler\""));
}
private void createClusterWithJDiscHandler() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <handler id='discHandler'>",
" <binding>binding0</binding>",
" <binding>binding1</binding>",
" <clientBinding>clientBinding</clientBinding>",
" </handler>",
"</container>");
createModel(root, clusterElem);
}
@Test
public void servlets_are_included_in_ServletPathConfig() {
createClusterWithServlet();
ServletPathsConfig servletPathsConfig = root.getConfig(ServletPathsConfig.class, "default");
assertThat(servletPathsConfig.servlets().values().iterator().next().path(), is("p/a/t/h"));
}
@Test
public void servletconfig_is_produced() {
createClusterWithServlet();
String configId = getContainerCluster("default").getServletMap().
values().iterator().next().getConfigId();
ServletConfigConfig servletConfig = root.getConfig(ServletConfigConfig.class, configId);
assertThat(servletConfig.map().get("myKey"), is("myValue"));
}
private void createClusterWithServlet() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <servlet id='myServlet' class='myClass' bundle='myBundle'>",
" <path>p/a/t/h</path>",
" <servlet-config>",
" <myKey>myValue</myKey>",
" </servlet-config>",
" </servlet>",
"</container>");
createModel(root, clusterElem);
}
@Test
public void processing_handler_bindings_can_be_overridden() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <processing>",
" <binding>binding0</binding>",
" <binding>binding1</binding>",
" </processing>",
"</container>");
createModel(root, clusterElem);
String discBindingsConfig = root.getConfig(JdiscBindingsConfig.class, "default").toString();
assertThat(discBindingsConfig, containsString(".serverBindings[0] \"binding0\""));
assertThat(discBindingsConfig, containsString(".serverBindings[1] \"binding1\""));
assertThat(discBindingsConfig, not(containsString("/processing/*")));
}
@Test
public void clientProvider_bindings_are_included_in_discBindings_config() {
createModelWithClientProvider();
String discBindingsConfig = root.getConfig(JdiscBindingsConfig.class, "default").toString();
assertThat(discBindingsConfig, containsString("{discClient}"));
assertThat(discBindingsConfig, containsString(".clientBindings[0] \"binding0\""));
assertThat(discBindingsConfig, containsString(".clientBindings[1] \"binding1\""));
assertThat(discBindingsConfig, containsString(".serverBindings[0] \"serverBinding\""));
}
@Test
public void clientProviders_are_included_in_components_config() {
createModelWithClientProvider();
assertThat(componentsConfig().toString(), containsString(".id \"discClient\""));
}
private void createModelWithClientProvider() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>" +
" <client id='discClient'>" +
" <binding>binding0</binding>" +
" <binding>binding1</binding>" +
" <serverBinding>serverBinding</serverBinding>" +
" </client>" +
"</container>" );
createModel(root, clusterElem);
}
@Test
public void serverProviders_are_included_in_components_config() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>" +
" <server id='discServer' />" +
"</container>" );
createModel(root, clusterElem);
String componentsConfig = componentsConfig().toString();
assertThat(componentsConfig, containsString(".id \"discServer\""));
}
private String getChainsConfig(String configId) {
return root.getConfig(ChainsConfig.class, configId).toString();
}
@Test
public void searchHandler_gets_only_search_chains_in_chains_config() {
createClusterWithProcessingAndSearchChains();
String searchHandlerConfigId = "default/component/com.yahoo.search.handler.SearchHandler";
String chainsConfig = getChainsConfig(searchHandlerConfigId);
assertThat(chainsConfig, containsLineWithPattern(".*\\.id \"testSearcher@default\"$"));
assertThat(chainsConfig, not(containsLineWithPattern(".*\\.id \"testProcessor@default\"$")));
}
@Test
public void processingHandler_gets_only_processing_chains_in_chains_config() {
createClusterWithProcessingAndSearchChains();
String processingHandlerConfigId = "default/component/com.yahoo.processing.handler.ProcessingHandler";
String chainsConfig = getChainsConfig(processingHandlerConfigId);
assertThat(chainsConfig, containsLineWithPattern(".*\\.id \"testProcessor@default\"$"));
assertThat(chainsConfig, not(containsLineWithPattern(".*\\.id \"testSearcher@default\"$")));
}
private void createClusterWithProcessingAndSearchChains() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>" +
" <search>" +
" <chain id='default'>" +
" <searcher id='testSearcher' />" +
" </chain>" +
" </search>" +
" <processing>" +
" <chain id='default'>" +
" <processor id='testProcessor'/>" +
" </chain>" +
" </processing>" +
nodesXml +
" </container>");
createModel(root, clusterElem);
}
@Test
public void user_config_can_be_overridden_on_node() {
Element containerElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <config name=\"prelude.cluster.qr-monitor\">" +
" <requesttimeout>111</requesttimeout>",
" </config> " +
" <nodes>",
" <node hostalias='host1' />",
" <node hostalias='host2'>",
" <config name=\"prelude.cluster.qr-monitor\">",
" <requesttimeout>222</requesttimeout>",
" </config> ",
" </node>",
" </nodes>",
"</container>");
root = ContentClusterUtils.createMockRoot(new String[]{"host1", "host2"});
createModel(root, containerElem);
ContainerCluster cluster = (ContainerCluster)root.getChildren().get("default");
assertThat(cluster.getContainers().size(), is(2));
assertEquals(root.getConfig(QrMonitorConfig.class, "default/container.0").requesttimeout(), 111);
assertEquals(root.getConfig(QrMonitorConfig.class, "default/container.1").requesttimeout(), 222);
}
@Test
public void nested_components_are_injected_to_handlers() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <handler id='myHandler'>",
" <component id='injected' />",
" </handler>",
" <client id='myClient'>",
" <component id='injected' />",
" </client>",
"</container>");
createModel(root, clusterElem);
Component<?,?> handler = getContainerComponent("default", "myHandler");
assertThat(handler.getInjectedComponentIds(), hasItem("injected@myHandler"));
Component<?,?> client = getContainerComponent("default", "myClient");
assertThat(client.getInjectedComponentIds(), hasItem("injected@myClient"));
}
@Test
public void component_includes_are_added() {
VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/application/include_dirs");
VespaModel model = creator.create(true);
ContainerCluster cluster = model.getContainerClusters().get("default");
Map<ComponentId, Component<?, ?>> componentsMap = cluster.getComponentsMap();
Component<?,?> example = componentsMap.get(
ComponentId.fromString("test.Exampledocproc"));
assertThat(example.getComponentId().getName(), is("test.Exampledocproc"));
}
@Test
public void affinity_is_set() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <http>",
" <server port='" + getDefaults().vespaWebServicePort() + "' id='main' />",
" </http>",
" <nodes cpu-socket-affinity='true'>",
" <node hostalias='node1' />",
" </nodes>" +
"</container>");
createModel(root, clusterElem);
assertTrue(getContainerCluster("default").getContainers().get(0).getAffinity().isPresent());
assertThat(getContainerCluster("default").getContainers().get(0).getAffinity().get().cpuSocket(), is(0));
}
@Test
public void singlenode_servicespec_is_used_with_hosts_xml() throws IOException, SAXException {
String servicesXml = "<container id='default' version='1.0' />";
String hostsXml = "<hosts>\n" +
" <host name=\"test1.yahoo.com\">\n" +
" <alias>node1</alias>\n" +
" </host>\n" +
"</hosts>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder()
.withHosts(hostsXml)
.withServices(servicesXml)
.build();
VespaModel model = new VespaModel(applicationPackage);
assertThat(model.getHostSystem().getHosts().size(), is(1));
}
@Test
public void http_aliases_are_stored_on_cluster_and_on_service_properties() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <aliases>",
" <service-alias>service1</service-alias>",
" <service-alias>service2</service-alias>",
" <endpoint-alias>foo1.bar1.com</endpoint-alias>",
" <endpoint-alias>foo2.bar2.com</endpoint-alias>",
" </aliases>",
" <nodes>",
" <node hostalias='host1' />",
" </nodes>",
"</container>");
createModel(root, clusterElem);
assertEquals(getContainerCluster("default").serviceAliases().get(0), "service1");
assertEquals(getContainerCluster("default").endpointAliases().get(0), "foo1.bar1.com");
assertEquals(getContainerCluster("default").serviceAliases().get(1), "service2");
assertEquals(getContainerCluster("default").endpointAliases().get(1), "foo2.bar2.com");
assertEquals(getContainerCluster("default").getContainers().get(0).getServicePropertyString("servicealiases"), "service1,service2");
assertEquals(getContainerCluster("default").getContainers().get(0).getServicePropertyString("endpointaliases"), "foo1.bar1.com,foo2.bar2.com");
}
@Test
public void http_aliases_are_only_honored_in_prod_environment() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <aliases>",
" <service-alias>service1</service-alias>",
" <endpoint-alias>foo1.bar1.com</endpoint-alias>",
" </aliases>",
" <nodes>",
" <node hostalias='host1' />",
" </nodes>",
"</container>");
DeployState deployState = new DeployState.Builder().zone(new Zone(Environment.dev, RegionName.from("us-east-1"))).build();
createModel(root, deployState, null, clusterElem);
assertEquals(0, getContainerCluster("default").serviceAliases().size());
assertEquals(0, getContainerCluster("default").endpointAliases().size());
assertNull(getContainerCluster("default").getContainers().get(0).getServicePropertyString("servicealiases"));
assertNull(getContainerCluster("default").getContainers().get(0).getServicePropertyString("endpointaliases"));
}
@Test
public void endpoints_are_added_to_containers() throws IOException, SAXException {
final var servicesXml = joinLines("",
"<container id='comics-search' version='1.0'>",
" <nodes>",
" <node hostalias='host1' />",
" </nodes>",
"</container>"
);
final var deploymentXml = joinLines("",
"<deployment version='1.0'>",
" <prod />",
"</deployment>"
);
final var applicationPackage = new MockApplicationPackage.Builder()
.withServices(servicesXml)
.withDeploymentSpec(deploymentXml)
.build();
final var deployState = new DeployState.Builder()
.applicationPackage(applicationPackage)
.zone(new Zone(Environment.prod, RegionName.from("us-east-1")))
.endpoints(Set.of(new ContainerEndpoint("comics-search", List.of("nalle", "balle"))))
.properties(new TestProperties().setHostedVespa(true))
.build();
final var model = new VespaModel(new NullConfigModelRegistry(), deployState);
final var containers = model.getContainerClusters().values().stream()
.flatMap(cluster -> cluster.getContainers().stream())
.collect(Collectors.toList());
assertFalse("Missing container objects based on configuration", containers.isEmpty());
containers.forEach(container -> {
final var rotations = container.getServicePropertyString("rotations").split(",");
final var rotationsSet = Set.of(rotations);
assertEquals(Set.of("balle", "nalle"), rotationsSet);
});
}
@Test
public void singlenode_servicespec_is_used_with_hosted_vespa() throws IOException, SAXException {
String servicesXml = "<container id='default' version='1.0' />";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.modelHostProvisioner(new InMemoryProvisioner(true, "host1.yahoo.com", "host2.yahoo.com"))
.applicationPackage(applicationPackage)
.properties(new TestProperties()
.setMultitenant(true)
.setHostedVespa(true))
.build());
assertEquals(1, model.getHostSystem().getHosts().size());
}
@Test(expected = IllegalArgumentException.class)
public void renderers_named_JsonRenderer_are_not_allowed() {
createModel(root, generateContainerElementWithRenderer("JsonRenderer"));
}
@Test(expected = IllegalArgumentException.class)
public void renderers_named_DefaultRenderer_are_not_allowed() {
createModel(root, generateContainerElementWithRenderer("XmlRenderer"));
}
@Test
public void renderers_named_something_else_are_allowed() {
createModel(root, generateContainerElementWithRenderer("my-little-renderer"));
}
@Test
public void vip_status_handler_uses_file_for_hosted_vespa() throws Exception {
String servicesXml = "<services>" +
"<container version='1.0'>" +
nodesXml +
"</container>" +
"</services>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(applicationPackage)
.properties(new TestProperties().setHostedVespa(true))
.build());
AbstractConfigProducerRoot modelRoot = model.getRoot();
VipStatusConfig vipStatusConfig = modelRoot.getConfig(VipStatusConfig.class, "container/component/status.html-status-handler");
assertTrue(vipStatusConfig.accessdisk());
assertEquals(ContainerModelBuilder.HOSTED_VESPA_STATUS_FILE, vipStatusConfig.statusfile());
}
@Test
public void qrconfig_is_produced() throws IOException, SAXException {
String servicesXml =
"<services>" +
"<admin version='3.0'>" +
" <nodes count='1'/>" +
"</admin>" +
"<container id ='default' version='1.0'>" +
" <nodes>" +
" <node hostalias='node1' />" +
" </nodes>" +
"</container>" +
"</services>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder()
.withServices(servicesXml)
.build();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(applicationPackage)
.properties(new TestProperties())
.build());
String hostname = HostName.getLocalhost();
QrConfig config = model.getConfig(QrConfig.class, "default/container.0");
assertEquals("default.container.0", config.discriminator());
assertEquals(19102, config.rpc().port());
assertEquals("vespa/service/default/container.0", config.rpc().slobrokId());
assertTrue(config.rpc().enabled());
assertEquals("", config.rpc().host());
assertFalse(config.restartOnDeploy());
assertEquals("filedistribution/" + hostname, config.filedistributor().configid());
}
@Test
public void secret_store_can_be_set_up() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <secret-store>",
" <group name='group1' environment='env1'/>",
" </secret-store>",
"</container>");
createModel(root, clusterElem);
SecretStore secretStore = getContainerCluster("container").getSecretStore().get();
assertEquals("group1", secretStore.getGroups().get(0).name);
assertEquals("env1", secretStore.getGroups().get(0).environment);
}
@Test
@Test
public void security_clients_pem_is_picked_up() {
var applicationPackage = new MockApplicationPackage.Builder()
.withRoot(applicationFolder.getRoot())
.build();
applicationPackage.getFile(Path.fromString("security")).createDirectory();
applicationPackage.getFile(Path.fromString("security/clients.pem")).writeFile(new StringReader("I am a very nice certificate"));
var deployState = DeployState.createTestState(applicationPackage);
Element clusterElem = DomBuilderTest.parse("<container version='1.0' />");
createModel(root, deployState, null, clusterElem);
assertEquals(Optional.of("I am a very nice certificate"), getContainerCluster("container").getTlsClientAuthority());
}
@Test
public void environment_vars_are_honoured() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <nodes>",
" <environment-variables>",
" <KMP_SETTING>1</KMP_SETTING>",
" <KMP_AFFINITY>granularity=fine,verbose,compact,1,0</KMP_AFFINITY>",
" </environment-variables>",
" <node hostalias='mockhost'/>",
" </nodes>",
"</container>" );
createModel(root, clusterElem);
QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder();
root.getConfig(qrStartBuilder, "container/container.0");
QrStartConfig qrStartConfig = new QrStartConfig(qrStartBuilder);
assertEquals("KMP_SETTING=1 KMP_AFFINITY=granularity=fine,verbose,compact,1,0 ", qrStartConfig.qrs().env());
}
private void verifyAvailableprocessors(boolean isHosted, Flavor flavor, int expectProcessors) throws IOException, SAXException {
DeployState deployState = new DeployState.Builder()
.modelHostProvisioner(flavor != null ? new SingleNodeProvisioner(flavor) : new SingleNodeProvisioner())
.properties(new TestProperties()
.setMultitenant(isHosted)
.setHostedVespa(isHosted))
.build();
MockRoot myRoot = new MockRoot("root", deployState);
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <nodes>",
" <node hostalias='localhost'/>",
" </nodes>",
"</container>"
);
createModel(myRoot, clusterElem);
QrStartConfig.Builder qsB = new QrStartConfig.Builder();
myRoot.getConfig(qsB, "container/container.0");
QrStartConfig qsC= new QrStartConfig(qsB);
assertEquals(expectProcessors, qsC.jvm().availableProcessors());
}
@Test
public void requireThatAvailableProcessorsFollowFlavor() throws IOException, SAXException {
verifyAvailableprocessors(false, null,0);
verifyAvailableprocessors(true, null,0);
verifyAvailableprocessors(true, new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build()), 9);
verifyAvailableprocessors(true, new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(1).build()), 2);
}
@Test
public void requireThatProvidingTlsSecretOpensPort4443() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
nodesXml,
"</container>" );
DeployState state = new DeployState.Builder().properties(new TestProperties().setHostedVespa(true).setTlsSecrets(Optional.of(new TlsSecrets("CERT", "KEY")))).build();
createModel(root, state, null, clusterElem);
ApplicationContainer container = (ApplicationContainer)root.getProducer("container/container.0");
List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().getConnectorFactories();
assertEquals(2, connectorFactories.size());
List<Integer> ports = connectorFactories.stream()
.map(ConnectorFactory::getListenPort)
.collect(Collectors.toList());
assertThat(ports, Matchers.containsInAnyOrder(8080, 4443));
ConnectorFactory tlsPort = connectorFactories.stream().filter(connectorFactory -> connectorFactory.getListenPort() == 4443).findFirst().orElseThrow();
ConnectorConfig.Builder builder = new ConnectorConfig.Builder();
tlsPort.getConfig(builder);
ConnectorConfig connectorConfig = new ConnectorConfig(builder);
assertTrue(connectorConfig.ssl().enabled());
assertEquals("CERT", connectorConfig.ssl().certificate());
assertEquals("KEY", connectorConfig.ssl().privateKey());
assertEquals(4443, connectorConfig.listenPort());
}
private Element generateContainerElementWithRenderer(String rendererId) {
return DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <search>",
String.format(" <renderer id='%s'/>", rendererId),
" </search>",
"</container>");
}
} | class ContainerModelBuilderTest extends ContainerModelBuilderTestBase {
@Rule
public TemporaryFolder applicationFolder = new TemporaryFolder();
@Test
public void deprecated_jdisc_tag_is_allowed() {
Element clusterElem = DomBuilderTest.parse(
"<jdisc version='1.0'>",
nodesXml,
"</jdisc>" );
TestLogger logger = new TestLogger();
createModel(root, logger, clusterElem);
AbstractService container = (AbstractService)root.getProducer("jdisc/container.0");
assertNotNull(container);
assertFalse(logger.msgs.isEmpty());
assertEquals(Level.WARNING, logger.msgs.get(0).getFirst());
assertEquals("'jdisc' is deprecated as tag name. Use 'container' instead.", logger.msgs.get(0).getSecond());
}
@Test
public void default_port_is_4080() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
nodesXml,
"</container>" );
createModel(root, clusterElem);
AbstractService container = (AbstractService)root.getProducer("container/container.0");
assertThat(container.getRelativePort(0), is(getDefaults().vespaWebServicePort()));
}
@Test
public void http_server_port_is_configurable_and_does_not_affect_other_ports() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <http>",
" <server port='9000' id='foo' />",
" </http>",
nodesXml,
"</container>" );
createModel(root, clusterElem);
AbstractService container = (AbstractService)root.getProducer("container/container.0");
assertThat(container.getRelativePort(0), is(9000));
assertThat(container.getRelativePort(1), is(not(9001)));
}
@Test
public void fail_if_http_port_is_not_4080_in_hosted_vespa() throws Exception {
String servicesXml =
"<services>" +
"<admin version='3.0'>" +
" <nodes count='1'/>" +
"</admin>" +
"<container version='1.0'>" +
" <http>" +
" <server port='9000' id='foo' />" +
" </http>" +
nodesXml +
"</container>" +
"</services>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
final TestLogger logger = new TestLogger();
new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(applicationPackage)
.deployLogger(logger)
.properties(new TestProperties().setHostedVespa(true))
.build());
assertFalse(logger.msgs.isEmpty());
assertThat(logger.msgs.get(0).getSecond(), containsString(String.format("You cannot set port to anything else than %d", Container.BASEPORT)));
}
@Test
public void one_cluster_with_explicit_port_and_one_without_is_ok() {
Element cluster1Elem = DomBuilderTest.parse(
"<container id='cluster1' version='1.0' />");
Element cluster2Elem = DomBuilderTest.parse(
"<container id='cluster2' version='1.0'>",
" <http>",
" <server port='8000' id='foo' />",
" </http>",
"</container>");
createModel(root, cluster1Elem, cluster2Elem);
}
@Test
public void two_clusters_without_explicit_port_throws_exception() {
Element cluster1Elem = DomBuilderTest.parse(
"<container id='cluster1' version='1.0'>",
nodesXml,
"</container>" );
Element cluster2Elem = DomBuilderTest.parse(
"<container id='cluster2' version='1.0'>",
nodesXml,
"</container>" );
try {
createModel(root, cluster1Elem, cluster2Elem);
fail("Expected exception");
} catch (RuntimeException e) {
assertThat(e.getMessage(), containsString("cannot reserve port"));
}
}
@Test
public void verify_bindings_for_builtin_handlers() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0' />"
);
createModel(root, clusterElem);
JdiscBindingsConfig config = root.getConfig(JdiscBindingsConfig.class, "default/container.0");
JdiscBindingsConfig.Handlers defaultRootHandler = config.handlers(BindingsOverviewHandler.class.getName());
assertThat(defaultRootHandler.serverBindings(), contains("http:
JdiscBindingsConfig.Handlers applicationStatusHandler = config.handlers(ApplicationStatusHandler.class.getName());
assertThat(applicationStatusHandler.serverBindings(),
contains("http:
JdiscBindingsConfig.Handlers fileRequestHandler = config.handlers(VipStatusHandler.class.getName());
assertThat(fileRequestHandler.serverBindings(),
contains("http:
}
@Test
public void default_root_handler_is_disabled_when_user_adds_a_handler_with_same_binding() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>" +
" <handler id='userRootHandler'>" +
" <binding>" + ContainerCluster.ROOT_HANDLER_BINDING + "</binding>" +
" </handler>" +
"</container>");
createModel(root, clusterElem);
ComponentsConfig.Components userRootHandler = getComponent(componentsConfig(), BindingsOverviewHandler.class.getName());
assertThat(userRootHandler, nullValue());
}
@Test
public void handler_bindings_are_included_in_discBindings_config() {
createClusterWithJDiscHandler();
String discBindingsConfig = root.getConfig(JdiscBindingsConfig.class, "default").toString();
assertThat(discBindingsConfig, containsString("{discHandler}"));
assertThat(discBindingsConfig, containsString(".serverBindings[0] \"binding0\""));
assertThat(discBindingsConfig, containsString(".serverBindings[1] \"binding1\""));
assertThat(discBindingsConfig, containsString(".clientBindings[0] \"clientBinding\""));
}
@Test
public void handlers_are_included_in_components_config() {
createClusterWithJDiscHandler();
assertThat(componentsConfig().toString(), containsString(".id \"discHandler\""));
}
private void createClusterWithJDiscHandler() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <handler id='discHandler'>",
" <binding>binding0</binding>",
" <binding>binding1</binding>",
" <clientBinding>clientBinding</clientBinding>",
" </handler>",
"</container>");
createModel(root, clusterElem);
}
@Test
public void servlets_are_included_in_ServletPathConfig() {
createClusterWithServlet();
ServletPathsConfig servletPathsConfig = root.getConfig(ServletPathsConfig.class, "default");
assertThat(servletPathsConfig.servlets().values().iterator().next().path(), is("p/a/t/h"));
}
@Test
public void servletconfig_is_produced() {
createClusterWithServlet();
String configId = getContainerCluster("default").getServletMap().
values().iterator().next().getConfigId();
ServletConfigConfig servletConfig = root.getConfig(ServletConfigConfig.class, configId);
assertThat(servletConfig.map().get("myKey"), is("myValue"));
}
private void createClusterWithServlet() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <servlet id='myServlet' class='myClass' bundle='myBundle'>",
" <path>p/a/t/h</path>",
" <servlet-config>",
" <myKey>myValue</myKey>",
" </servlet-config>",
" </servlet>",
"</container>");
createModel(root, clusterElem);
}
@Test
public void processing_handler_bindings_can_be_overridden() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <processing>",
" <binding>binding0</binding>",
" <binding>binding1</binding>",
" </processing>",
"</container>");
createModel(root, clusterElem);
String discBindingsConfig = root.getConfig(JdiscBindingsConfig.class, "default").toString();
assertThat(discBindingsConfig, containsString(".serverBindings[0] \"binding0\""));
assertThat(discBindingsConfig, containsString(".serverBindings[1] \"binding1\""));
assertThat(discBindingsConfig, not(containsString("/processing/*")));
}
@Test
public void clientProvider_bindings_are_included_in_discBindings_config() {
createModelWithClientProvider();
String discBindingsConfig = root.getConfig(JdiscBindingsConfig.class, "default").toString();
assertThat(discBindingsConfig, containsString("{discClient}"));
assertThat(discBindingsConfig, containsString(".clientBindings[0] \"binding0\""));
assertThat(discBindingsConfig, containsString(".clientBindings[1] \"binding1\""));
assertThat(discBindingsConfig, containsString(".serverBindings[0] \"serverBinding\""));
}
@Test
public void clientProviders_are_included_in_components_config() {
createModelWithClientProvider();
assertThat(componentsConfig().toString(), containsString(".id \"discClient\""));
}
private void createModelWithClientProvider() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>" +
" <client id='discClient'>" +
" <binding>binding0</binding>" +
" <binding>binding1</binding>" +
" <serverBinding>serverBinding</serverBinding>" +
" </client>" +
"</container>" );
createModel(root, clusterElem);
}
@Test
public void serverProviders_are_included_in_components_config() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>" +
" <server id='discServer' />" +
"</container>" );
createModel(root, clusterElem);
String componentsConfig = componentsConfig().toString();
assertThat(componentsConfig, containsString(".id \"discServer\""));
}
private String getChainsConfig(String configId) {
return root.getConfig(ChainsConfig.class, configId).toString();
}
@Test
public void searchHandler_gets_only_search_chains_in_chains_config() {
createClusterWithProcessingAndSearchChains();
String searchHandlerConfigId = "default/component/com.yahoo.search.handler.SearchHandler";
String chainsConfig = getChainsConfig(searchHandlerConfigId);
assertThat(chainsConfig, containsLineWithPattern(".*\\.id \"testSearcher@default\"$"));
assertThat(chainsConfig, not(containsLineWithPattern(".*\\.id \"testProcessor@default\"$")));
}
@Test
public void processingHandler_gets_only_processing_chains_in_chains_config() {
createClusterWithProcessingAndSearchChains();
String processingHandlerConfigId = "default/component/com.yahoo.processing.handler.ProcessingHandler";
String chainsConfig = getChainsConfig(processingHandlerConfigId);
assertThat(chainsConfig, containsLineWithPattern(".*\\.id \"testProcessor@default\"$"));
assertThat(chainsConfig, not(containsLineWithPattern(".*\\.id \"testSearcher@default\"$")));
}
private void createClusterWithProcessingAndSearchChains() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>" +
" <search>" +
" <chain id='default'>" +
" <searcher id='testSearcher' />" +
" </chain>" +
" </search>" +
" <processing>" +
" <chain id='default'>" +
" <processor id='testProcessor'/>" +
" </chain>" +
" </processing>" +
nodesXml +
" </container>");
createModel(root, clusterElem);
}
@Test
public void user_config_can_be_overridden_on_node() {
Element containerElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <config name=\"prelude.cluster.qr-monitor\">" +
" <requesttimeout>111</requesttimeout>",
" </config> " +
" <nodes>",
" <node hostalias='host1' />",
" <node hostalias='host2'>",
" <config name=\"prelude.cluster.qr-monitor\">",
" <requesttimeout>222</requesttimeout>",
" </config> ",
" </node>",
" </nodes>",
"</container>");
root = ContentClusterUtils.createMockRoot(new String[]{"host1", "host2"});
createModel(root, containerElem);
ContainerCluster cluster = (ContainerCluster)root.getChildren().get("default");
assertThat(cluster.getContainers().size(), is(2));
assertEquals(root.getConfig(QrMonitorConfig.class, "default/container.0").requesttimeout(), 111);
assertEquals(root.getConfig(QrMonitorConfig.class, "default/container.1").requesttimeout(), 222);
}
@Test
public void nested_components_are_injected_to_handlers() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <handler id='myHandler'>",
" <component id='injected' />",
" </handler>",
" <client id='myClient'>",
" <component id='injected' />",
" </client>",
"</container>");
createModel(root, clusterElem);
Component<?,?> handler = getContainerComponent("default", "myHandler");
assertThat(handler.getInjectedComponentIds(), hasItem("injected@myHandler"));
Component<?,?> client = getContainerComponent("default", "myClient");
assertThat(client.getInjectedComponentIds(), hasItem("injected@myClient"));
}
@Test
public void component_includes_are_added() {
VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/application/include_dirs");
VespaModel model = creator.create(true);
ContainerCluster cluster = model.getContainerClusters().get("default");
Map<ComponentId, Component<?, ?>> componentsMap = cluster.getComponentsMap();
Component<?,?> example = componentsMap.get(
ComponentId.fromString("test.Exampledocproc"));
assertThat(example.getComponentId().getName(), is("test.Exampledocproc"));
}
@Test
public void affinity_is_set() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <http>",
" <server port='" + getDefaults().vespaWebServicePort() + "' id='main' />",
" </http>",
" <nodes cpu-socket-affinity='true'>",
" <node hostalias='node1' />",
" </nodes>" +
"</container>");
createModel(root, clusterElem);
assertTrue(getContainerCluster("default").getContainers().get(0).getAffinity().isPresent());
assertThat(getContainerCluster("default").getContainers().get(0).getAffinity().get().cpuSocket(), is(0));
}
@Test
public void singlenode_servicespec_is_used_with_hosts_xml() throws IOException, SAXException {
String servicesXml = "<container id='default' version='1.0' />";
String hostsXml = "<hosts>\n" +
" <host name=\"test1.yahoo.com\">\n" +
" <alias>node1</alias>\n" +
" </host>\n" +
"</hosts>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder()
.withHosts(hostsXml)
.withServices(servicesXml)
.build();
VespaModel model = new VespaModel(applicationPackage);
assertThat(model.getHostSystem().getHosts().size(), is(1));
}
@Test
public void http_aliases_are_stored_on_cluster_and_on_service_properties() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <aliases>",
" <service-alias>service1</service-alias>",
" <service-alias>service2</service-alias>",
" <endpoint-alias>foo1.bar1.com</endpoint-alias>",
" <endpoint-alias>foo2.bar2.com</endpoint-alias>",
" </aliases>",
" <nodes>",
" <node hostalias='host1' />",
" </nodes>",
"</container>");
createModel(root, clusterElem);
assertEquals(getContainerCluster("default").serviceAliases().get(0), "service1");
assertEquals(getContainerCluster("default").endpointAliases().get(0), "foo1.bar1.com");
assertEquals(getContainerCluster("default").serviceAliases().get(1), "service2");
assertEquals(getContainerCluster("default").endpointAliases().get(1), "foo2.bar2.com");
assertEquals(getContainerCluster("default").getContainers().get(0).getServicePropertyString("servicealiases"), "service1,service2");
assertEquals(getContainerCluster("default").getContainers().get(0).getServicePropertyString("endpointaliases"), "foo1.bar1.com,foo2.bar2.com");
}
@Test
public void http_aliases_are_only_honored_in_prod_environment() {
Element clusterElem = DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <aliases>",
" <service-alias>service1</service-alias>",
" <endpoint-alias>foo1.bar1.com</endpoint-alias>",
" </aliases>",
" <nodes>",
" <node hostalias='host1' />",
" </nodes>",
"</container>");
DeployState deployState = new DeployState.Builder().zone(new Zone(Environment.dev, RegionName.from("us-east-1"))).build();
createModel(root, deployState, null, clusterElem);
assertEquals(0, getContainerCluster("default").serviceAliases().size());
assertEquals(0, getContainerCluster("default").endpointAliases().size());
assertNull(getContainerCluster("default").getContainers().get(0).getServicePropertyString("servicealiases"));
assertNull(getContainerCluster("default").getContainers().get(0).getServicePropertyString("endpointaliases"));
}
@Test
public void endpoints_are_added_to_containers() throws IOException, SAXException {
final var servicesXml = joinLines("",
"<container id='comics-search' version='1.0'>",
" <nodes>",
" <node hostalias='host1' />",
" </nodes>",
"</container>"
);
final var deploymentXml = joinLines("",
"<deployment version='1.0'>",
" <prod />",
"</deployment>"
);
final var applicationPackage = new MockApplicationPackage.Builder()
.withServices(servicesXml)
.withDeploymentSpec(deploymentXml)
.build();
final var deployState = new DeployState.Builder()
.applicationPackage(applicationPackage)
.zone(new Zone(Environment.prod, RegionName.from("us-east-1")))
.endpoints(Set.of(new ContainerEndpoint("comics-search", List.of("nalle", "balle"))))
.properties(new TestProperties().setHostedVespa(true))
.build();
final var model = new VespaModel(new NullConfigModelRegistry(), deployState);
final var containers = model.getContainerClusters().values().stream()
.flatMap(cluster -> cluster.getContainers().stream())
.collect(Collectors.toList());
assertFalse("Missing container objects based on configuration", containers.isEmpty());
containers.forEach(container -> {
final var rotations = container.getServicePropertyString("rotations").split(",");
final var rotationsSet = Set.of(rotations);
assertEquals(Set.of("balle", "nalle"), rotationsSet);
});
}
@Test
public void singlenode_servicespec_is_used_with_hosted_vespa() throws IOException, SAXException {
String servicesXml = "<container id='default' version='1.0' />";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.modelHostProvisioner(new InMemoryProvisioner(true, "host1.yahoo.com", "host2.yahoo.com"))
.applicationPackage(applicationPackage)
.properties(new TestProperties()
.setMultitenant(true)
.setHostedVespa(true))
.build());
assertEquals(1, model.getHostSystem().getHosts().size());
}
@Test(expected = IllegalArgumentException.class)
public void renderers_named_JsonRenderer_are_not_allowed() {
createModel(root, generateContainerElementWithRenderer("JsonRenderer"));
}
@Test(expected = IllegalArgumentException.class)
public void renderers_named_DefaultRenderer_are_not_allowed() {
createModel(root, generateContainerElementWithRenderer("XmlRenderer"));
}
@Test
public void renderers_named_something_else_are_allowed() {
createModel(root, generateContainerElementWithRenderer("my-little-renderer"));
}
@Test
public void vip_status_handler_uses_file_for_hosted_vespa() throws Exception {
String servicesXml = "<services>" +
"<container version='1.0'>" +
nodesXml +
"</container>" +
"</services>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(applicationPackage)
.properties(new TestProperties().setHostedVespa(true))
.build());
AbstractConfigProducerRoot modelRoot = model.getRoot();
VipStatusConfig vipStatusConfig = modelRoot.getConfig(VipStatusConfig.class, "container/component/status.html-status-handler");
assertTrue(vipStatusConfig.accessdisk());
assertEquals(ContainerModelBuilder.HOSTED_VESPA_STATUS_FILE, vipStatusConfig.statusfile());
}
@Test
public void qrconfig_is_produced() throws IOException, SAXException {
String servicesXml =
"<services>" +
"<admin version='3.0'>" +
" <nodes count='1'/>" +
"</admin>" +
"<container id ='default' version='1.0'>" +
" <nodes>" +
" <node hostalias='node1' />" +
" </nodes>" +
"</container>" +
"</services>";
ApplicationPackage applicationPackage = new MockApplicationPackage.Builder()
.withServices(servicesXml)
.build();
VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder()
.applicationPackage(applicationPackage)
.properties(new TestProperties())
.build());
String hostname = HostName.getLocalhost();
QrConfig config = model.getConfig(QrConfig.class, "default/container.0");
assertEquals("default.container.0", config.discriminator());
assertEquals(19102, config.rpc().port());
assertEquals("vespa/service/default/container.0", config.rpc().slobrokId());
assertTrue(config.rpc().enabled());
assertEquals("", config.rpc().host());
assertFalse(config.restartOnDeploy());
assertEquals("filedistribution/" + hostname, config.filedistributor().configid());
}
@Test
public void secret_store_can_be_set_up() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <secret-store>",
" <group name='group1' environment='env1'/>",
" </secret-store>",
"</container>");
createModel(root, clusterElem);
SecretStore secretStore = getContainerCluster("container").getSecretStore().get();
assertEquals("group1", secretStore.getGroups().get(0).name);
assertEquals("env1", secretStore.getGroups().get(0).environment);
}
@Test
@Test
public void security_clients_pem_is_picked_up() {
var applicationPackage = new MockApplicationPackage.Builder()
.withRoot(applicationFolder.getRoot())
.build();
applicationPackage.getFile(Path.fromString("security")).createDirectory();
applicationPackage.getFile(Path.fromString("security/clients.pem")).writeFile(new StringReader("I am a very nice certificate"));
var deployState = DeployState.createTestState(applicationPackage);
Element clusterElem = DomBuilderTest.parse("<container version='1.0' />");
createModel(root, deployState, null, clusterElem);
assertEquals(Optional.of("I am a very nice certificate"), getContainerCluster("container").getTlsClientAuthority());
}
@Test
public void environment_vars_are_honoured() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <nodes>",
" <environment-variables>",
" <KMP_SETTING>1</KMP_SETTING>",
" <KMP_AFFINITY>granularity=fine,verbose,compact,1,0</KMP_AFFINITY>",
" </environment-variables>",
" <node hostalias='mockhost'/>",
" </nodes>",
"</container>" );
createModel(root, clusterElem);
QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder();
root.getConfig(qrStartBuilder, "container/container.0");
QrStartConfig qrStartConfig = new QrStartConfig(qrStartBuilder);
assertEquals("KMP_SETTING=1 KMP_AFFINITY=granularity=fine,verbose,compact,1,0 ", qrStartConfig.qrs().env());
}
private void verifyAvailableprocessors(boolean isHosted, Flavor flavor, int expectProcessors) throws IOException, SAXException {
DeployState deployState = new DeployState.Builder()
.modelHostProvisioner(flavor != null ? new SingleNodeProvisioner(flavor) : new SingleNodeProvisioner())
.properties(new TestProperties()
.setMultitenant(isHosted)
.setHostedVespa(isHosted))
.build();
MockRoot myRoot = new MockRoot("root", deployState);
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
" <nodes>",
" <node hostalias='localhost'/>",
" </nodes>",
"</container>"
);
createModel(myRoot, clusterElem);
QrStartConfig.Builder qsB = new QrStartConfig.Builder();
myRoot.getConfig(qsB, "container/container.0");
QrStartConfig qsC= new QrStartConfig(qsB);
assertEquals(expectProcessors, qsC.jvm().availableProcessors());
}
@Test
public void requireThatAvailableProcessorsFollowFlavor() throws IOException, SAXException {
verifyAvailableprocessors(false, null,0);
verifyAvailableprocessors(true, null,0);
verifyAvailableprocessors(true, new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build()), 9);
verifyAvailableprocessors(true, new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(1).build()), 2);
}
@Test
public void requireThatProvidingTlsSecretOpensPort4443() {
Element clusterElem = DomBuilderTest.parse(
"<container version='1.0'>",
nodesXml,
"</container>" );
DeployState state = new DeployState.Builder().properties(new TestProperties().setHostedVespa(true).setTlsSecrets(Optional.of(new TlsSecrets("CERT", "KEY")))).build();
createModel(root, state, null, clusterElem);
ApplicationContainer container = (ApplicationContainer)root.getProducer("container/container.0");
List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().getConnectorFactories();
assertEquals(2, connectorFactories.size());
List<Integer> ports = connectorFactories.stream()
.map(ConnectorFactory::getListenPort)
.collect(Collectors.toList());
assertThat(ports, Matchers.containsInAnyOrder(8080, 4443));
ConnectorFactory tlsPort = connectorFactories.stream().filter(connectorFactory -> connectorFactory.getListenPort() == 4443).findFirst().orElseThrow();
ConnectorConfig.Builder builder = new ConnectorConfig.Builder();
tlsPort.getConfig(builder);
ConnectorConfig connectorConfig = new ConnectorConfig(builder);
assertTrue(connectorConfig.ssl().enabled());
assertEquals("CERT", connectorConfig.ssl().certificate());
assertEquals("KEY", connectorConfig.ssl().privateKey());
assertEquals(4443, connectorConfig.listenPort());
}
private Element generateContainerElementWithRenderer(String rendererId) {
return DomBuilderTest.parse(
"<container id='default' version='1.0'>",
" <search>",
String.format(" <renderer id='%s'/>", rendererId),
" </search>",
"</container>");
}
} |
Isn't retrying handled by the `ConfigServer` implementation? | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | return retrying(10, () -> { | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} |
Not for, e.g., `APPLICATION_LOCK_TIMEOUT`, which frequently happens for certain applications. | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | return retrying(10, () -> { | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} |
Ok, then add that case? `ConfigServerClient` is the place we have put other retrying logic. | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | return retrying(10, () -> { | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} |
I want to handle deactivation retries here to avoid letting the client hold the controller's application lock for a very long time. If it is retried here, other agents in the controller will get the application lock after at most 2 minutes — otherwise, they may have to wait for the duration of a deployment, which we have had some issues with before. Deployment retries are handled in this runner class, as well. | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | return retrying(10, () -> { | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} |
The deactivate implementation in the config server client only have retries over the three servers, as it needs to hit the correct one. There is no other retrying logic there, for that path. | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | return retrying(10, () -> { | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} |
I want to let the whole step (deleteTester, deleteApplication) fail and be retried, but that requires some additional data stored for the steps in the job machinery. This is preferable because it allows the job to retry on a different controller, during upgrade or failure scenarios. I will get to it later, when I implement the delay for production tests, I think. | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | return retrying(10, () -> { | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} |
(They initially retried until they succeeded, but sometimes the config server was just wrong, and refused to give an OK response, so the job would run for ever, and it was changed to be a single attempt instead.) | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | return retrying(10, () -> { | private Optional<RunStatus> deactivateReal(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating deployment of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.applications().deactivate(id.application(), id.type().zone(controller.system()));
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting application " + id.application(), e);
return Optional.of(error);
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} | class InternalStepRunner implements StepRunner {
private static final Logger logger = Logger.getLogger(InternalStepRunner.class.getName());
private static final NodeResources DEFAULT_TESTER_RESOURCES =
new NodeResources(1, 4, 50, 0.3, NodeResources.DiskSpeed.any);
private static final NodeResources DEFAULT_TESTER_RESOURCES_AWS =
new NodeResources(2, 8, 50, 0.3, NodeResources.DiskSpeed.any);
static final Duration endpointTimeout = Duration.ofMinutes(15);
static final Duration testerTimeout = Duration.ofMinutes(30);
static final Duration installationTimeout = Duration.ofMinutes(150);
static final Duration certificateTimeout = Duration.ofMinutes(300);
private final Controller controller;
private final TestConfigSerializer testConfigSerializer;
private final DeploymentFailureMails mails;
public InternalStepRunner(Controller controller) {
this.controller = controller;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
this.mails = new DeploymentFailureMails(controller.zoneRegistry());
}
@Override
public Optional<RunStatus> run(LockedStep step, RunId id) {
DualLogger logger = new DualLogger(id, step.get());
try {
switch (step.get()) {
case deployTester: return deployTester(id, logger);
case deployInitialReal: return deployInitialReal(id, logger);
case installInitialReal: return installInitialReal(id, logger);
case deployReal: return deployReal(id, logger);
case installTester: return installTester(id, logger);
case installReal: return installReal(id, logger);
case startTests: return startTests(id, logger);
case endTests: return endTests(id, logger);
case copyVespaLogs: return copyVespaLogs(id, logger);
case deactivateReal: return deactivateReal(id, logger);
case deactivateTester: return deactivateTester(id, logger);
case report: return report(id, logger);
default: throw new AssertionError("Unknown step '" + step + "'!");
}
}
catch (UncheckedIOException e) {
logger.logWithInternalException(INFO, "IO exception running " + id + ": " + Exceptions.toMessageString(e), e);
return Optional.empty();
}
catch (RuntimeException e) {
logger.log(WARNING, "Unexpected exception running " + id, e);
if (JobProfile.of(id.type()).alwaysRun().contains(step.get())) {
logger.log("Will keep trying, as this is a cleanup step.");
return Optional.empty();
}
return Optional.of(error);
}
}
private Optional<RunStatus> deployInitialReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " +
versions.sourcePlatform().orElse(versions.targetPlatform()) +
" and application version " +
versions.sourceApplication().orElse(versions.targetApplication()).id() + " ...");
return deployReal(id, true, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, DualLogger logger) {
Versions versions = controller.jobController().run(id).get().versions();
logger.log("Deploying platform version " + versions.targetPlatform() +
" and application version " + versions.targetApplication().id() + " ...");
return deployReal(id, false, versions, logger);
}
private Optional<RunStatus> deployReal(RunId id, boolean setTheStage, Versions versions, DualLogger logger) {
Optional<ApplicationPackage> applicationPackage = id.type().environment().isManuallyDeployed()
? Optional.of(new ApplicationPackage(controller.applications().applicationStore()
.getDev(id.application(), id.type().zone(controller.system()))))
: Optional.empty();
Optional<Version> vespaVersion = id.type().environment().isManuallyDeployed()
? Optional.of(versions.targetPlatform())
: Optional.empty();
return deploy(id.application(),
id.type(),
() -> controller.applications().deploy(id.application(),
id.type().zone(controller.system()),
applicationPackage,
new DeployOptions(false,
vespaVersion,
false,
setTheStage)),
logger);
}
private Optional<RunStatus> deployTester(RunId id, DualLogger logger) {
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Deploying the tester container on platform " + platform + " ...");
return deploy(id.tester().id(),
id.type(),
() -> controller.applications().deployTester(id.tester(),
testerPackage(id),
id.type().zone(controller.system()),
new DeployOptions(true,
Optional.of(platform),
false,
false)),
logger);
}
private Optional<RunStatus> deploy(ApplicationId id, JobType type, Supplier<ActivateResult> deployment, DualLogger logger) {
try {
PrepareResponse prepareResponse = deployment.get().prepareResponse();
if ( ! prepareResponse.configChangeActions.refeedActions.stream().allMatch(action -> action.allowed)) {
List<String> messages = new ArrayList<>();
messages.add("Deploy failed due to non-compatible changes that require re-feed.");
messages.add("Your options are:");
messages.add("1. Revert the incompatible changes.");
messages.add("2. If you think it is safe in your case, you can override this validation, see");
messages.add(" http:
messages.add("3. Deploy as a new application under a different name.");
messages.add("Illegal actions:");
prepareResponse.configChangeActions.refeedActions.stream()
.filter(action -> ! action.allowed)
.flatMap(action -> action.messages.stream())
.forEach(messages::add);
messages.add("Details:");
prepareResponse.log.stream()
.map(entry -> entry.message)
.forEach(messages::add);
logger.log(messages);
return Optional.of(deploymentFailed);
}
if (prepareResponse.configChangeActions.restartActions.isEmpty())
logger.log("No services requiring restart.");
else
prepareResponse.configChangeActions.restartActions.stream()
.flatMap(action -> action.services.stream())
.map(service -> service.hostName)
.sorted().distinct()
.map(Hostname::new)
.forEach(hostname -> {
controller.applications().restart(new DeploymentId(id, type.zone(controller.system())), Optional.of(hostname));
logger.log("Restarting services on host " + hostname.id() + ".");
});
logger.log("Deployment successful.");
if (prepareResponse.message != null)
logger.log(prepareResponse.message);
return Optional.of(running);
}
catch (ConfigServerException e) {
if ( e.getErrorCode() == ACTIVATION_CONFLICT
|| e.getErrorCode() == APPLICATION_LOCK_FAILURE
|| e.getErrorCode() == PARENT_HOST_NOT_READY
|| e.getErrorCode() == CERTIFICATE_NOT_READY
|| e.getErrorCode() == LOAD_BALANCER_NOT_READY) {
logger.log("Will retry, because of '" + e.getErrorCode() + "' deploying:\n" + e.getMessage());
return Optional.empty();
}
if ( e.getErrorCode() == INVALID_APPLICATION_PACKAGE
|| e.getErrorCode() == BAD_REQUEST
|| e.getErrorCode() == OUT_OF_CAPACITY) {
logger.log("Deployment failed: " + e.getMessage());
return Optional.of(e.getErrorCode() == OUT_OF_CAPACITY ? outOfCapacity : deploymentFailed);
}
throw e;
}
}
private Optional<RunStatus> installInitialReal(RunId id, DualLogger logger) {
return installReal(id, true, logger);
}
private Optional<RunStatus> installReal(RunId id, DualLogger logger) {
return installReal(id, false, logger);
}
private Optional<RunStatus> installReal(RunId id, boolean setTheStage, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(INFO, "Deployment expired before installation was successful.");
return Optional.of(installationFailed);
}
Versions versions = controller.jobController().run(id).get().versions();
Version platform = setTheStage ? versions.sourcePlatform().orElse(versions.targetPlatform()) : versions.targetPlatform();
ApplicationVersion application = setTheStage ? versions.sourceApplication().orElse(versions.targetApplication()) : versions.targetApplication();
logger.log("Checking installation of " + platform + " and " + application.id() + " ...");
if ( nodesConverged(id.application(), id.type(), platform, logger)
&& servicesConverged(id.application(), id.type(), platform, logger)) {
if (endpointsAvailable(id.application(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.application(), id.type().zone(controller.system()), logger)) {
logger.log("Installation succeeded!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), installationTimeout)) {
logger.log(INFO, "Installation failed to complete within " + installationTimeout.toMinutes() + " minutes!");
return Optional.of(installationFailed);
}
logger.log("Installation not yet complete.");
return Optional.empty();
}
private Optional<RunStatus> installTester(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if ( ! deployment.isPresent()) {
logger.log(WARNING, "Deployment expired before installation of tester was successful.");
return Optional.of(error);
}
Version platform = controller.jobController().run(id).get().versions().targetPlatform();
logger.log("Checking installation of tester container ...");
if ( nodesConverged(id.tester().id(), id.type(), platform, logger)
&& servicesConverged(id.tester().id(), id.type(), platform, logger)) {
if (endpointsAvailable(id.tester().id(), id.type().zone(controller.system()), logger)) {
if (containersAreUp(id.tester().id(), id.type().zone(controller.system()), logger)) {
logger.log("Tester container successfully installed!");
return Optional.of(running);
}
}
else if (timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Tester failed to show up within " + endpointTimeout.toMinutes() + " minutes!");
return Optional.of(error);
}
}
if (timedOut(id, deployment.get(), testerTimeout)) {
logger.log(WARNING, "Installation of tester failed to complete within " + testerTimeout.toMinutes() + " minutes of real deployment!");
return Optional.of(error);
}
logger.log("Installation of tester not yet complete.");
return Optional.empty();
}
/** Returns true iff all containers in the deployment give 100 consecutive 200 OK responses on /status.html. */
private boolean containersAreUp(ApplicationId id, ZoneId zoneId, DualLogger logger) {
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zoneId)));
if ( ! endpoints.containsKey(zoneId))
return false;
for (URI endpoint : endpoints.get(zoneId).values()) {
boolean ready = id.instance().isTester() ?
controller.jobController().cloud().testerReady(endpoint)
: controller.jobController().cloud().ready(endpoint);
if (!ready) {
logger.log("Failed to get 100 consecutive OKs from " + endpoint);
return false;
}
}
return true;
}
private boolean endpointsAvailable(ApplicationId id, ZoneId zone, DualLogger logger) {
logger.log("Attempting to find deployment endpoints ...");
var endpoints = controller.applications().clusterEndpoints(Set.of(new DeploymentId(id, zone)));
if ( ! endpoints.containsKey(zone)) {
logger.log("Endpoints not yet ready.");
return false;
}
for (var endpoint : endpoints.get(zone).values())
if ( ! controller.jobController().cloud().exists(endpoint)) {
logger.log(INFO, "DNS lookup yielded no IP address for '" + endpoint + "'.");
return false;
}
logEndpoints(endpoints, logger);
return true;
}
private void logEndpoints(Map<ZoneId, Map<ClusterSpec.Id, URI>> endpoints, DualLogger logger) {
List<String> messages = new ArrayList<>();
messages.add("Found endpoints:");
endpoints.forEach((zone, uris) -> {
messages.add("- " + zone);
uris.forEach((cluster, uri) -> messages.add(" |-- " + uri + " (" + cluster + ")"));
});
logger.log(messages);
}
private boolean nodesConverged(ApplicationId id, JobType type, Version target, DualLogger logger) {
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(type.zone(controller.system()), id, ImmutableSet.of(active, reserved));
List<String> statuses = nodes.stream()
.map(node -> String.format("%70s: %-16s%-25s%-32s%s",
node.hostname(),
node.serviceState(),
node.wantedVersion() + (node.currentVersion().equals(node.wantedVersion()) ? "" : " <-- " + node.currentVersion()),
node.restartGeneration() >= node.wantedRestartGeneration() ? ""
: "restart pending (" + node.wantedRestartGeneration() + " <-- " + node.restartGeneration() + ")",
node.rebootGeneration() >= node.wantedRebootGeneration() ? ""
: "reboot pending (" + node.wantedRebootGeneration() + " <-- " + node.rebootGeneration() + ")"))
.collect(Collectors.toList());
logger.log(statuses);
return nodes.stream().allMatch(node -> node.currentVersion().equals(target)
&& node.restartGeneration() >= node.wantedRestartGeneration()
&& node.rebootGeneration() >= node.wantedRebootGeneration());
}
private boolean servicesConverged(ApplicationId id, JobType type, Version platform, DualLogger logger) {
var convergence = controller.serviceRegistry().configServer().serviceConvergence(new DeploymentId(id, type.zone(controller.system())),
Optional.of(platform));
if (convergence.isEmpty()) {
logger.log("Config status not currently available -- will retry.");
return false;
}
logger.log("Wanted config generation is " + convergence.get().wantedGeneration());
List<String> statuses = convergence.get().services().stream()
.filter(serviceStatus -> serviceStatus.currentGeneration() != convergence.get().wantedGeneration())
.map(serviceStatus -> String.format("%70s: %11s on port %4d has config generation %s",
serviceStatus.host().value(),
serviceStatus.type(),
serviceStatus.port(),
serviceStatus.currentGeneration() == -1 ? "not started!" : Long.toString(serviceStatus.currentGeneration())))
.collect(Collectors.toList());
logger.log(statuses);
if (statuses.isEmpty())
logger.log("All services on wanted config generation.");
return convergence.get().converged();
}
private Optional<RunStatus> startTests(RunId id, DualLogger logger) {
Optional<Deployment> deployment = deployment(id.application(), id.type());
if (deployment.isEmpty()) {
logger.log(INFO, "Deployment expired before tests could start.");
return Optional.of(aborted);
}
var deployments = controller.applications().requireInstance(id.application())
.productionDeployments().keySet().stream()
.map(zone -> new DeploymentId(id.application(), zone))
.collect(Collectors.toSet());
deployments.add(new DeploymentId(id.application(), id.type().zone(controller.system())));
logger.log("Attempting to find endpoints ...");
var endpoints = controller.applications().clusterEndpoints(deployments);
if ( ! endpoints.containsKey(id.type().zone(controller.system())) && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the deployment to test vanished again, while it was still active!");
return Optional.of(error);
}
logEndpoints(endpoints, logger);
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if (testerEndpoint.isEmpty() && timedOut(id, deployment.get(), endpointTimeout)) {
logger.log(WARNING, "Endpoints for the tester container vanished again, while it was still active!");
return Optional.of(error);
}
if ( ! controller.jobController().cloud().testerReady(testerEndpoint.get())) {
logger.log(WARNING, "Tester container went bad!");
return Optional.of(error);
}
logger.log("Starting tests ...");
controller.jobController().cloud().startTests(testerEndpoint.get(),
TesterCloud.Suite.of(id.type()),
testConfigSerializer.configJson(id.application(),
id.type(),
true,
endpoints,
controller.applications().contentClustersByZone(deployments)));
return Optional.of(running);
}
private Optional<RunStatus> endTests(RunId id, DualLogger logger) {
if ( ! deployment(id.application(), id.type()).isPresent()) {
logger.log(INFO, "Deployment expired before tests could complete.");
return Optional.of(aborted);
}
Optional<X509Certificate> testerCertificate = controller.jobController().run(id).get().testerCertificate();
if (testerCertificate.isPresent()) {
try {
testerCertificate.get().checkValidity(Date.from(controller.clock().instant()));
}
catch (CertificateExpiredException | CertificateNotYetValidException e) {
logger.log(INFO, "Tester certificate expired before tests could complete.");
return Optional.of(aborted);
}
}
Optional<URI> testerEndpoint = controller.jobController().testerEndpoint(id);
if ( ! testerEndpoint.isPresent()) {
logger.log("Endpoints for tester not found -- trying again later.");
return Optional.empty();
}
controller.jobController().updateTestLog(id);
TesterCloud.Status testStatus = controller.jobController().cloud().getStatus(testerEndpoint.get());
switch (testStatus) {
case NOT_STARTED:
throw new IllegalStateException("Tester reports tests not started, even though they should have!");
case RUNNING:
return Optional.empty();
case FAILURE:
logger.log("Tests failed.");
return Optional.of(testFailure);
case ERROR:
logger.log(INFO, "Tester failed running its tests!");
return Optional.of(error);
case SUCCESS:
logger.log("Tests completed successfully.");
return Optional.of(running);
default:
throw new IllegalStateException("Unknown status '" + testStatus + "'!");
}
}
private Optional<RunStatus> copyVespaLogs(RunId id, DualLogger logger) {
if (deployment(id.application(), id.type()).isPresent())
try {
controller.jobController().updateVespaLog(id);
}
catch (Exception e) {
logger.log(INFO, "Failure getting vespa logs for " + id, e);
return Optional.of(error);
}
return Optional.of(running);
}
private Optional<RunStatus> deactivateTester(RunId id, DualLogger logger) {
try {
return retrying(10, () -> {
logger.log("Deactivating tester of " + id.application() + " in " + id.type().zone(controller.system()) + " ...");
controller.jobController().deactivateTester(id.tester(), id.type());
return running;
});
}
catch (RuntimeException e) {
logger.log(WARNING, "Failed deleting tester of " + id.application(), e);
return Optional.of(error);
}
}
private static Optional<RunStatus> retrying(int retries, Supplier<RunStatus> task) {
RuntimeException exception = null;
do {
try {
return Optional.of(task.get());
}
catch (RuntimeException e) {
if (exception == null)
exception = e;
else
exception.addSuppressed(e);
}
} while (--retries >= 0);
throw exception;
}
private Optional<RunStatus> report(RunId id, DualLogger logger) {
try {
controller.jobController().active(id).ifPresent(run -> {
if (run.hasFailed())
sendNotification(run, logger);
});
}
catch (IllegalStateException e) {
logger.log(INFO, "Job '" + id.type() + "' no longer supposed to run?", e);
return Optional.of(error);
}
return Optional.of(running);
}
/** Sends a mail with a notification of a failed run, if one should be sent. */
private void sendNotification(Run run, DualLogger logger) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(run.id().application()));
Notifications notifications = application.deploymentSpec().requireInstance(run.id().application().instance()).notifications();
boolean newCommit = application.change().application()
.map(run.versions().targetApplication()::equals)
.orElse(false);
When when = newCommit ? failingCommit : failing;
List<String> recipients = new ArrayList<>(notifications.emailAddressesFor(when));
if (notifications.emailRolesFor(when).contains(author))
run.versions().targetApplication().authorEmail().ifPresent(recipients::add);
if (recipients.isEmpty())
return;
try {
if (run.status() == outOfCapacity && run.id().type().isProduction())
controller.serviceRegistry().mailer().send(mails.outOfCapacity(run.id(), recipients));
if (run.status() == deploymentFailed)
controller.serviceRegistry().mailer().send(mails.deploymentFailure(run.id(), recipients));
if (run.status() == installationFailed)
controller.serviceRegistry().mailer().send(mails.installationFailure(run.id(), recipients));
if (run.status() == testFailure)
controller.serviceRegistry().mailer().send(mails.testFailure(run.id(), recipients));
if (run.status() == error)
controller.serviceRegistry().mailer().send(mails.systemError(run.id(), recipients));
}
catch (RuntimeException e) {
logger.log(INFO, "Exception trying to send mail for " + run.id(), e);
}
}
/** Returns the deployment of the real application in the zone of the given job, if it exists. */
private Optional<Deployment> deployment(ApplicationId id, JobType type) {
return Optional.ofNullable(application(id).deployments().get(type.zone(controller.system())));
}
/** Returns the real application with the given id. */
private Instance application(ApplicationId id) {
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), __ -> { });
return controller.applications().requireInstance(id);
}
/**
* Returns whether the time since deployment is more than the zone deployment expiry, or the given timeout.
*
* We time out the job before the deployment expires, for zone where deployments are not persistent,
* to be able to collect the Vespa log from the deployment. Thus, the lower of the zone's deployment expiry,
* and the given default installation timeout, minus one minute, is used as a timeout threshold.
*/
private boolean timedOut(RunId id, Deployment deployment, Duration defaultTimeout) {
Run run = controller.jobController().run(id).get();
if (run.start().isAfter(deployment.at()))
return false;
Duration timeout = controller.zoneRegistry().getDeploymentTimeToLive(deployment.zone())
.filter(zoneTimeout -> zoneTimeout.compareTo(defaultTimeout) < 0)
.orElse(defaultTimeout);
return deployment.at().isBefore(controller.clock().instant().minus(timeout.minus(Duration.ofMinutes(1))));
}
/** Returns the application package for the tester application, assembled from a generated config, fat-jar and services.xml. */
private ApplicationPackage testerPackage(RunId id) {
ApplicationVersion version = controller.jobController().run(id).get().versions().targetApplication();
DeploymentSpec spec = controller.applications().requireApplication(TenantAndApplicationId.from(id.application())).deploymentSpec();
ZoneId zone = id.type().zone(controller.system());
boolean useTesterCertificate = controller.system().isPublic() && id.type().isTest();
byte[] servicesXml = servicesXml(controller.zoneRegistry().accessControlDomain(),
! controller.system().isPublic(),
useTesterCertificate,
testerFlavorFor(id, spec)
.map(NodeResources::fromLegacyName)
.orElse(zone.region().value().contains("aws-") ?
DEFAULT_TESTER_RESOURCES_AWS : DEFAULT_TESTER_RESOURCES));
byte[] testPackage = controller.applications().applicationStore().getTester(id.application().tenant(), id.application().application(), version);
byte[] deploymentXml = deploymentXml(id.tester(),
spec.requireInstance(id.application().instance()).athenzDomain(),
spec.requireInstance(id.application().instance()).athenzService(zone.environment(), zone.region()));
try (ZipBuilder zipBuilder = new ZipBuilder(testPackage.length + servicesXml.length + 1000)) {
zipBuilder.add(testPackage);
zipBuilder.add("services.xml", servicesXml);
zipBuilder.add("deployment.xml", deploymentXml);
if (useTesterCertificate)
appendAndStoreCertificate(zipBuilder, id);
zipBuilder.close();
return new ApplicationPackage(zipBuilder.toByteArray());
}
}
private void appendAndStoreCertificate(ZipBuilder zipBuilder, RunId id) {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 2048);
X500Principal subject = new X500Principal("CN=" + id.tester().id().toFullString() + "." + id.type() + "." + id.number());
X509Certificate certificate = X509CertificateBuilder.fromKeypair(keyPair,
subject,
controller.clock().instant(),
controller.clock().instant().plus(certificateTimeout),
SignatureAlgorithm.SHA512_WITH_RSA,
BigInteger.valueOf(1))
.build();
controller.jobController().storeTesterCertificate(id, certificate);
zipBuilder.add("artifacts/key", KeyUtils.toPem(keyPair.getPrivate()).getBytes(UTF_8));
zipBuilder.add("artifacts/cert", X509CertificateUtils.toPem(certificate).getBytes(UTF_8));
}
private static Optional<String> testerFlavorFor(RunId id, DeploymentSpec spec) {
for (DeploymentSpec.Step step : spec.steps())
if (step.deploysTo(id.type().environment()))
return step.zones().get(0).testerFlavor();
throw new IllegalStateException("No step deploys to the zone this run is for!");
}
/** Returns the generated services.xml content for the tester application. */
static byte[] servicesXml(AthenzDomain domain, boolean useAthenzCredentials, boolean useTesterCertificate,
NodeResources resources) {
int jdiscMemoryGb = 2;
int jdiscMemoryPct = (int) Math.ceil(100 * jdiscMemoryGb / resources.memoryGb());
int testMemoryMb = (int) (1024 * (resources.memoryGb() - jdiscMemoryGb) / 2);
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name());
/* TODO after 18 November 2019, include storageType:
String resourceString = String.format(Locale.ENGLISH,
"<resources vcpu=\"%.2f\" memory=\"%.2fGb\" disk=\"%.2fGb\" disk-speed=\"%s\" storage-type=\"%s\"/>",
resources.vcpu(), resources.memoryGb(), resources.diskGb(), resources.diskSpeed().name(), resources.storageType().name());
*/
AthenzDomain idDomain = ("vespa.vespa.cd".equals(domain.value()) ? AthenzDomain.from("vespa.vespa") : domain);
String servicesXml =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<services xmlns:deploy='vespa' version='1.0'>\n" +
" <container version='1.0' id='tester'>\n" +
"\n" +
" <component id=\"com.yahoo.vespa.hosted.testrunner.TestRunner\" bundle=\"vespa-testrunner-components\">\n" +
" <config name=\"com.yahoo.vespa.hosted.testrunner.test-runner\">\n" +
" <artifactsPath>artifacts</artifactsPath>\n" +
" <surefireMemoryMb>" + testMemoryMb + "</surefireMemoryMb>\n" +
" <useAthenzCredentials>" + useAthenzCredentials + "</useAthenzCredentials>\n" +
" <useTesterCertificate>" + useTesterCertificate + "</useTesterCertificate>\n" +
" </config>\n" +
" </component>\n" +
"\n" +
" <handler id=\"com.yahoo.vespa.hosted.testrunner.TestRunnerHandler\" bundle=\"vespa-testrunner-components\">\n" +
" <binding>http:
" </handler>\n" +
"\n" +
" <http>\n" +
" <!-- Make sure 4080 is the first port. This will be used by the config server. -->\n" +
" <server id='default' port='4080'/>\n" +
" <server id='testertls4443' port='4443'>\n" +
" <config name=\"jdisc.http.connector\">\n" +
" <tlsClientAuthEnforcer>\n" +
" <enable>true</enable>\n" +
" <pathWhitelist>\n" +
" <item>/status.html</item>\n" +
" <item>/state/v1/config</item>\n" +
" </pathWhitelist>\n" +
" </tlsClientAuthEnforcer>\n" +
" </config>\n" +
" <ssl>\n" +
" <private-key-file>/var/lib/sia/keys/" + idDomain.value() + ".tenant.key.pem</private-key-file>\n" +
" <certificate-file>/var/lib/sia/certs/" + idDomain.value() + ".tenant.cert.pem</certificate-file>\n" +
" <ca-certificates-file>/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem</ca-certificates-file>\n" +
" <client-authentication>want</client-authentication>\n" +
" </ssl>\n" +
" </server>\n" +
" <filtering>\n" +
" <access-control domain='" + domain.value() + "'>\n" +
" <exclude>\n" +
" <binding>http:
" </exclude>\n" +
" </access-control>\n" +
" <request-chain id=\"testrunner-api\">\n" +
" <filter id='authz-filter' class='com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFilter' bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.athenz-authorization-filter\">\n" +
" <credentialsToVerify>TOKEN_ONLY</credentialsToVerify>\n" +
" <roleTokenHeaderName>Yahoo-Role-Auth</roleTokenHeaderName>\n" +
" </config>\n" +
" <component id=\"com.yahoo.jdisc.http.filter.security.athenz.StaticRequestResourceMapper\" bundle=\"jdisc-security-filters\">\n" +
" <config name=\"jdisc.http.filter.security.athenz.static-request-resource-mapper\">\n" +
" <resourceName>" + domain.value() + ":tester-application</resourceName>\n" +
" <action>deploy</action>\n" +
" </config>\n" +
" </component>\n" +
" </filter>\n" +
" </request-chain>\n" +
" </filtering>\n" +
" </http>\n" +
"\n" +
" <nodes count=\"1\" allocated-memory=\"" + jdiscMemoryPct + "%\">\n" +
" " + resourceString + "\n" +
" </nodes>\n" +
" </container>\n" +
"</services>\n";
return servicesXml.getBytes(UTF_8);
}
/** Returns a dummy deployment xml which sets up the service identity for the tester, if present. */
private static byte[] deploymentXml(TesterId id, Optional<AthenzDomain> athenzDomain, Optional<AthenzService> athenzService) {
String deploymentSpec =
"<?xml version='1.0' encoding='UTF-8'?>\n" +
"<deployment version=\"1.0\" " +
athenzDomain.map(domain -> "athenz-domain=\"" + domain.value() + "\" ").orElse("") +
athenzService.map(service -> "athenz-service=\"" + service.value() + "\" ").orElse("") + ">" +
" <instance id=\"" + id.id().instance().value() + "\" />" +
"</deployment>";
return deploymentSpec.getBytes(UTF_8);
}
/** Logger which logs to a {@link JobController}, as well as to the parent class' {@link Logger}. */
private class DualLogger {
private final RunId id;
private final Step step;
private DualLogger(RunId id, Step step) {
this.id = id;
this.step = step;
}
private void log(String... messages) {
log(List.of(messages));
}
private void log(List<String> messages) {
controller.jobController().log(id, step, INFO, messages);
}
private void log(Level level, String message) {
log(level, message, null);
}
private void logWithInternalException(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
controller.jobController().log(id, step, level, message);
}
private void log(Level level, String message, Throwable thrown) {
logger.log(level, id + " at " + step + ": " + message, thrown);
if (thrown != null) {
ByteArrayOutputStream traceBuffer = new ByteArrayOutputStream();
thrown.printStackTrace(new PrintStream(traceBuffer));
message += "\n" + traceBuffer;
}
controller.jobController().log(id, step, level, message);
}
}
} |
If they are equal, we should return `false` or at least make sure not to "undo" this in `finally` if we fail to achieve the wanted result. | private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() != wantToRetire)
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
} | if (node.status().wantToRetire() != wantToRetire) | private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetired = markWantToRetire(move.node, true);
if ( ! couldMarkRetired) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
}
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/** Returns true only if this operation changes the state of the wantToRetire flag */
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(move.node, true);
if ( ! couldMarkRetiredNow) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
}
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} |
If it's already set to want to retire it's fine that we do it. However, as you point out it is not fine to undo it if somebody else sets it and we failed (regardless of when it happens). PTAL - I'm going to run out of "try" clauses soon. | private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() != wantToRetire)
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
} | if (node.status().wantToRetire() != wantToRetire) | private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetired = markWantToRetire(move.node, true);
if ( ! couldMarkRetired) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
}
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/** Returns true only if this operation changes the state of the wantToRetire flag */
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(move.node, true);
if ( ! couldMarkRetiredNow) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
}
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} |
PTAL | private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() != wantToRetire)
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
} | if (node.status().wantToRetire() != wantToRetire) | private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetired = markWantToRetire(move.node, true);
if ( ! couldMarkRetired) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
}
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/** Returns true only if this operation changes the state of the wantToRetire flag */
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(move.node, true);
if ( ! couldMarkRetiredNow) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
}
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} |
This leaves the reserved node with the application for 20-27 mins (until it is expired by `ReservationExpirer`), this is especially unfortunate in CD when we want to fail integration tests when some node are stuck in a non-active state. We should prepare the application again with the node unmarked as wantToRetire or move it directly to dirty if that is safe. FYI: @hmusum | private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(move.node, true);
if ( ! couldMarkRetiredNow) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
} | return false; | private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(move.node, true);
if ( ! couldMarkRetiredNow) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/** Returns true only if this operation changes the state of the wantToRetire flag */
private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/** Returns true only if this operation changes the state of the wantToRetire flag */
private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} |
The latter should be fine here. After lunch ... | private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(move.node, true);
if ( ! couldMarkRetiredNow) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
} | return false; | private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(move.node, true);
if ( ! couldMarkRetiredNow) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/** Returns true only if this operation changes the state of the wantToRetire flag */
private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/** Returns true only if this operation changes the state of the wantToRetire flag */
private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} |
This will kill all user tenants, since they aren't returned in that `accessibleTenants` method. Fine with me, but you should probably ask some other people too before doing this. | Set<Role> roles(AthenzPrincipal principal, URI uri) {
Path path = new Path(uri);
path.matches("/application/v4/tenant/{tenant}/{*}");
Optional<Tenant> tenant = Optional.ofNullable(path.get("tenant")).map(TenantName::from).flatMap(tenants::get);
path.matches("/application/v4/tenant/{tenant}/application/{application}/{*}");
Optional<ApplicationName> application = Optional.ofNullable(path.get("application")).map(ApplicationName::from);
path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/{*}");
Optional<InstanceName> instance = Optional.ofNullable(path.get("instance")).map(InstanceName::from);
AthenzIdentity identity = principal.getIdentity();
Set<Role> roleMemberships = new HashSet<>();
if (athenz.hasHostedOperatorAccess(identity))
roleMemberships.add(Role.hostedOperator());
athenz.accessibleTenants(tenants.asList(), new Credentials(principal))
.forEach(accessibleTenant -> roleMemberships.add(Role.athenzTenantAdmin(accessibleTenant.name())));
if (identity.getDomain().equals(SCREWDRIVER_DOMAIN) && application.isPresent() && tenant.isPresent())
if ( tenant.get().type() != Tenant.Type.athenz
|| hasDeployerAccess(identity, ((AthenzTenant) tenant.get()).domain(), application.get()))
roleMemberships.add(Role.tenantPipeline(tenant.get().name(), application.get()));
if ( tenant.isPresent() && application.isPresent() && instance.isPresent()
&& principal.getIdentity() instanceof AthenzUser
&& instance.get().value().equals(principal.getIdentity().getName()))
roleMemberships.add(Role.athenzUser(tenant.get().name(), application.get(), instance.get()));
if (athenz.hasSystemFlagsAccess(identity, /*dryrun*/false)) {
roleMemberships.add(Role.systemFlagsDeployer());
}
if (athenz.hasSystemFlagsAccess(identity, /*dryrun*/true)) {
roleMemberships.add(Role.systemFlagsDryrunner());
}
return roleMemberships.isEmpty()
? Set.of(Role.everyone())
: Set.copyOf(roleMemberships);
} | .forEach(accessibleTenant -> roleMemberships.add(Role.athenzTenantAdmin(accessibleTenant.name()))); | Set<Role> roles(AthenzPrincipal principal, URI uri) {
Path path = new Path(uri);
path.matches("/application/v4/tenant/{tenant}/{*}");
Optional<Tenant> tenant = Optional.ofNullable(path.get("tenant")).map(TenantName::from).flatMap(tenants::get);
path.matches("/application/v4/tenant/{tenant}/application/{application}/{*}");
Optional<ApplicationName> application = Optional.ofNullable(path.get("application")).map(ApplicationName::from);
path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/{*}");
Optional<InstanceName> instance = Optional.ofNullable(path.get("instance")).map(InstanceName::from);
AthenzIdentity identity = principal.getIdentity();
Set<Role> roleMemberships = new HashSet<>();
if (athenz.hasHostedOperatorAccess(identity))
roleMemberships.add(Role.hostedOperator());
athenz.accessibleTenants(tenants.asList(), new Credentials(principal))
.forEach(accessibleTenant -> roleMemberships.add(Role.athenzTenantAdmin(accessibleTenant.name())));
if (identity.getDomain().equals(SCREWDRIVER_DOMAIN) && application.isPresent() && tenant.isPresent())
if ( tenant.get().type() != Tenant.Type.athenz
|| hasDeployerAccess(identity, ((AthenzTenant) tenant.get()).domain(), application.get()))
roleMemberships.add(Role.tenantPipeline(tenant.get().name(), application.get()));
if ( tenant.isPresent() && application.isPresent() && instance.isPresent()
&& principal.getIdentity() instanceof AthenzUser
&& instance.get().value().equals(principal.getIdentity().getName()))
roleMemberships.add(Role.athenzUser(tenant.get().name(), application.get(), instance.get()));
if (athenz.hasSystemFlagsAccess(identity, /*dryrun*/false)) {
roleMemberships.add(Role.systemFlagsDeployer());
}
if (athenz.hasSystemFlagsAccess(identity, /*dryrun*/true)) {
roleMemberships.add(Role.systemFlagsDryrunner());
}
return roleMemberships.isEmpty()
? Set.of(Role.everyone())
: Set.copyOf(roleMemberships);
} | class AthenzRoleFilter extends JsonSecurityRequestFilterBase {
private static final Logger logger = Logger.getLogger(AthenzRoleFilter.class.getName());
private final AthenzFacade athenz;
private final TenantController tenants;
@Inject
public AthenzRoleFilter(AthenzClientFactory athenzClientFactory, Controller controller) {
this.athenz = new AthenzFacade(athenzClientFactory);
this.tenants = controller.tenants();
}
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
try {
Principal principal = request.getUserPrincipal();
if (principal instanceof AthenzPrincipal) {
request.setAttribute(SecurityContext.ATTRIBUTE_NAME, new SecurityContext(principal,
roles((AthenzPrincipal) principal,
request.getUri())));
}
}
catch (Exception e) {
logger.log(LogLevel.INFO, () -> "Exception mapping Athenz principal to roles: " + Exceptions.toMessageString(e));
}
return Optional.empty();
}
private boolean hasDeployerAccess(AthenzIdentity identity, AthenzDomain tenantDomain, ApplicationName application) {
try {
return athenz.hasApplicationAccess(identity,
ApplicationAction.deploy,
tenantDomain,
application);
} catch (ZmsClientException e) {
throw new RuntimeException("Failed to authorize operation: (" + e.getMessage() + ")", e);
}
}
} | class AthenzRoleFilter extends JsonSecurityRequestFilterBase {
private static final Logger logger = Logger.getLogger(AthenzRoleFilter.class.getName());
private final AthenzFacade athenz;
private final TenantController tenants;
@Inject
public AthenzRoleFilter(AthenzClientFactory athenzClientFactory, Controller controller) {
this.athenz = new AthenzFacade(athenzClientFactory);
this.tenants = controller.tenants();
}
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
try {
Principal principal = request.getUserPrincipal();
if (principal instanceof AthenzPrincipal) {
request.setAttribute(SecurityContext.ATTRIBUTE_NAME, new SecurityContext(principal,
roles((AthenzPrincipal) principal,
request.getUri())));
}
}
catch (Exception e) {
logger.log(LogLevel.INFO, () -> "Exception mapping Athenz principal to roles: " + Exceptions.toMessageString(e));
}
return Optional.empty();
}
private boolean hasDeployerAccess(AthenzIdentity identity, AthenzDomain tenantDomain, ApplicationName application) {
try {
return athenz.hasApplicationAccess(identity,
ApplicationAction.deploy,
tenantDomain,
application);
} catch (ZmsClientException e) {
throw new RuntimeException("Failed to authorize operation: (" + e.getMessage() + ")", e);
}
}
} |
https://github.com/vespa-engine/vespa/pull/11355 | private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(move.node, true);
if ( ! couldMarkRetiredNow) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
} | return false; | private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(move.node, true);
if ( ! couldMarkRetiredNow) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/** Returns true only if this operation changes the state of the wantToRetire flag */
private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/** Returns true only if this operation changes the state of the wantToRetire flag */
private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} |
What does this cover? | private Set<EndpointId> endpointIdsOf(LoadBalancer loadBalancer) {
if (zone.environment().isManuallyDeployed()) {
return Set.of();
}
var instanceSpec = deploymentSpec.instance(loadBalancer.application().instance());
if (instanceSpec.isEmpty()) {
return Set.of();
}
return instanceSpec.get().endpoints().stream()
.filter(endpoint -> endpoint.containerId().equals(loadBalancer.cluster().value()))
.filter(endpoint -> endpoint.regions().contains(zone.region()))
.map(com.yahoo.config.application.api.Endpoint::endpointId)
.map(EndpointId::of)
.collect(Collectors.toSet());
} | if (instanceSpec.isEmpty()) { | private Set<EndpointId> endpointIdsOf(LoadBalancer loadBalancer) {
if (zone.environment().isManuallyDeployed()) {
return Set.of();
}
var instanceSpec = deploymentSpec.instance(loadBalancer.application().instance());
if (instanceSpec.isEmpty()) {
return Set.of();
}
return instanceSpec.get().endpoints().stream()
.filter(endpoint -> endpoint.containerId().equals(loadBalancer.cluster().value()))
.filter(endpoint -> endpoint.regions().contains(zone.region()))
.map(com.yahoo.config.application.api.Endpoint::endpointId)
.map(EndpointId::of)
.collect(Collectors.toSet());
} | class AllocatedLoadBalancers {
private final ApplicationId application;
private final ZoneId zone;
private final List<LoadBalancer> list;
private final DeploymentSpec deploymentSpec;
private AllocatedLoadBalancers(ApplicationId application, ZoneId zone, List<LoadBalancer> loadBalancers,
DeploymentSpec deploymentSpec) {
this.application = application;
this.zone = zone;
this.list = loadBalancers.stream()
.filter(AllocatedLoadBalancers::shouldUpdatePolicy)
.collect(Collectors.toUnmodifiableList());
this.deploymentSpec = deploymentSpec;
}
/** Compute all endpoint IDs for given load balancer */
private static boolean shouldUpdatePolicy(LoadBalancer loadBalancer) {
switch (loadBalancer.state()) {
case active:
case reserved:
return true;
}
return false;
}
} | class AllocatedLoadBalancers {
private final ApplicationId application;
private final ZoneId zone;
private final List<LoadBalancer> list;
private final DeploymentSpec deploymentSpec;
private AllocatedLoadBalancers(ApplicationId application, ZoneId zone, List<LoadBalancer> loadBalancers,
DeploymentSpec deploymentSpec) {
this.application = application;
this.zone = zone;
this.list = loadBalancers.stream()
.filter(AllocatedLoadBalancers::shouldUpdatePolicy)
.collect(Collectors.toUnmodifiableList());
this.deploymentSpec = deploymentSpec;
}
/** Compute all endpoint IDs for given load balancer */
private static boolean shouldUpdatePolicy(LoadBalancer loadBalancer) {
switch (loadBalancer.state()) {
case active:
case reserved:
return true;
}
return false;
}
} |
It's an `Optional`. | private Set<EndpointId> endpointIdsOf(LoadBalancer loadBalancer) {
if (zone.environment().isManuallyDeployed()) {
return Set.of();
}
var instanceSpec = deploymentSpec.instance(loadBalancer.application().instance());
if (instanceSpec.isEmpty()) {
return Set.of();
}
return instanceSpec.get().endpoints().stream()
.filter(endpoint -> endpoint.containerId().equals(loadBalancer.cluster().value()))
.filter(endpoint -> endpoint.regions().contains(zone.region()))
.map(com.yahoo.config.application.api.Endpoint::endpointId)
.map(EndpointId::of)
.collect(Collectors.toSet());
} | if (instanceSpec.isEmpty()) { | private Set<EndpointId> endpointIdsOf(LoadBalancer loadBalancer) {
if (zone.environment().isManuallyDeployed()) {
return Set.of();
}
var instanceSpec = deploymentSpec.instance(loadBalancer.application().instance());
if (instanceSpec.isEmpty()) {
return Set.of();
}
return instanceSpec.get().endpoints().stream()
.filter(endpoint -> endpoint.containerId().equals(loadBalancer.cluster().value()))
.filter(endpoint -> endpoint.regions().contains(zone.region()))
.map(com.yahoo.config.application.api.Endpoint::endpointId)
.map(EndpointId::of)
.collect(Collectors.toSet());
} | class AllocatedLoadBalancers {
private final ApplicationId application;
private final ZoneId zone;
private final List<LoadBalancer> list;
private final DeploymentSpec deploymentSpec;
private AllocatedLoadBalancers(ApplicationId application, ZoneId zone, List<LoadBalancer> loadBalancers,
DeploymentSpec deploymentSpec) {
this.application = application;
this.zone = zone;
this.list = loadBalancers.stream()
.filter(AllocatedLoadBalancers::shouldUpdatePolicy)
.collect(Collectors.toUnmodifiableList());
this.deploymentSpec = deploymentSpec;
}
/** Compute all endpoint IDs for given load balancer */
private static boolean shouldUpdatePolicy(LoadBalancer loadBalancer) {
switch (loadBalancer.state()) {
case active:
case reserved:
return true;
}
return false;
}
} | class AllocatedLoadBalancers {
private final ApplicationId application;
private final ZoneId zone;
private final List<LoadBalancer> list;
private final DeploymentSpec deploymentSpec;
private AllocatedLoadBalancers(ApplicationId application, ZoneId zone, List<LoadBalancer> loadBalancers,
DeploymentSpec deploymentSpec) {
this.application = application;
this.zone = zone;
this.list = loadBalancers.stream()
.filter(AllocatedLoadBalancers::shouldUpdatePolicy)
.collect(Collectors.toUnmodifiableList());
this.deploymentSpec = deploymentSpec;
}
/** Compute all endpoint IDs for given load balancer */
private static boolean shouldUpdatePolicy(LoadBalancer loadBalancer) {
switch (loadBalancer.state()) {
case active:
case reserved:
return true;
}
return false;
}
} |
Yes. When would it not be present? All automatic deployments will be for instances that are given in the deployment spec. All others should be covered above. | private Set<EndpointId> endpointIdsOf(LoadBalancer loadBalancer) {
if (zone.environment().isManuallyDeployed()) {
return Set.of();
}
var instanceSpec = deploymentSpec.instance(loadBalancer.application().instance());
if (instanceSpec.isEmpty()) {
return Set.of();
}
return instanceSpec.get().endpoints().stream()
.filter(endpoint -> endpoint.containerId().equals(loadBalancer.cluster().value()))
.filter(endpoint -> endpoint.regions().contains(zone.region()))
.map(com.yahoo.config.application.api.Endpoint::endpointId)
.map(EndpointId::of)
.collect(Collectors.toSet());
} | if (instanceSpec.isEmpty()) { | private Set<EndpointId> endpointIdsOf(LoadBalancer loadBalancer) {
if (zone.environment().isManuallyDeployed()) {
return Set.of();
}
var instanceSpec = deploymentSpec.instance(loadBalancer.application().instance());
if (instanceSpec.isEmpty()) {
return Set.of();
}
return instanceSpec.get().endpoints().stream()
.filter(endpoint -> endpoint.containerId().equals(loadBalancer.cluster().value()))
.filter(endpoint -> endpoint.regions().contains(zone.region()))
.map(com.yahoo.config.application.api.Endpoint::endpointId)
.map(EndpointId::of)
.collect(Collectors.toSet());
} | class AllocatedLoadBalancers {
private final ApplicationId application;
private final ZoneId zone;
private final List<LoadBalancer> list;
private final DeploymentSpec deploymentSpec;
private AllocatedLoadBalancers(ApplicationId application, ZoneId zone, List<LoadBalancer> loadBalancers,
DeploymentSpec deploymentSpec) {
this.application = application;
this.zone = zone;
this.list = loadBalancers.stream()
.filter(AllocatedLoadBalancers::shouldUpdatePolicy)
.collect(Collectors.toUnmodifiableList());
this.deploymentSpec = deploymentSpec;
}
/** Compute all endpoint IDs for given load balancer */
private static boolean shouldUpdatePolicy(LoadBalancer loadBalancer) {
switch (loadBalancer.state()) {
case active:
case reserved:
return true;
}
return false;
}
} | class AllocatedLoadBalancers {
private final ApplicationId application;
private final ZoneId zone;
private final List<LoadBalancer> list;
private final DeploymentSpec deploymentSpec;
private AllocatedLoadBalancers(ApplicationId application, ZoneId zone, List<LoadBalancer> loadBalancers,
DeploymentSpec deploymentSpec) {
this.application = application;
this.zone = zone;
this.list = loadBalancers.stream()
.filter(AllocatedLoadBalancers::shouldUpdatePolicy)
.collect(Collectors.toUnmodifiableList());
this.deploymentSpec = deploymentSpec;
}
/** Compute all endpoint IDs for given load balancer */
private static boolean shouldUpdatePolicy(LoadBalancer loadBalancer) {
switch (loadBalancer.state()) {
case active:
case reserved:
return true;
}
return false;
}
} |
Sure, I can make it throw instead (in future PR). | private Set<EndpointId> endpointIdsOf(LoadBalancer loadBalancer) {
if (zone.environment().isManuallyDeployed()) {
return Set.of();
}
var instanceSpec = deploymentSpec.instance(loadBalancer.application().instance());
if (instanceSpec.isEmpty()) {
return Set.of();
}
return instanceSpec.get().endpoints().stream()
.filter(endpoint -> endpoint.containerId().equals(loadBalancer.cluster().value()))
.filter(endpoint -> endpoint.regions().contains(zone.region()))
.map(com.yahoo.config.application.api.Endpoint::endpointId)
.map(EndpointId::of)
.collect(Collectors.toSet());
} | if (instanceSpec.isEmpty()) { | private Set<EndpointId> endpointIdsOf(LoadBalancer loadBalancer) {
if (zone.environment().isManuallyDeployed()) {
return Set.of();
}
var instanceSpec = deploymentSpec.instance(loadBalancer.application().instance());
if (instanceSpec.isEmpty()) {
return Set.of();
}
return instanceSpec.get().endpoints().stream()
.filter(endpoint -> endpoint.containerId().equals(loadBalancer.cluster().value()))
.filter(endpoint -> endpoint.regions().contains(zone.region()))
.map(com.yahoo.config.application.api.Endpoint::endpointId)
.map(EndpointId::of)
.collect(Collectors.toSet());
} | class AllocatedLoadBalancers {
private final ApplicationId application;
private final ZoneId zone;
private final List<LoadBalancer> list;
private final DeploymentSpec deploymentSpec;
private AllocatedLoadBalancers(ApplicationId application, ZoneId zone, List<LoadBalancer> loadBalancers,
DeploymentSpec deploymentSpec) {
this.application = application;
this.zone = zone;
this.list = loadBalancers.stream()
.filter(AllocatedLoadBalancers::shouldUpdatePolicy)
.collect(Collectors.toUnmodifiableList());
this.deploymentSpec = deploymentSpec;
}
/** Compute all endpoint IDs for given load balancer */
private static boolean shouldUpdatePolicy(LoadBalancer loadBalancer) {
switch (loadBalancer.state()) {
case active:
case reserved:
return true;
}
return false;
}
} | class AllocatedLoadBalancers {
private final ApplicationId application;
private final ZoneId zone;
private final List<LoadBalancer> list;
private final DeploymentSpec deploymentSpec;
private AllocatedLoadBalancers(ApplicationId application, ZoneId zone, List<LoadBalancer> loadBalancers,
DeploymentSpec deploymentSpec) {
this.application = application;
this.zone = zone;
this.list = loadBalancers.stream()
.filter(AllocatedLoadBalancers::shouldUpdatePolicy)
.collect(Collectors.toUnmodifiableList());
this.deploymentSpec = deploymentSpec;
}
/** Compute all endpoint IDs for given load balancer */
private static boolean shouldUpdatePolicy(LoadBalancer loadBalancer) {
switch (loadBalancer.state()) {
case active:
case reserved:
return true;
}
return false;
}
} |
```suggestion markWantToRetire(move.node, false); // Necessary if this failed, no-op otherwise ``` `markWantToRetire()` will get the node after taking the lock anyway... | private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(Optional.of(move.node), true);
if ( ! couldMarkRetiredNow) return false;
Optional<Node> expectedNewNode = Optional.empty();
try {
if ( ! deployment.prepare()) return false;
expectedNewNode =
nodeRepository().getNodes(application, Node.State.reserved).stream()
.filter(node -> node.hasParent(move.toHost.hostname()))
.filter(node -> node.allocation().get().membership().cluster().id().equals(move.node.allocation().get().membership().cluster().id()))
.findAny();
if (expectedNewNode.isEmpty()) return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(nodeRepository().getNode(move.node.hostname()), false);
if (expectedNewNode.isPresent()) {
Optional<Node> reservedNewNode = nodeRepository().getNode(expectedNewNode.get().hostname(), Node.State.reserved);
reservedNewNode.ifPresent(reserved -> nodeRepository().setDirty(reserved, Agent.system, "Expired by Rebalancer"));
}
}
}
} | markWantToRetire(nodeRepository().getNode(move.node.hostname()), false); | private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(move.node, true);
if ( ! couldMarkRetiredNow) return false;
Optional<Node> expectedNewNode = Optional.empty();
try {
if ( ! deployment.prepare()) return false;
expectedNewNode =
nodeRepository().getNodes(application, Node.State.reserved).stream()
.filter(node -> node.hasParent(move.toHost.hostname()))
.filter(node -> node.allocation().get().membership().cluster().id().equals(move.node.allocation().get().membership().cluster().id()))
.findAny();
if (expectedNewNode.isEmpty()) return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
if (expectedNewNode.isPresent()) {
Optional<Node> reservedNewNode = nodeRepository().getNode(expectedNewNode.get().hostname(), Node.State.reserved);
reservedNewNode.ifPresent(reserved -> nodeRepository().setDirty(reserved, Agent.system, "Expired by Rebalancer"));
}
}
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
if (node.allocation().get().owner().instance().isTester()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/** Returns true only if this operation changes the state of the wantToRetire flag */
private boolean markWantToRetire(Optional<Node> node, boolean wantToRetire) {
if (node.isEmpty()) return false;
try (Mutex lock = nodeRepository().lock(node.get())) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.get().hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (nodeToMove.get().status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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 Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
if (node.allocation().get().owner().instance().isTester()) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
}
/** Returns true only if this operation changes the state of the wantToRetire flag */
private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (nodeToMove.get().status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} |
I think you should look up in rankFeatures instead of rankProperties. | private void validate(NearestNeighborItem item) {
int target = item.getTargetNumHits();
if (target < 1) {
setError(item.toString() + " has invalid targetNumHits");
return;
}
String qprop = item.getQueryRankFeatureName();
List<Object> rankPropValList = rankProperties.asMap().get(qprop);
if (rankPropValList == null) {
setError(item.toString() + " query property not found");
return;
}
if (rankPropValList.size() != 1) {
setError(item.toString() + " query property does not have a single value");
return;
}
Object rankPropValue = rankPropValList.get(0);
if (! (rankPropValue instanceof Tensor)) {
setError(item.toString() + " query property should be a tensor, was: "+rankPropValue);
return;
}
Tensor qTensor = (Tensor)rankPropValue;
TensorType qTensorType = qTensor.type();
String field = item.getIndexName();
if (validAttributes.containsKey(field)) {
TensorType fTensorType = validAttributes.get(field);
if (fTensorType == null) {
setError(item.toString() + " field is not a tensor");
return;
}
if (! fTensorType.equals(qTensorType)) {
setError(item.toString() + " field type "+fTensorType+" does not match query property type "+qTensorType);
return;
}
} else {
setError(item.toString() + " field is not an attribute");
return;
}
} | List<Object> rankPropValList = rankProperties.asMap().get(qprop); | private void validate(NearestNeighborItem item) {
int target = item.getTargetNumHits();
if (target < 1) {
setError(item.toString() + " has invalid targetNumHits");
return;
}
String qprop = item.getQueryTensorName();
List<Object> rankPropValList = rankProperties.asMap().get(qprop);
if (rankPropValList == null) {
setError(item.toString() + " query tensor not found");
return;
}
if (rankPropValList.size() != 1) {
setError(item.toString() + " query tensor does not have a single value");
return;
}
Object rankPropValue = rankPropValList.get(0);
if (! (rankPropValue instanceof Tensor)) {
setError(item.toString() + " query tensor should be a tensor, was: "+
(rankPropValue == null ? "null" : rankPropValue.getClass().toString()));
return;
}
Tensor qTensor = (Tensor)rankPropValue;
TensorType qTensorType = qTensor.type();
String field = item.getIndexName();
if (validAttributes.containsKey(field)) {
TensorType fTensorType = validAttributes.get(field);
if (fTensorType == null) {
setError(item.toString() + " field is not a tensor");
return;
}
if (! fTensorType.equals(qTensorType)) {
setError(item.toString() + " field type "+fTensorType+" does not match query tensor type "+qTensorType);
return;
}
if (! isDenseVector(fTensorType)) {
setError(item.toString() + " tensor type "+fTensorType+" is not a dense vector");
return;
}
} else {
setError(item.toString() + " field is not an attribute");
return;
}
} | class NNVisitor extends ToolBox.QueryVisitor {
public Optional<ErrorMessage> errorMessage = Optional.empty();
private RankProperties rankProperties;
private Map<String, TensorType> validAttributes;
public NNVisitor(RankProperties rankProperties, Map<String, TensorType> validAttributes) {
this.rankProperties = rankProperties;
this.validAttributes = validAttributes;
}
@Override
public boolean visit(Item item) {
if (item instanceof NearestNeighborItem) {
validate((NearestNeighborItem) item);
}
return true;
}
private void setError(String description) {
errorMessage = Optional.of(ErrorMessage.createIllegalQuery(description));
}
@Override
public void onExit() {}
} | class NNVisitor extends ToolBox.QueryVisitor {
public Optional<ErrorMessage> errorMessage = Optional.empty();
private RankProperties rankProperties;
private Map<String, TensorType> validAttributes;
public NNVisitor(RankProperties rankProperties, Map<String, TensorType> validAttributes) {
this.rankProperties = rankProperties;
this.validAttributes = validAttributes;
}
@Override
public boolean visit(Item item) {
if (item instanceof NearestNeighborItem) {
validate((NearestNeighborItem) item);
}
return true;
}
private void setError(String description) {
errorMessage = Optional.of(ErrorMessage.createIllegalQuery(description));
}
private static boolean isDenseVector(TensorType tt) {
List<TensorType.Dimension> dims = tt.dimensions();
if (dims.size() != 1) return false;
for (var d : dims) {
if (d.type() != TensorType.Dimension.Type.indexedBound) return false;
}
return true;
}
@Override
public void onExit() {}
} |
Please update to reflect name of member variable (queryTensorName?). | protected void appendBodyString(StringBuilder buffer) {
buffer.append("{field=").append(field);
buffer.append(",property=").append(property);
buffer.append(",targetNumHits=").append(targetNumber).append("}");
} | buffer.append(",property=").append(property); | protected void appendBodyString(StringBuilder buffer) {
buffer.append("{field=").append(field);
buffer.append(",queryTensorName=").append(queryTensorName);
buffer.append(",targetNumHits=").append(targetNumHits).append("}");
} | class NearestNeighborItem extends SimpleTaggableItem {
private int targetNumber = 0;
private String field;
private String property;
/** @return the K number of hits to produce */
public int getTargetNumHits() { return targetNumber; }
/** @return the field name */
public String getIndexName() { return field; }
/** @return the name of the query ranking feature */
public String getQueryRankFeatureName() { return property; }
public NearestNeighborItem(String fieldName, String queryRankFeatureName) {
this.field = fieldName;
this.property = queryRankFeatureName;
}
public void setTargetNumHits(int target) { this.targetNumber = target; }
@Override
public void setIndexName(String index) { this.field = index; }
@Override
public ItemType getItemType() { return ItemType.NEAREST_NEIGHBOR; }
@Override
public String getName() { return "NEAREST_NEIGHBOR"; }
@Override
public int getTermCount() { return 1; }
@Override
public int encode(ByteBuffer buffer) {
super.encodeThis(buffer);
putString(field, buffer);
putString(property, buffer);
IntegerCompressor.putCompressedPositiveNumber(targetNumber, buffer);
return 1;
}
@Override
} | class NearestNeighborItem extends SimpleTaggableItem {
private int targetNumHits = 0;
private String field;
private String queryTensorName;
public NearestNeighborItem(String fieldName, String queryTensorName) {
this.field = fieldName;
this.queryTensorName = queryTensorName;
}
/** Returns the K number of hits to produce */
public int getTargetNumHits() { return targetNumHits; }
/** Returns the field name */
public String getIndexName() { return field; }
/** Returns the name of the query tensor */
public String getQueryTensorName() { return queryTensorName; }
/** Set the K number of hits to produce */
public void setTargetNumHits(int target) { this.targetNumHits = target; }
@Override
public void setIndexName(String index) { this.field = index; }
@Override
public ItemType getItemType() { return ItemType.NEAREST_NEIGHBOR; }
@Override
public String getName() { return "NEAREST_NEIGHBOR"; }
@Override
public int getTermCount() { return 1; }
@Override
public int encode(ByteBuffer buffer) {
super.encodeThis(buffer);
putString(field, buffer);
putString(queryTensorName, buffer);
IntegerCompressor.putCompressedPositiveNumber(targetNumHits, buffer);
return 1;
}
@Override
} |
my first version did lookup in rankFeatures but the tensor wasn't there anymore; the "prepare" method in Ranking had been called by the time the validation was run, so it was moved to rankProperties, and renamed. This took some hours of hair-pulling to figure out. We think it's best to make a new searcher that only calls this prepare() step and add explicit constraints - in a separate PR. | private void validate(NearestNeighborItem item) {
int target = item.getTargetNumHits();
if (target < 1) {
setError(item.toString() + " has invalid targetNumHits");
return;
}
String qprop = item.getQueryRankFeatureName();
List<Object> rankPropValList = rankProperties.asMap().get(qprop);
if (rankPropValList == null) {
setError(item.toString() + " query property not found");
return;
}
if (rankPropValList.size() != 1) {
setError(item.toString() + " query property does not have a single value");
return;
}
Object rankPropValue = rankPropValList.get(0);
if (! (rankPropValue instanceof Tensor)) {
setError(item.toString() + " query property should be a tensor, was: "+rankPropValue);
return;
}
Tensor qTensor = (Tensor)rankPropValue;
TensorType qTensorType = qTensor.type();
String field = item.getIndexName();
if (validAttributes.containsKey(field)) {
TensorType fTensorType = validAttributes.get(field);
if (fTensorType == null) {
setError(item.toString() + " field is not a tensor");
return;
}
if (! fTensorType.equals(qTensorType)) {
setError(item.toString() + " field type "+fTensorType+" does not match query property type "+qTensorType);
return;
}
} else {
setError(item.toString() + " field is not an attribute");
return;
}
} | List<Object> rankPropValList = rankProperties.asMap().get(qprop); | private void validate(NearestNeighborItem item) {
int target = item.getTargetNumHits();
if (target < 1) {
setError(item.toString() + " has invalid targetNumHits");
return;
}
String qprop = item.getQueryTensorName();
List<Object> rankPropValList = rankProperties.asMap().get(qprop);
if (rankPropValList == null) {
setError(item.toString() + " query tensor not found");
return;
}
if (rankPropValList.size() != 1) {
setError(item.toString() + " query tensor does not have a single value");
return;
}
Object rankPropValue = rankPropValList.get(0);
if (! (rankPropValue instanceof Tensor)) {
setError(item.toString() + " query tensor should be a tensor, was: "+
(rankPropValue == null ? "null" : rankPropValue.getClass().toString()));
return;
}
Tensor qTensor = (Tensor)rankPropValue;
TensorType qTensorType = qTensor.type();
String field = item.getIndexName();
if (validAttributes.containsKey(field)) {
TensorType fTensorType = validAttributes.get(field);
if (fTensorType == null) {
setError(item.toString() + " field is not a tensor");
return;
}
if (! fTensorType.equals(qTensorType)) {
setError(item.toString() + " field type "+fTensorType+" does not match query tensor type "+qTensorType);
return;
}
if (! isDenseVector(fTensorType)) {
setError(item.toString() + " tensor type "+fTensorType+" is not a dense vector");
return;
}
} else {
setError(item.toString() + " field is not an attribute");
return;
}
} | class NNVisitor extends ToolBox.QueryVisitor {
public Optional<ErrorMessage> errorMessage = Optional.empty();
private RankProperties rankProperties;
private Map<String, TensorType> validAttributes;
public NNVisitor(RankProperties rankProperties, Map<String, TensorType> validAttributes) {
this.rankProperties = rankProperties;
this.validAttributes = validAttributes;
}
@Override
public boolean visit(Item item) {
if (item instanceof NearestNeighborItem) {
validate((NearestNeighborItem) item);
}
return true;
}
private void setError(String description) {
errorMessage = Optional.of(ErrorMessage.createIllegalQuery(description));
}
@Override
public void onExit() {}
} | class NNVisitor extends ToolBox.QueryVisitor {
public Optional<ErrorMessage> errorMessage = Optional.empty();
private RankProperties rankProperties;
private Map<String, TensorType> validAttributes;
public NNVisitor(RankProperties rankProperties, Map<String, TensorType> validAttributes) {
this.rankProperties = rankProperties;
this.validAttributes = validAttributes;
}
@Override
public boolean visit(Item item) {
if (item instanceof NearestNeighborItem) {
validate((NearestNeighborItem) item);
}
return true;
}
private void setError(String description) {
errorMessage = Optional.of(ErrorMessage.createIllegalQuery(description));
}
private static boolean isDenseVector(TensorType tt) {
List<TensorType.Dimension> dims = tt.dimensions();
if (dims.size() != 1) return false;
for (var d : dims) {
if (d.type() != TensorType.Dimension.Type.indexedBound) return false;
}
return true;
}
@Override
public void onExit() {}
} |
Yes, that stuff is a flacking mess :-/ Might be better to wait with cleanup until we can remove the old query binary serialization? You can add a constraint to be before the spot where this transformation happens. | private void validate(NearestNeighborItem item) {
int target = item.getTargetNumHits();
if (target < 1) {
setError(item.toString() + " has invalid targetNumHits");
return;
}
String qprop = item.getQueryRankFeatureName();
List<Object> rankPropValList = rankProperties.asMap().get(qprop);
if (rankPropValList == null) {
setError(item.toString() + " query property not found");
return;
}
if (rankPropValList.size() != 1) {
setError(item.toString() + " query property does not have a single value");
return;
}
Object rankPropValue = rankPropValList.get(0);
if (! (rankPropValue instanceof Tensor)) {
setError(item.toString() + " query property should be a tensor, was: "+rankPropValue);
return;
}
Tensor qTensor = (Tensor)rankPropValue;
TensorType qTensorType = qTensor.type();
String field = item.getIndexName();
if (validAttributes.containsKey(field)) {
TensorType fTensorType = validAttributes.get(field);
if (fTensorType == null) {
setError(item.toString() + " field is not a tensor");
return;
}
if (! fTensorType.equals(qTensorType)) {
setError(item.toString() + " field type "+fTensorType+" does not match query property type "+qTensorType);
return;
}
} else {
setError(item.toString() + " field is not an attribute");
return;
}
} | List<Object> rankPropValList = rankProperties.asMap().get(qprop); | private void validate(NearestNeighborItem item) {
int target = item.getTargetNumHits();
if (target < 1) {
setError(item.toString() + " has invalid targetNumHits");
return;
}
String qprop = item.getQueryTensorName();
List<Object> rankPropValList = rankProperties.asMap().get(qprop);
if (rankPropValList == null) {
setError(item.toString() + " query tensor not found");
return;
}
if (rankPropValList.size() != 1) {
setError(item.toString() + " query tensor does not have a single value");
return;
}
Object rankPropValue = rankPropValList.get(0);
if (! (rankPropValue instanceof Tensor)) {
setError(item.toString() + " query tensor should be a tensor, was: "+
(rankPropValue == null ? "null" : rankPropValue.getClass().toString()));
return;
}
Tensor qTensor = (Tensor)rankPropValue;
TensorType qTensorType = qTensor.type();
String field = item.getIndexName();
if (validAttributes.containsKey(field)) {
TensorType fTensorType = validAttributes.get(field);
if (fTensorType == null) {
setError(item.toString() + " field is not a tensor");
return;
}
if (! fTensorType.equals(qTensorType)) {
setError(item.toString() + " field type "+fTensorType+" does not match query tensor type "+qTensorType);
return;
}
if (! isDenseVector(fTensorType)) {
setError(item.toString() + " tensor type "+fTensorType+" is not a dense vector");
return;
}
} else {
setError(item.toString() + " field is not an attribute");
return;
}
} | class NNVisitor extends ToolBox.QueryVisitor {
public Optional<ErrorMessage> errorMessage = Optional.empty();
private RankProperties rankProperties;
private Map<String, TensorType> validAttributes;
public NNVisitor(RankProperties rankProperties, Map<String, TensorType> validAttributes) {
this.rankProperties = rankProperties;
this.validAttributes = validAttributes;
}
@Override
public boolean visit(Item item) {
if (item instanceof NearestNeighborItem) {
validate((NearestNeighborItem) item);
}
return true;
}
private void setError(String description) {
errorMessage = Optional.of(ErrorMessage.createIllegalQuery(description));
}
@Override
public void onExit() {}
} | class NNVisitor extends ToolBox.QueryVisitor {
public Optional<ErrorMessage> errorMessage = Optional.empty();
private RankProperties rankProperties;
private Map<String, TensorType> validAttributes;
public NNVisitor(RankProperties rankProperties, Map<String, TensorType> validAttributes) {
this.rankProperties = rankProperties;
this.validAttributes = validAttributes;
}
@Override
public boolean visit(Item item) {
if (item instanceof NearestNeighborItem) {
validate((NearestNeighborItem) item);
}
return true;
}
private void setError(String description) {
errorMessage = Optional.of(ErrorMessage.createIllegalQuery(description));
}
private static boolean isDenseVector(TensorType tt) {
List<TensorType.Dimension> dims = tt.dimensions();
if (dims.size() != 1) return false;
for (var d : dims) {
if (d.type() != TensorType.Dimension.Type.indexedBound) return false;
}
return true;
}
@Override
public void onExit() {}
} |
query.prepare() is only called from GroupingExecutor as far as i can see; that seems like a disaster waiting to happen... | private void validate(NearestNeighborItem item) {
int target = item.getTargetNumHits();
if (target < 1) {
setError(item.toString() + " has invalid targetNumHits");
return;
}
String qprop = item.getQueryRankFeatureName();
List<Object> rankPropValList = rankProperties.asMap().get(qprop);
if (rankPropValList == null) {
setError(item.toString() + " query property not found");
return;
}
if (rankPropValList.size() != 1) {
setError(item.toString() + " query property does not have a single value");
return;
}
Object rankPropValue = rankPropValList.get(0);
if (! (rankPropValue instanceof Tensor)) {
setError(item.toString() + " query property should be a tensor, was: "+rankPropValue);
return;
}
Tensor qTensor = (Tensor)rankPropValue;
TensorType qTensorType = qTensor.type();
String field = item.getIndexName();
if (validAttributes.containsKey(field)) {
TensorType fTensorType = validAttributes.get(field);
if (fTensorType == null) {
setError(item.toString() + " field is not a tensor");
return;
}
if (! fTensorType.equals(qTensorType)) {
setError(item.toString() + " field type "+fTensorType+" does not match query property type "+qTensorType);
return;
}
} else {
setError(item.toString() + " field is not an attribute");
return;
}
} | List<Object> rankPropValList = rankProperties.asMap().get(qprop); | private void validate(NearestNeighborItem item) {
int target = item.getTargetNumHits();
if (target < 1) {
setError(item.toString() + " has invalid targetNumHits");
return;
}
String qprop = item.getQueryTensorName();
List<Object> rankPropValList = rankProperties.asMap().get(qprop);
if (rankPropValList == null) {
setError(item.toString() + " query tensor not found");
return;
}
if (rankPropValList.size() != 1) {
setError(item.toString() + " query tensor does not have a single value");
return;
}
Object rankPropValue = rankPropValList.get(0);
if (! (rankPropValue instanceof Tensor)) {
setError(item.toString() + " query tensor should be a tensor, was: "+
(rankPropValue == null ? "null" : rankPropValue.getClass().toString()));
return;
}
Tensor qTensor = (Tensor)rankPropValue;
TensorType qTensorType = qTensor.type();
String field = item.getIndexName();
if (validAttributes.containsKey(field)) {
TensorType fTensorType = validAttributes.get(field);
if (fTensorType == null) {
setError(item.toString() + " field is not a tensor");
return;
}
if (! fTensorType.equals(qTensorType)) {
setError(item.toString() + " field type "+fTensorType+" does not match query tensor type "+qTensorType);
return;
}
if (! isDenseVector(fTensorType)) {
setError(item.toString() + " tensor type "+fTensorType+" is not a dense vector");
return;
}
} else {
setError(item.toString() + " field is not an attribute");
return;
}
} | class NNVisitor extends ToolBox.QueryVisitor {
public Optional<ErrorMessage> errorMessage = Optional.empty();
private RankProperties rankProperties;
private Map<String, TensorType> validAttributes;
public NNVisitor(RankProperties rankProperties, Map<String, TensorType> validAttributes) {
this.rankProperties = rankProperties;
this.validAttributes = validAttributes;
}
@Override
public boolean visit(Item item) {
if (item instanceof NearestNeighborItem) {
validate((NearestNeighborItem) item);
}
return true;
}
private void setError(String description) {
errorMessage = Optional.of(ErrorMessage.createIllegalQuery(description));
}
@Override
public void onExit() {}
} | class NNVisitor extends ToolBox.QueryVisitor {
public Optional<ErrorMessage> errorMessage = Optional.empty();
private RankProperties rankProperties;
private Map<String, TensorType> validAttributes;
public NNVisitor(RankProperties rankProperties, Map<String, TensorType> validAttributes) {
this.rankProperties = rankProperties;
this.validAttributes = validAttributes;
}
@Override
public boolean visit(Item item) {
if (item instanceof NearestNeighborItem) {
validate((NearestNeighborItem) item);
}
return true;
}
private void setError(String description) {
errorMessage = Optional.of(ErrorMessage.createIllegalQuery(description));
}
private static boolean isDenseVector(TensorType tt) {
List<TensorType.Dimension> dims = tt.dimensions();
if (dims.size() != 1) return false;
for (var d : dims) {
if (d.type() != TensorType.Dimension.Type.indexedBound) return false;
}
return true;
}
@Override
public void onExit() {}
} |
done | protected void appendBodyString(StringBuilder buffer) {
buffer.append("{field=").append(field);
buffer.append(",property=").append(property);
buffer.append(",targetNumHits=").append(targetNumber).append("}");
} | buffer.append(",property=").append(property); | protected void appendBodyString(StringBuilder buffer) {
buffer.append("{field=").append(field);
buffer.append(",queryTensorName=").append(queryTensorName);
buffer.append(",targetNumHits=").append(targetNumHits).append("}");
} | class NearestNeighborItem extends SimpleTaggableItem {
private int targetNumber = 0;
private String field;
private String property;
/** @return the K number of hits to produce */
public int getTargetNumHits() { return targetNumber; }
/** @return the field name */
public String getIndexName() { return field; }
/** @return the name of the query ranking feature */
public String getQueryRankFeatureName() { return property; }
public NearestNeighborItem(String fieldName, String queryRankFeatureName) {
this.field = fieldName;
this.property = queryRankFeatureName;
}
public void setTargetNumHits(int target) { this.targetNumber = target; }
@Override
public void setIndexName(String index) { this.field = index; }
@Override
public ItemType getItemType() { return ItemType.NEAREST_NEIGHBOR; }
@Override
public String getName() { return "NEAREST_NEIGHBOR"; }
@Override
public int getTermCount() { return 1; }
@Override
public int encode(ByteBuffer buffer) {
super.encodeThis(buffer);
putString(field, buffer);
putString(property, buffer);
IntegerCompressor.putCompressedPositiveNumber(targetNumber, buffer);
return 1;
}
@Override
} | class NearestNeighborItem extends SimpleTaggableItem {
private int targetNumHits = 0;
private String field;
private String queryTensorName;
public NearestNeighborItem(String fieldName, String queryTensorName) {
this.field = fieldName;
this.queryTensorName = queryTensorName;
}
/** Returns the K number of hits to produce */
public int getTargetNumHits() { return targetNumHits; }
/** Returns the field name */
public String getIndexName() { return field; }
/** Returns the name of the query tensor */
public String getQueryTensorName() { return queryTensorName; }
/** Set the K number of hits to produce */
public void setTargetNumHits(int target) { this.targetNumHits = target; }
@Override
public void setIndexName(String index) { this.field = index; }
@Override
public ItemType getItemType() { return ItemType.NEAREST_NEIGHBOR; }
@Override
public String getName() { return "NEAREST_NEIGHBOR"; }
@Override
public int getTermCount() { return 1; }
@Override
public int encode(ByteBuffer buffer) {
super.encodeThis(buffer);
putString(field, buffer);
putString(queryTensorName, buffer);
IntegerCompressor.putCompressedPositiveNumber(targetNumHits, buffer);
return 1;
}
@Override
} |
Yep. | private void validate(NearestNeighborItem item) {
int target = item.getTargetNumHits();
if (target < 1) {
setError(item.toString() + " has invalid targetNumHits");
return;
}
String qprop = item.getQueryRankFeatureName();
List<Object> rankPropValList = rankProperties.asMap().get(qprop);
if (rankPropValList == null) {
setError(item.toString() + " query property not found");
return;
}
if (rankPropValList.size() != 1) {
setError(item.toString() + " query property does not have a single value");
return;
}
Object rankPropValue = rankPropValList.get(0);
if (! (rankPropValue instanceof Tensor)) {
setError(item.toString() + " query property should be a tensor, was: "+rankPropValue);
return;
}
Tensor qTensor = (Tensor)rankPropValue;
TensorType qTensorType = qTensor.type();
String field = item.getIndexName();
if (validAttributes.containsKey(field)) {
TensorType fTensorType = validAttributes.get(field);
if (fTensorType == null) {
setError(item.toString() + " field is not a tensor");
return;
}
if (! fTensorType.equals(qTensorType)) {
setError(item.toString() + " field type "+fTensorType+" does not match query property type "+qTensorType);
return;
}
} else {
setError(item.toString() + " field is not an attribute");
return;
}
} | List<Object> rankPropValList = rankProperties.asMap().get(qprop); | private void validate(NearestNeighborItem item) {
int target = item.getTargetNumHits();
if (target < 1) {
setError(item.toString() + " has invalid targetNumHits");
return;
}
String qprop = item.getQueryTensorName();
List<Object> rankPropValList = rankProperties.asMap().get(qprop);
if (rankPropValList == null) {
setError(item.toString() + " query tensor not found");
return;
}
if (rankPropValList.size() != 1) {
setError(item.toString() + " query tensor does not have a single value");
return;
}
Object rankPropValue = rankPropValList.get(0);
if (! (rankPropValue instanceof Tensor)) {
setError(item.toString() + " query tensor should be a tensor, was: "+
(rankPropValue == null ? "null" : rankPropValue.getClass().toString()));
return;
}
Tensor qTensor = (Tensor)rankPropValue;
TensorType qTensorType = qTensor.type();
String field = item.getIndexName();
if (validAttributes.containsKey(field)) {
TensorType fTensorType = validAttributes.get(field);
if (fTensorType == null) {
setError(item.toString() + " field is not a tensor");
return;
}
if (! fTensorType.equals(qTensorType)) {
setError(item.toString() + " field type "+fTensorType+" does not match query tensor type "+qTensorType);
return;
}
if (! isDenseVector(fTensorType)) {
setError(item.toString() + " tensor type "+fTensorType+" is not a dense vector");
return;
}
} else {
setError(item.toString() + " field is not an attribute");
return;
}
} | class NNVisitor extends ToolBox.QueryVisitor {
public Optional<ErrorMessage> errorMessage = Optional.empty();
private RankProperties rankProperties;
private Map<String, TensorType> validAttributes;
public NNVisitor(RankProperties rankProperties, Map<String, TensorType> validAttributes) {
this.rankProperties = rankProperties;
this.validAttributes = validAttributes;
}
@Override
public boolean visit(Item item) {
if (item instanceof NearestNeighborItem) {
validate((NearestNeighborItem) item);
}
return true;
}
private void setError(String description) {
errorMessage = Optional.of(ErrorMessage.createIllegalQuery(description));
}
@Override
public void onExit() {}
} | class NNVisitor extends ToolBox.QueryVisitor {
public Optional<ErrorMessage> errorMessage = Optional.empty();
private RankProperties rankProperties;
private Map<String, TensorType> validAttributes;
public NNVisitor(RankProperties rankProperties, Map<String, TensorType> validAttributes) {
this.rankProperties = rankProperties;
this.validAttributes = validAttributes;
}
@Override
public boolean visit(Item item) {
if (item instanceof NearestNeighborItem) {
validate((NearestNeighborItem) item);
}
return true;
}
private void setError(String description) {
errorMessage = Optional.of(ErrorMessage.createIllegalQuery(description));
}
private static boolean isDenseVector(TensorType tt) {
List<TensorType.Dimension> dims = tt.dimensions();
if (dims.size() != 1) return false;
for (var d : dims) {
if (d.type() != TensorType.Dimension.Type.indexedBound) return false;
}
return true;
}
@Override
public void onExit() {}
} |
Since this is just active nodes you can just say if (node.allocation().get().owner().instance().isTester())) continue; | private Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
if (node.allocation().map(allocation -> allocation.owner().instance().isTester()).orElse(false)) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
} | if (node.allocation().map(allocation -> allocation.owner().instance().isTester()).orElse(false)) continue; | private Move findBestMove(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
Move bestMove = Move.none;
for (Node node : allNodes.nodeType(NodeType.tenant).state(Node.State.active)) {
if (node.parentHostname().isEmpty()) continue;
if (node.allocation().get().owner().instance().isTester())) continue;
for (Node toHost : allNodes.nodeType(NodeType.host).state(NodePrioritizer.ALLOCATABLE_HOST_STATES)) {
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, toHost, netSkewReduction);
}
}
return bestMove;
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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.
*/
/** Returns true only if this operation changes the state of the wantToRetire flag */
private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(move.node, true);
if ( ! couldMarkRetiredNow) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
}
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} | class Rebalancer extends Maintainer {
private final Deployer deployer;
private final HostResourcesCalculator hostResourcesCalculator;
private final Optional<HostProvisioner> hostProvisioner;
private final Metric metric;
private final Clock clock;
public Rebalancer(Deployer deployer,
NodeRepository nodeRepository,
HostResourcesCalculator hostResourcesCalculator,
Optional<HostProvisioner> hostProvisioner,
Metric metric,
Clock clock,
Duration interval) {
super(nodeRepository, interval);
this.deployer = deployer;
this.hostResourcesCalculator = hostResourcesCalculator;
this.hostProvisioner = hostProvisioner;
this.metric = metric;
this.clock = clock;
}
@Override
protected void maintain() {
if (hostProvisioner.isPresent()) return;
NodeList allNodes = nodeRepository().list();
updateSkewMetric(allNodes);
if ( ! zoneIsStable(allNodes)) return;
Move bestMove = findBestMove(allNodes);
if (bestMove == Move.none) return;
deployTo(bestMove);
}
/** We do this here rather than in MetricsReporter because it is expensive and frequent updates are unnecessary */
private void updateSkewMetric(NodeList allNodes) {
DockerHostCapacity capacity = new DockerHostCapacity(allNodes, hostResourcesCalculator);
double totalSkew = 0;
int hostCount = 0;
for (Node host : allNodes.nodeType((NodeType.host)).state(Node.State.active)) {
hostCount++;
totalSkew += Node.skew(host.flavor().resources(), capacity.freeCapacityOf(host));
}
metric.set("hostedVespa.docker.skew", totalSkew/hostCount, null);
}
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.
*/
/** Returns true only if this operation changes the state of the wantToRetire flag */
private boolean markWantToRetire(Node node, boolean wantToRetire) {
try (Mutex lock = nodeRepository().lock(node)) {
Optional<Node> nodeToMove = nodeRepository().getNode(node.hostname());
if (nodeToMove.isEmpty()) return false;
if (nodeToMove.get().state() != Node.State.active) return false;
if (node.status().wantToRetire() == wantToRetire) return false;
nodeRepository().write(nodeToMove.get().withWantToRetire(wantToRetire, Agent.system, clock.instant()), lock);
return true;
}
}
/**
* Try a redeployment to effect the chosen move.
* If it can be done, that's ok; we'll try this or another move later.
*
* @return true if the move was done, false if it couldn't be
*/
private boolean deployTo(Move move) {
ApplicationId application = move.node.allocation().get().owner();
try (MaintenanceDeployment deployment = new MaintenanceDeployment(application, deployer, nodeRepository())) {
if ( ! deployment.isValid()) return false;
boolean couldMarkRetiredNow = markWantToRetire(move.node, true);
if ( ! couldMarkRetiredNow) return false;
try {
if ( ! deployment.prepare()) return false;
if (nodeRepository().getNodes(application, Node.State.reserved).stream().noneMatch(node -> node.hasParent(move.toHost.hostname())))
return false;
if ( ! deployment.activate()) return false;
log.info("Rebalancer redeployed " + application + " to " + move);
return true;
}
finally {
markWantToRetire(move.node, false);
}
}
}
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().justNumbers()));
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().justNumbers()));
return skewBefore - skewAfter;
}
private static class Move {
static final Move none = new Move(null, null, 0);
final Node node;
final Node toHost;
final double netSkewReduction;
Move(Node node, Node toHost, double netSkewReduction) {
this.node = node;
this.toHost = toHost;
this.netSkewReduction = netSkewReduction;
}
@Override
public String toString() {
return "move " +
( node == null ? "none" :
(node.hostname() + " to " + toHost + " [skew reduction " + netSkewReduction + "]"));
}
}
private static class MaintenanceDeployment implements Closeable {
private static final Logger log = Logger.getLogger(MaintenanceDeployment.class.getName());
private final ApplicationId application;
private final Optional<Mutex> lock;
private final Optional<Deployment> deployment;
public MaintenanceDeployment(ApplicationId application, Deployer deployer, NodeRepository nodeRepository) {
this.application = application;
lock = tryLock(application, nodeRepository);
deployment = tryDeployment(lock, application, deployer, nodeRepository);
}
/** Return whether this is - as yet - functional and can be used to carry out the deployment */
public boolean isValid() {
return deployment.isPresent();
}
private Optional<Mutex> tryLock(ApplicationId application, NodeRepository nodeRepository) {
try {
return Optional.of(nodeRepository.lock(application, Duration.ofSeconds(1)));
}
catch (ApplicationLockException e) {
return Optional.empty();
}
}
private Optional<Deployment> tryDeployment(Optional<Mutex> lock,
ApplicationId application,
Deployer deployer,
NodeRepository nodeRepository) {
if (lock.isEmpty()) return Optional.empty();
if (nodeRepository.getNodes(application, Node.State.active).isEmpty()) return Optional.empty();
return deployer.deployFromLocalActive(application);
}
public boolean prepare() {
return doStep(() -> deployment.get().prepare());
}
public boolean activate() {
return doStep(() -> deployment.get().activate());
}
private boolean doStep(Runnable action) {
if ( ! isValid()) return false;
try {
action.run();
return true;
} catch (TransientException e) {
log.log(LogLevel.INFO, "Failed to deploy " + application + " with a transient error: " +
Exceptions.toMessageString(e));
return false;
} catch (RuntimeException e) {
log.log(LogLevel.WARNING, "Exception on maintenance deploy of " + application, e);
return false;
}
}
@Override
public void close() {
lock.ifPresent(l -> l.close());
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.